test.cc 788 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571
  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. // Empty media type
  898. result.clear();
  899. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  900. // Only commas
  901. result.clear();
  902. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  903. // Valid cases should still work
  904. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*/*");
  907. EXPECT_TRUE(detail::parse_accept_header("*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "*");
  910. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  911. EXPECT_EQ(result.size(), 1U);
  912. EXPECT_EQ(result[0], "text/*");
  913. }
  914. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  915. Server svr;
  916. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  917. EXPECT_EQ(req.accept_content_types.size(), 3U);
  918. EXPECT_EQ(req.accept_content_types[0], "application/json");
  919. EXPECT_EQ(req.accept_content_types[1], "text/html");
  920. EXPECT_EQ(req.accept_content_types[2], "*/*");
  921. res.set_content("ok", "text/plain");
  922. });
  923. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  924. EXPECT_TRUE(false);
  925. res.set_content("bad request", "text/plain");
  926. });
  927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  928. auto se = detail::scope_exit([&] {
  929. svr.stop();
  930. listen_thread.join();
  931. ASSERT_FALSE(svr.is_running());
  932. });
  933. svr.wait_until_ready();
  934. Client cli("localhost", PORT);
  935. {
  936. auto res = cli.Get(
  937. "/accept_ok",
  938. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  940. EXPECT_EQ(StatusCode::OK_200, res->status);
  941. }
  942. {
  943. auto res = cli.Get("/accept_bad_request",
  944. Headers{{"Accept", "text/html;q=abc,application/json"}});
  945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  946. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  947. }
  948. }
  949. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  950. Server svr;
  951. svr.Get("/", [](const Request & /*req*/, Response &res) {
  952. res.set_content("ok", "text/plain");
  953. });
  954. std::atomic<int> start_count{0};
  955. std::atomic<bool> running_when_called{false};
  956. svr.set_start_handler([&]() {
  957. running_when_called = svr.is_running();
  958. start_count++;
  959. });
  960. auto port = svr.bind_to_any_port(HOST);
  961. std::thread t([&]() { svr.listen_after_bind(); });
  962. auto se = detail::scope_exit([&] {
  963. svr.stop();
  964. t.join();
  965. ASSERT_FALSE(svr.is_running());
  966. });
  967. svr.wait_until_ready();
  968. // A successful request proves the accept loop is running, which the start
  969. // handler precedes; so by now the handler must have run exactly once.
  970. Client cli(HOST, port);
  971. cli.set_connection_timeout(std::chrono::seconds(5));
  972. auto res = cli.Get("/");
  973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  974. EXPECT_EQ(StatusCode::OK_200, res->status);
  975. EXPECT_EQ(1, start_count.load());
  976. EXPECT_TRUE(running_when_called.load());
  977. }
  978. TEST(DivideTest, DivideStringTests) {
  979. auto divide = [](const std::string &str, char d) {
  980. std::string lhs;
  981. std::string rhs;
  982. detail::divide(str, d,
  983. [&](const char *lhs_data, std::size_t lhs_size,
  984. const char *rhs_data, std::size_t rhs_size) {
  985. lhs.assign(lhs_data, lhs_size);
  986. rhs.assign(rhs_data, rhs_size);
  987. });
  988. return std::make_pair(std::move(lhs), std::move(rhs));
  989. };
  990. {
  991. const auto res = divide("", '=');
  992. EXPECT_EQ(res.first, "");
  993. EXPECT_EQ(res.second, "");
  994. }
  995. {
  996. const auto res = divide("=", '=');
  997. EXPECT_EQ(res.first, "");
  998. EXPECT_EQ(res.second, "");
  999. }
  1000. {
  1001. const auto res = divide(" ", '=');
  1002. EXPECT_EQ(res.first, " ");
  1003. EXPECT_EQ(res.second, "");
  1004. }
  1005. {
  1006. const auto res = divide("a", '=');
  1007. EXPECT_EQ(res.first, "a");
  1008. EXPECT_EQ(res.second, "");
  1009. }
  1010. {
  1011. const auto res = divide("a=", '=');
  1012. EXPECT_EQ(res.first, "a");
  1013. EXPECT_EQ(res.second, "");
  1014. }
  1015. {
  1016. const auto res = divide("=b", '=');
  1017. EXPECT_EQ(res.first, "");
  1018. EXPECT_EQ(res.second, "b");
  1019. }
  1020. {
  1021. const auto res = divide("a=b", '=');
  1022. EXPECT_EQ(res.first, "a");
  1023. EXPECT_EQ(res.second, "b");
  1024. }
  1025. {
  1026. const auto res = divide("a=b=", '=');
  1027. EXPECT_EQ(res.first, "a");
  1028. EXPECT_EQ(res.second, "b=");
  1029. }
  1030. {
  1031. const auto res = divide("a=b=c", '=');
  1032. EXPECT_EQ(res.first, "a");
  1033. EXPECT_EQ(res.second, "b=c");
  1034. }
  1035. }
  1036. TEST(SplitTest, ParseQueryString) {
  1037. string s = "key1=val1&key2=val2&key3=val3";
  1038. Params dic;
  1039. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1040. [&](const char *b, const char *e) {
  1041. string key, val;
  1042. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1043. if (key.empty()) {
  1044. key.assign(b2, e2);
  1045. } else {
  1046. val.assign(b2, e2);
  1047. }
  1048. });
  1049. dic.emplace(key, val);
  1050. });
  1051. EXPECT_EQ("val1", dic.find("key1")->second);
  1052. EXPECT_EQ("val2", dic.find("key2")->second);
  1053. EXPECT_EQ("val3", dic.find("key3")->second);
  1054. }
  1055. TEST(SplitTest, ParseInvalidQueryTests) {
  1056. {
  1057. string s = " ";
  1058. Params dict;
  1059. detail::parse_query_text(s, dict);
  1060. EXPECT_TRUE(dict.empty());
  1061. }
  1062. {
  1063. string s = " = =";
  1064. Params dict;
  1065. detail::parse_query_text(s, dict);
  1066. EXPECT_TRUE(dict.empty());
  1067. }
  1068. }
  1069. TEST(ParseQueryTest, ParseQueryString) {
  1070. {
  1071. std::string s = "key1=val1&key2=val2&key3=val3";
  1072. Params dic;
  1073. detail::parse_query_text(s, dic);
  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. {
  1079. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1080. Params dic;
  1081. detail::parse_query_text(s, dic);
  1082. EXPECT_EQ("", dic.find("key1")->second);
  1083. EXPECT_EQ("val1", dic.find("key2")->second);
  1084. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1085. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1086. }
  1087. }
  1088. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1089. Params dic;
  1090. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1091. dic.emplace("key1", "val1");
  1092. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1093. dic.emplace("key2", "val2");
  1094. dic.emplace("key3", "val3");
  1095. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1096. }
  1097. // Joins every entry of a Headers or Params into "key=value " so a whole
  1098. // traversal can be compared in one assertion. Both are instantiations of the
  1099. // same insertion-ordered container, so one helper serves both.
  1100. template <typename Map> static std::string entries_to_string(const Map &m) {
  1101. std::string s;
  1102. for (const auto &entry : m) {
  1103. s += entry.first + "=" + entry.second + " ";
  1104. }
  1105. return s;
  1106. }
  1107. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1108. // Params used to be a std::multimap, which sorted by name and handed the
  1109. // caller's query back alphabetised. A client signing its query string could
  1110. // not reproduce the order it asked for.
  1111. Params dic;
  1112. dic.emplace("zulu", "1");
  1113. dic.emplace("alpha", "2");
  1114. dic.emplace("mike", "3");
  1115. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1116. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1117. }
  1118. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1119. Params dic;
  1120. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1121. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1122. }
  1123. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1124. Request req;
  1125. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1126. req.params);
  1127. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1128. EXPECT_EQ("first", req.get_param_value("tag"));
  1129. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1130. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1131. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1132. EXPECT_EQ("", req.get_param_value("tag", 3));
  1133. }
  1134. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1135. // Params shares its container with Headers, which matches field names
  1136. // case-insensitively. Parameter names must not pick that up.
  1137. Params dic;
  1138. dic.emplace("Key", "upper");
  1139. dic.emplace("key", "lower");
  1140. EXPECT_EQ(2U, dic.size());
  1141. EXPECT_EQ(1U, dic.count("Key"));
  1142. EXPECT_EQ(1U, dic.count("key"));
  1143. EXPECT_EQ("upper", dic.find("Key")->second);
  1144. EXPECT_EQ("lower", dic.find("key")->second);
  1145. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1146. }
  1147. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1148. Server svr;
  1149. std::string order;
  1150. svr.Get("/order", [&](const Request &req, Response &res) {
  1151. order = entries_to_string(req.params);
  1152. res.set_content("ok", "text/plain");
  1153. });
  1154. auto port = svr.bind_to_any_port(HOST);
  1155. thread t = thread([&] { svr.listen_after_bind(); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. t.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli(HOST, port);
  1163. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1166. }
  1167. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1168. Server svr;
  1169. std::string field_order, file_order;
  1170. svr.Post("/order", [&](const Request &req, Response &res) {
  1171. for (const auto &field : req.form.fields) {
  1172. field_order += field.first + "=" + field.second.content + " ";
  1173. }
  1174. for (const auto &file : req.form.files) {
  1175. file_order += file.first + "=" + file.second.filename + " ";
  1176. }
  1177. res.set_content("ok", "text/plain");
  1178. });
  1179. auto port = svr.bind_to_any_port(HOST);
  1180. thread t = thread([&] { svr.listen_after_bind(); });
  1181. auto se = detail::scope_exit([&] {
  1182. svr.stop();
  1183. t.join();
  1184. ASSERT_FALSE(svr.is_running());
  1185. });
  1186. svr.wait_until_ready();
  1187. UploadFormDataItems items = {
  1188. {"zulu", "1", "", ""},
  1189. {"alpha", "2", "", ""},
  1190. {"mike", "3", "", ""},
  1191. {"zebra", "z", "z.txt", "text/plain"},
  1192. {"apple", "a", "a.txt", "text/plain"},
  1193. };
  1194. Client cli(HOST, port);
  1195. auto res = cli.Post("/order", items);
  1196. ASSERT_TRUE(res);
  1197. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1198. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1199. }
  1200. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1201. Server svr;
  1202. std::vector<std::string> values;
  1203. std::string first, second, out_of_range, order;
  1204. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1205. values = req.form.get_fields("tag");
  1206. first = req.form.get_field("tag", 0);
  1207. second = req.form.get_field("tag", 1);
  1208. out_of_range = req.form.get_field("tag", 2);
  1209. for (const auto &field : req.form.fields) {
  1210. order += field.first + "=" + field.second.content + " ";
  1211. }
  1212. res.set_content("ok", "text/plain");
  1213. });
  1214. auto port = svr.bind_to_any_port(HOST);
  1215. thread t = thread([&] { svr.listen_after_bind(); });
  1216. auto se = detail::scope_exit([&] {
  1217. svr.stop();
  1218. t.join();
  1219. ASSERT_FALSE(svr.is_running());
  1220. });
  1221. svr.wait_until_ready();
  1222. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1223. // not adjacent in the container.
  1224. UploadFormDataItems items = {
  1225. {"tag", "first", "", ""},
  1226. {"other", "x", "", ""},
  1227. {"tag", "second", "", ""},
  1228. };
  1229. Client cli(HOST, port);
  1230. auto res = cli.Post("/repeated", items);
  1231. ASSERT_TRUE(res);
  1232. ASSERT_EQ(2U, values.size());
  1233. EXPECT_EQ("first", values[0]);
  1234. EXPECT_EQ("second", values[1]);
  1235. EXPECT_EQ("first", first);
  1236. EXPECT_EQ("second", second);
  1237. // std::multimap already kept entries sharing a name in insertion order, so
  1238. // everything above passes without this change too. The whole traversal is
  1239. // what tells the two apart: sorting by name would hoist "other" to the front
  1240. // and the two "tag" parts would end up adjacent.
  1241. EXPECT_EQ("tag=first other=x tag=second ", order);
  1242. // Advancing past the last entry of a name used to run off the container;
  1243. // the container's saturating increment makes it return the default instead.
  1244. EXPECT_EQ("", out_of_range);
  1245. }
  1246. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1247. // Server::read_content() keeps a FormFields::iterator alive across the
  1248. // content callbacks that fill the part it points at. The container is
  1249. // vector-backed, so a later emplace can reallocate and invalidate an older
  1250. // iterator; 64 parts grow the vector through seven reallocations, which
  1251. // checks that every part's content still lands in its own entry.
  1252. const size_t part_count = 64;
  1253. // One formula for both the parts sent and the values expected back, so the
  1254. // two cannot drift apart.
  1255. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1256. auto content_of = [](size_t i) {
  1257. return std::string(64, static_cast<char>('a' + (i % 26)));
  1258. };
  1259. Server svr;
  1260. std::vector<std::pair<std::string, std::string>> received;
  1261. svr.Post("/many", [&](const Request &req, Response &res) {
  1262. for (const auto &field : req.form.fields) {
  1263. received.emplace_back(field.first, field.second.content);
  1264. }
  1265. res.set_content("ok", "text/plain");
  1266. });
  1267. auto port = svr.bind_to_any_port(HOST);
  1268. thread t = thread([&] { svr.listen_after_bind(); });
  1269. auto se = detail::scope_exit([&] {
  1270. svr.stop();
  1271. t.join();
  1272. ASSERT_FALSE(svr.is_running());
  1273. });
  1274. svr.wait_until_ready();
  1275. UploadFormDataItems items;
  1276. for (size_t i = 0; i < part_count; i++) {
  1277. items.push_back({name_of(i), content_of(i), "", ""});
  1278. }
  1279. Client cli(HOST, port);
  1280. auto res = cli.Post("/many", items);
  1281. ASSERT_TRUE(res);
  1282. ASSERT_EQ(part_count, received.size());
  1283. for (size_t i = 0; i < part_count; i++) {
  1284. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1285. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1286. }
  1287. }
  1288. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1289. string content_type = "multipart/form-data; boundary=something";
  1290. string boundary;
  1291. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1292. EXPECT_TRUE(ret);
  1293. EXPECT_EQ(boundary, "something");
  1294. }
  1295. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1296. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1297. string boundary;
  1298. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1299. EXPECT_TRUE(ret);
  1300. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1301. }
  1302. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1303. string content_type =
  1304. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1305. string boundary;
  1306. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1307. EXPECT_TRUE(ret);
  1308. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1309. }
  1310. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1311. string content_type =
  1312. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1319. const string boundary(70, 'a');
  1320. string content_type = "multipart/form-data; boundary=" + boundary;
  1321. string parsed;
  1322. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1323. EXPECT_TRUE(ret);
  1324. EXPECT_EQ(parsed, boundary);
  1325. }
  1326. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1327. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1328. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1329. string parsed;
  1330. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1331. EXPECT_FALSE(ret);
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1334. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1335. // is 72 characters on the wire and still valid.
  1336. const string boundary(70, 'a');
  1337. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1338. string parsed;
  1339. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1340. EXPECT_EQ(parsed, boundary);
  1341. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1342. parsed.clear();
  1343. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1344. }
  1345. TEST(GetHeaderValueTest, DefaultValue) {
  1346. Headers headers = {{"Dummy", "Dummy"}};
  1347. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1348. EXPECT_STREQ("text/plain", val);
  1349. }
  1350. TEST(GetHeaderValueTest, DefaultValueInt) {
  1351. Headers headers = {{"Dummy", "Dummy"}};
  1352. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1353. EXPECT_EQ(100ull, val);
  1354. }
  1355. TEST(GetHeaderValueTest, RegularValue) {
  1356. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1357. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1358. EXPECT_STREQ("text/html", val);
  1359. }
  1360. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1361. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1362. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1363. EXPECT_STREQ("text/html", val);
  1364. }
  1365. TEST(GetHeaderValueTest, SetContent) {
  1366. Response res;
  1367. res.set_content("html", "text/html");
  1368. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1369. res.set_content("text", "text/plain");
  1370. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1371. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1372. }
  1373. TEST(GetHeaderValueTest, RegularValueInt) {
  1374. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1375. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1376. EXPECT_EQ(100ull, val);
  1377. }
  1378. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1379. Headers headers = {{"Content-Length", "x"}};
  1380. auto is_invalid_value = false;
  1381. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1382. is_invalid_value);
  1383. EXPECT_EQ(0ull, val);
  1384. EXPECT_TRUE(is_invalid_value);
  1385. }
  1386. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1387. // An all-digit value that overflows size_t must be reported as invalid, not
  1388. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1389. // a large length to a small one on 32-bit builds, leaving the framing length
  1390. // wrong while is_invalid_value stayed false.
  1391. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1392. auto is_invalid_value = false;
  1393. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1394. is_invalid_value);
  1395. EXPECT_TRUE(is_invalid_value);
  1396. // A well-formed length is unaffected.
  1397. Headers ok = {{"Content-Length", "1234"}};
  1398. is_invalid_value = false;
  1399. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1400. is_invalid_value);
  1401. EXPECT_EQ(1234ull, val);
  1402. EXPECT_FALSE(is_invalid_value);
  1403. }
  1404. TEST(GetHeaderValueTest, Range) {
  1405. {
  1406. Headers headers = {make_range_header({{1, -1}})};
  1407. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1408. EXPECT_STREQ("bytes=1-", val);
  1409. }
  1410. {
  1411. Headers headers = {make_range_header({{-1, 1}})};
  1412. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1413. EXPECT_STREQ("bytes=-1", val);
  1414. }
  1415. {
  1416. Headers headers = {make_range_header({{1, 10}})};
  1417. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1418. EXPECT_STREQ("bytes=1-10", val);
  1419. }
  1420. {
  1421. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1422. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1423. EXPECT_STREQ("bytes=1-10, 100-", val);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1427. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1428. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1429. }
  1430. {
  1431. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1432. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1433. EXPECT_STREQ("bytes=0-0, -1", val);
  1434. }
  1435. }
  1436. TEST(BearerTokenAuthTest, SchemeValidation) {
  1437. // A value shorter than "Bearer " must not throw from the fixed-length
  1438. // substr, and a non-Bearer scheme must not be reported as a token.
  1439. struct {
  1440. const char *value;
  1441. const char *expected;
  1442. } cases[] = {
  1443. {"x", ""},
  1444. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1445. {"Bearer abc123", "abc123"},
  1446. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1447. };
  1448. for (const auto &c : cases) {
  1449. Request req;
  1450. req.set_header("Authorization", c.value);
  1451. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1452. }
  1453. }
  1454. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1455. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1456. // to depend on the standard library (libstdc++ handed back duplicates in
  1457. // reverse insertion order, libc++ in insertion order).
  1458. Request req;
  1459. req.set_header("Accept-Encoding", "gzip");
  1460. req.set_header("Accept-Encoding", "deflate");
  1461. req.set_header("Accept-Encoding", "br");
  1462. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1463. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1464. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1465. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1466. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1467. }
  1468. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1469. Request req;
  1470. req.set_header("X-Test", "only");
  1471. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1472. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1473. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1474. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1475. }
  1476. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1477. Headers headers;
  1478. headers.emplace("Host", "example.com");
  1479. headers.emplace("Accept-Encoding", "gzip");
  1480. headers.emplace("User-Agent", "test");
  1481. headers.emplace("Accept-Encoding", "deflate");
  1482. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1483. "Accept-Encoding=deflate ",
  1484. entries_to_string(headers));
  1485. }
  1486. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1487. Headers headers = {{"Content-Type", "text/html"},
  1488. {"CONTENT-TYPE", "text/xml"}};
  1489. EXPECT_EQ(2U, headers.count("content-type"));
  1490. auto it = headers.find("content-type");
  1491. ASSERT_TRUE(it != headers.end());
  1492. EXPECT_EQ("text/html", it->second);
  1493. }
  1494. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1495. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1496. // drop only those fields and leave everything positioned between them.
  1497. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1498. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1499. auto rng = headers.equal_range("a");
  1500. headers.erase(rng.first, rng.second);
  1501. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1502. }
  1503. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1504. Headers headers = {
  1505. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1506. EXPECT_EQ(3U, headers.erase("A"));
  1507. EXPECT_EQ(0U, headers.count("A"));
  1508. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1509. }
  1510. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1511. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1512. headers.emplace_front("Host", "example.com");
  1513. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1514. entries_to_string(headers));
  1515. }
  1516. TEST(ParseHeaderValueTest, Range) {
  1517. {
  1518. Ranges ranges;
  1519. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1520. EXPECT_TRUE(ret);
  1521. EXPECT_EQ(1u, ranges.size());
  1522. EXPECT_EQ(1u, ranges[0].first);
  1523. EXPECT_EQ(-1, ranges[0].second);
  1524. }
  1525. {
  1526. Ranges ranges;
  1527. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1528. EXPECT_TRUE(ret);
  1529. EXPECT_EQ(1u, ranges.size());
  1530. EXPECT_EQ(-1, ranges[0].first);
  1531. EXPECT_EQ(1u, ranges[0].second);
  1532. }
  1533. {
  1534. Ranges ranges;
  1535. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1536. EXPECT_TRUE(ret);
  1537. EXPECT_EQ(1u, ranges.size());
  1538. EXPECT_EQ(1u, ranges[0].first);
  1539. EXPECT_EQ(10u, ranges[0].second);
  1540. }
  1541. {
  1542. Ranges ranges;
  1543. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1544. EXPECT_FALSE(ret);
  1545. }
  1546. {
  1547. Ranges ranges;
  1548. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(2u, ranges.size());
  1551. EXPECT_EQ(1u, ranges[0].first);
  1552. EXPECT_EQ(10u, ranges[0].second);
  1553. EXPECT_EQ(100u, ranges[1].first);
  1554. EXPECT_EQ(-1, ranges[1].second);
  1555. }
  1556. {
  1557. Ranges ranges;
  1558. auto ret =
  1559. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(3u, ranges.size());
  1562. EXPECT_EQ(1u, ranges[0].first);
  1563. EXPECT_EQ(10u, ranges[0].second);
  1564. EXPECT_EQ(100u, ranges[1].first);
  1565. EXPECT_EQ(200u, ranges[1].second);
  1566. EXPECT_EQ(300u, ranges[2].first);
  1567. EXPECT_EQ(400u, ranges[2].second);
  1568. }
  1569. {
  1570. Ranges ranges;
  1571. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1572. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1573. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1574. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1575. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1576. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1577. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1578. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1579. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1580. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1581. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1582. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1583. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1584. EXPECT_TRUE(ranges.empty());
  1585. }
  1586. }
  1587. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1588. Request req;
  1589. req.set_header("Accept-Encoding", "gzip");
  1590. Response res;
  1591. res.set_header("Content-Type", "text/plain");
  1592. auto ret = detail::encoding_type(req, res);
  1593. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1594. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1595. #else
  1596. EXPECT_TRUE(ret == detail::EncodingType::None);
  1597. #endif
  1598. }
  1599. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1600. Request req;
  1601. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1602. Response res;
  1603. res.set_header("Content-Type", "text/plain");
  1604. auto ret = detail::encoding_type(req, res);
  1605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1606. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1607. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1608. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1609. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1610. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1611. #else
  1612. EXPECT_TRUE(ret == detail::EncodingType::None);
  1613. #endif
  1614. }
  1615. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1616. Request req;
  1617. req.set_header("Accept-Encoding",
  1618. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1619. Response res;
  1620. res.set_header("Content-Type", "text/plain");
  1621. auto ret = detail::encoding_type(req, res);
  1622. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1623. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1624. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1625. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1626. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1627. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1628. #else
  1629. EXPECT_TRUE(ret == detail::EncodingType::None);
  1630. #endif
  1631. }
  1632. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1633. // All supported encodings rejected with q=0 should return None
  1634. Request req;
  1635. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1636. Response res;
  1637. res.set_header("Content-Type", "text/plain");
  1638. auto ret = detail::encoding_type(req, res);
  1639. EXPECT_TRUE(ret == detail::EncodingType::None);
  1640. }
  1641. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1642. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1643. Request req;
  1644. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1645. Response res;
  1646. res.set_header("Content-Type", "text/plain");
  1647. auto ret = detail::encoding_type(req, res);
  1648. EXPECT_TRUE(ret == detail::EncodingType::None);
  1649. }
  1650. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1651. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1652. Request req;
  1653. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1654. Response res;
  1655. res.set_header("Content-Type", "text/plain");
  1656. auto ret = detail::encoding_type(req, res);
  1657. EXPECT_TRUE(ret == detail::EncodingType::None);
  1658. }
  1659. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1660. // RFC 7231: Accept-Encoding values are case-insensitive
  1661. Request req;
  1662. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1663. Response res;
  1664. res.set_header("Content-Type", "text/plain");
  1665. auto ret = detail::encoding_type(req, res);
  1666. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1667. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1668. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1669. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1670. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1671. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1672. #else
  1673. EXPECT_TRUE(ret == detail::EncodingType::None);
  1674. #endif
  1675. }
  1676. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1677. // q value should determine priority, not hardcoded order
  1678. Request req;
  1679. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1680. Response res;
  1681. res.set_header("Content-Type", "text/plain");
  1682. auto ret = detail::encoding_type(req, res);
  1683. // gzip has highest q=1.0, so it should be selected even though
  1684. // br and zstd are also supported
  1685. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1686. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1687. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1688. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1689. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1690. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1691. #else
  1692. EXPECT_TRUE(ret == detail::EncodingType::None);
  1693. #endif
  1694. }
  1695. TEST(BufferStreamTest, read) {
  1696. detail::BufferStream strm1;
  1697. Stream &strm = strm1;
  1698. EXPECT_EQ(5, strm.write("hello"));
  1699. char buf[512];
  1700. EXPECT_EQ(2, strm.read(buf, 2));
  1701. EXPECT_EQ('h', buf[0]);
  1702. EXPECT_EQ('e', buf[1]);
  1703. EXPECT_EQ(2, strm.read(buf, 2));
  1704. EXPECT_EQ('l', buf[0]);
  1705. EXPECT_EQ('l', buf[1]);
  1706. EXPECT_EQ(1, strm.read(buf, 1));
  1707. EXPECT_EQ('o', buf[0]);
  1708. EXPECT_EQ(0, strm.read(buf, 1));
  1709. }
  1710. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1711. auto host = "www.httpwatch.com";
  1712. auto ip = hosted_at(host);
  1713. EXPECT_EQ("23.96.13.243", ip);
  1714. std::vector<std::string> addrs;
  1715. hosted_at(host, addrs);
  1716. EXPECT_EQ(1u, addrs.size());
  1717. }
  1718. #if 0 // It depends on each test environment...
  1719. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1720. auto host = "www.youtube.com";
  1721. std::vector<std::string> addrs;
  1722. hosted_at(host, addrs);
  1723. EXPECT_EQ(20u, addrs.size());
  1724. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1725. EXPECT_TRUE(it != addrs.end());
  1726. }
  1727. #endif
  1728. class ChunkedEncodingTest : public ::testing::Test {
  1729. protected:
  1730. ChunkedEncodingTest()
  1731. : cli_(HOST, PORT)
  1732. #ifdef CPPHTTPLIB_SSL_ENABLED
  1733. ,
  1734. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1735. #endif
  1736. {
  1737. cli_.set_connection_timeout(2);
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. cli_.enable_server_certificate_verification(false);
  1740. #endif
  1741. }
  1742. virtual void SetUp() {
  1743. read_file("./image.jpg", image_data_);
  1744. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!", "text/plain");
  1746. });
  1747. svr_.Get(
  1748. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1749. res.set_chunked_content_provider(
  1750. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1751. size_t remaining = image_data_.size() - offset;
  1752. if (remaining == 0) {
  1753. sink.done();
  1754. } else {
  1755. constexpr size_t CHUNK_SIZE = 1024;
  1756. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1757. sink.write(&image_data_[offset], send_size);
  1758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1759. }
  1760. return true;
  1761. });
  1762. });
  1763. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1764. svr_.wait_until_ready();
  1765. }
  1766. virtual void TearDown() {
  1767. svr_.stop();
  1768. if (!request_threads_.empty()) {
  1769. std::this_thread::sleep_for(std::chrono::seconds(1));
  1770. for (auto &t : request_threads_) {
  1771. t.join();
  1772. }
  1773. }
  1774. t_.join();
  1775. }
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli_;
  1778. SSLServer svr_;
  1779. #else
  1780. Client cli_;
  1781. Server svr_;
  1782. #endif
  1783. thread t_;
  1784. std::vector<thread> request_threads_;
  1785. std::string image_data_;
  1786. };
  1787. TEST_F(ChunkedEncodingTest, NormalGet) {
  1788. auto res = cli_.Get("/chunked");
  1789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1790. std::string out;
  1791. read_file("./image.jpg", out);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ(out, res->body);
  1794. }
  1795. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1796. std::string body;
  1797. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1798. body.append(data, data_length);
  1799. return true;
  1800. });
  1801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1802. std::string out;
  1803. read_file("./image.jpg", out);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. EXPECT_EQ(out, body);
  1806. }
  1807. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1808. std::string body;
  1809. auto res = cli_.Get(
  1810. "/chunked",
  1811. [&](const Response &response) {
  1812. EXPECT_EQ(StatusCode::OK_200, response.status);
  1813. return true;
  1814. },
  1815. [&](const char *data, size_t data_length) {
  1816. body.append(data, data_length);
  1817. return true;
  1818. });
  1819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1820. std::string out;
  1821. read_file("./image.jpg", out);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ(out, body);
  1824. }
  1825. TEST(RangeTest, FromHTTPBin_Online) {
  1826. auto host = "httpbingo.org";
  1827. auto path = std::string{"/range/32"};
  1828. #ifdef CPPHTTPLIB_SSL_ENABLED
  1829. auto port = 443;
  1830. SSLClient cli(host, port);
  1831. #else
  1832. auto port = 80;
  1833. Client cli(host, port);
  1834. #endif
  1835. cli.set_connection_timeout(5);
  1836. {
  1837. auto res = cli.Get(path);
  1838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1839. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1840. EXPECT_EQ(StatusCode::OK_200, res->status);
  1841. }
  1842. {
  1843. Headers headers = {make_range_header({{1, -1}})};
  1844. auto res = cli.Get(path, headers);
  1845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1846. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1848. }
  1849. {
  1850. Headers headers = {make_range_header({{1, 10}})};
  1851. auto res = cli.Get(path, headers);
  1852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1853. EXPECT_EQ("bcdefghijk", res->body);
  1854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1855. }
  1856. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1857. // entire resource, while the original httpbin returned 200. Both are
  1858. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1859. {
  1860. Headers headers = {make_range_header({{0, 31}})};
  1861. auto res = cli.Get(path, headers);
  1862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1863. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1864. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1865. res->status == StatusCode::PartialContent_206);
  1866. }
  1867. {
  1868. Headers headers = {make_range_header({{0, -1}})};
  1869. auto res = cli.Get(path, headers);
  1870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1871. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1872. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1873. res->status == StatusCode::PartialContent_206);
  1874. }
  1875. // go-httpbin returns 206 with clamped range for over-range requests,
  1876. // while the original httpbin returned 416. Both behaviors are observed
  1877. // in real servers, so we only verify the request succeeds.
  1878. {
  1879. Headers headers = {make_range_header({{0, 32}})};
  1880. auto res = cli.Get(path, headers);
  1881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1882. }
  1883. }
  1884. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1885. auto host = "unresolvableaddress.local";
  1886. auto path = std::string{"/"};
  1887. #ifdef CPPHTTPLIB_SSL_ENABLED
  1888. auto port = 443;
  1889. SSLClient cli(host, port);
  1890. #else
  1891. auto port = 80;
  1892. Client cli(host, port);
  1893. #endif
  1894. cli.set_connection_timeout(1);
  1895. {
  1896. auto res = cli.Get(path);
  1897. ASSERT_FALSE(res);
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. }
  1901. #if defined(__linux__) && defined(__GLIBC__) && \
  1902. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1903. // Forward declaration: in split builds split.py strips `inline` and moves the
  1904. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1905. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1906. // against the symbol in both header-only and split builds.
  1907. namespace httplib {
  1908. namespace detail {
  1909. int getaddrinfo_with_timeout(const char *node, const char *service,
  1910. const struct addrinfo *hints,
  1911. struct addrinfo **res, time_t timeout_sec);
  1912. } // namespace detail
  1913. } // namespace httplib
  1914. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1915. //
  1916. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1917. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1918. // gai_suspend() call hits the connection timeout the function calls
  1919. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1920. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1921. // still alive and still references the now-destroyed stack frame.
  1922. //
  1923. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1924. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1925. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1926. // and runs them in a container.
  1927. namespace {
  1928. bool should_run_issue_2431_tests() {
  1929. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1930. return v && *v && std::string(v) != "0";
  1931. }
  1932. std::string unique_unresolvable_host(int n) {
  1933. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1934. // glibc still asks the configured nameserver — which is exactly the path
  1935. // we want to exercise. A unique label per call avoids the resolver cache.
  1936. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1937. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1938. std::to_string(n) + ".invalid";
  1939. }
  1940. } // namespace
  1941. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1942. if (!should_run_issue_2431_tests()) {
  1943. GTEST_SKIP()
  1944. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1945. }
  1946. for (int i = 0; i < 8; ++i) {
  1947. struct addrinfo hints;
  1948. memset(&hints, 0, sizeof(hints));
  1949. hints.ai_family = AF_UNSPEC;
  1950. hints.ai_socktype = SOCK_STREAM;
  1951. auto host = unique_unresolvable_host(i);
  1952. struct addrinfo *result = nullptr;
  1953. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1954. &result, /*timeout_sec=*/1);
  1955. if (rc == 0 && result) { freeaddrinfo(result); }
  1956. }
  1957. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1958. // stack region they still believe holds their gaicb.
  1959. std::this_thread::sleep_for(std::chrono::seconds(3));
  1960. }
  1961. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1962. if (!should_run_issue_2431_tests()) {
  1963. GTEST_SKIP()
  1964. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1965. }
  1966. std::atomic<bool> stop{false};
  1967. std::vector<std::thread> threads;
  1968. for (int t = 0; t < 8; ++t) {
  1969. threads.emplace_back([t, &stop] {
  1970. int i = 0;
  1971. while (!stop.load(std::memory_order_relaxed)) {
  1972. struct addrinfo hints;
  1973. memset(&hints, 0, sizeof(hints));
  1974. hints.ai_family = AF_UNSPEC;
  1975. hints.ai_socktype = SOCK_STREAM;
  1976. auto host = unique_unresolvable_host(t * 100000 + i++);
  1977. struct addrinfo *result = nullptr;
  1978. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1979. &result, /*timeout_sec=*/1);
  1980. if (rc == 0 && result) { freeaddrinfo(result); }
  1981. }
  1982. });
  1983. }
  1984. std::this_thread::sleep_for(std::chrono::seconds(8));
  1985. stop.store(true, std::memory_order_relaxed);
  1986. for (auto &th : threads) {
  1987. th.join();
  1988. }
  1989. std::this_thread::sleep_for(std::chrono::seconds(3));
  1990. }
  1991. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1992. if (!should_run_issue_2431_tests()) {
  1993. GTEST_SKIP()
  1994. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1995. }
  1996. std::atomic<bool> stop{false};
  1997. std::vector<std::thread> threads;
  1998. for (int t = 0; t < 8; ++t) {
  1999. threads.emplace_back([t, &stop] {
  2000. int i = 0;
  2001. while (!stop.load(std::memory_order_relaxed)) {
  2002. auto host = unique_unresolvable_host(t * 100000 + i++);
  2003. Client cli(host, 80);
  2004. cli.set_connection_timeout(1, 0);
  2005. cli.set_read_timeout(1, 0);
  2006. cli.set_write_timeout(1, 0);
  2007. (void)cli.Get("/");
  2008. }
  2009. });
  2010. }
  2011. std::this_thread::sleep_for(std::chrono::seconds(8));
  2012. stop.store(true, std::memory_order_relaxed);
  2013. for (auto &th : threads) {
  2014. th.join();
  2015. }
  2016. std::this_thread::sleep_for(std::chrono::seconds(3));
  2017. }
  2018. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2019. TEST(ConnectionErrorTest, InvalidHost) {
  2020. auto host = "-abcde.com";
  2021. #ifdef CPPHTTPLIB_SSL_ENABLED
  2022. auto port = 443;
  2023. SSLClient cli(host, port);
  2024. #else
  2025. auto port = 80;
  2026. Client cli(host, port);
  2027. #endif
  2028. cli.set_connection_timeout(std::chrono::seconds(2));
  2029. auto res = cli.Get("/");
  2030. ASSERT_TRUE(!res);
  2031. EXPECT_EQ(Error::Connection, res.error());
  2032. }
  2033. TEST(ConnectionErrorTest, InvalidHost2) {
  2034. auto host = "httpcan.org/";
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. SSLClient cli(host);
  2037. #else
  2038. Client cli(host);
  2039. #endif
  2040. cli.set_connection_timeout(std::chrono::seconds(2));
  2041. auto res = cli.Get("/");
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Connection, res.error());
  2044. }
  2045. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2046. auto host = "httpcan.org/";
  2047. #ifdef CPPHTTPLIB_SSL_ENABLED
  2048. SSLClient cli(host);
  2049. #else
  2050. Client cli(host);
  2051. #endif
  2052. cli.set_connection_timeout(std::chrono::seconds(2));
  2053. auto res = cli.Get("/");
  2054. ASSERT_TRUE(!res);
  2055. stringstream s;
  2056. s << "error code: " << res.error();
  2057. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2058. }
  2059. TEST(ConnectionErrorTest, InvalidPort) {
  2060. auto host = "localhost";
  2061. auto port = 44380;
  2062. #ifdef CPPHTTPLIB_SSL_ENABLED
  2063. SSLClient cli(host, port);
  2064. #else
  2065. Client cli(host, port);
  2066. #endif
  2067. cli.set_connection_timeout(std::chrono::seconds(2));
  2068. auto res = cli.Get("/");
  2069. ASSERT_TRUE(!res);
  2070. EXPECT_TRUE(Error::Connection == res.error() ||
  2071. Error::ConnectionTimeout == res.error());
  2072. }
  2073. TEST(ConnectionErrorTest, Timeout_Online) {
  2074. auto host = "google.com";
  2075. #ifdef CPPHTTPLIB_SSL_ENABLED
  2076. auto port = 44380;
  2077. SSLClient cli(host, port);
  2078. #else
  2079. auto port = 8080;
  2080. Client cli(host, port);
  2081. #endif
  2082. cli.set_connection_timeout(std::chrono::seconds(2));
  2083. // only probe one address type so that the error reason
  2084. // correlates to the timed-out IPv4, not the unsupported
  2085. // IPv6 connection attempt
  2086. cli.set_address_family(AF_INET);
  2087. auto res = cli.Get("/");
  2088. ASSERT_TRUE(!res);
  2089. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2090. }
  2091. TEST(CancelTest, NoCancel_Online) {
  2092. auto host = "httpbingo.org";
  2093. auto path = std::string{"/range/32"};
  2094. #ifdef CPPHTTPLIB_SSL_ENABLED
  2095. auto port = 443;
  2096. SSLClient cli(host, port);
  2097. #else
  2098. auto port = 80;
  2099. Client cli(host, port);
  2100. #endif
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2104. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. }
  2107. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2108. // Use /bytes with a large payload so that the DownloadProgress callback
  2109. // (which only fires for Content-Length responses) is invoked before the
  2110. // entire body is received, giving cancellation a chance to fire.
  2111. auto host = "httpbingo.org";
  2112. auto path = std::string{"/bytes/524288"};
  2113. #ifdef CPPHTTPLIB_SSL_ENABLED
  2114. auto port = 443;
  2115. SSLClient cli(host, port);
  2116. #else
  2117. auto port = 80;
  2118. Client cli(host, port);
  2119. #endif
  2120. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. ASSERT_TRUE(!res);
  2123. EXPECT_EQ(Error::Canceled, res.error());
  2124. }
  2125. TEST(CancelTest, WithCancelLargePayload_Online) {
  2126. auto host = "httpbingo.org";
  2127. auto path = std::string{"/bytes/524288"};
  2128. #ifdef CPPHTTPLIB_SSL_ENABLED
  2129. auto port = 443;
  2130. SSLClient cli(host, port);
  2131. #else
  2132. auto port = 80;
  2133. Client cli(host, port);
  2134. #endif
  2135. cli.set_connection_timeout(std::chrono::seconds(5));
  2136. uint32_t count = 0;
  2137. auto res =
  2138. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2139. ASSERT_TRUE(!res);
  2140. EXPECT_EQ(Error::Canceled, res.error());
  2141. }
  2142. TEST(CancelTest, NoCancelPost) {
  2143. Server svr;
  2144. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2145. res.set_content("Hello World!", "text/plain");
  2146. });
  2147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2148. auto se = detail::scope_exit([&] {
  2149. svr.stop();
  2150. thread.join();
  2151. ASSERT_FALSE(svr.is_running());
  2152. });
  2153. svr.wait_until_ready();
  2154. Client cli(HOST, PORT);
  2155. cli.set_connection_timeout(std::chrono::seconds(5));
  2156. auto res =
  2157. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2158. "application/json", [](uint64_t, uint64_t) { return true; });
  2159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2160. EXPECT_EQ("Hello World!", res->body);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. }
  2163. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2164. Server svr;
  2165. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2166. res.set_content("Hello World!", "text/plain");
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. Client cli(HOST, PORT);
  2176. cli.set_connection_timeout(std::chrono::seconds(5));
  2177. auto res =
  2178. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2179. "application/json", [](uint64_t, uint64_t) { return false; });
  2180. ASSERT_TRUE(!res);
  2181. EXPECT_EQ(Error::Canceled, res.error());
  2182. }
  2183. TEST(CancelTest, WithCancelLargePayloadPost) {
  2184. Server svr;
  2185. svr.set_payload_max_length(200 * 1024 * 1024);
  2186. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2187. res.set_content(LARGE_DATA, "text/plain");
  2188. });
  2189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. Client cli(HOST, PORT);
  2197. cli.set_payload_max_length(200 * 1024 * 1024);
  2198. cli.set_connection_timeout(std::chrono::seconds(5));
  2199. auto res =
  2200. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2201. "application/json", [](uint64_t, uint64_t) { return false; });
  2202. ASSERT_TRUE(!res);
  2203. EXPECT_EQ(Error::Canceled, res.error());
  2204. }
  2205. TEST(CancelTest, NoCancelPut) {
  2206. Server svr;
  2207. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2208. res.set_content("Hello World!", "text/plain");
  2209. });
  2210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2211. auto se = detail::scope_exit([&] {
  2212. svr.stop();
  2213. thread.join();
  2214. ASSERT_FALSE(svr.is_running());
  2215. });
  2216. svr.wait_until_ready();
  2217. Client cli(HOST, PORT);
  2218. cli.set_connection_timeout(std::chrono::seconds(5));
  2219. auto res =
  2220. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2221. "application/json", [](uint64_t, uint64_t) { return true; });
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. EXPECT_EQ("Hello World!", res->body);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. }
  2226. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2227. Server svr;
  2228. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!", "text/plain");
  2230. });
  2231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2232. auto se = detail::scope_exit([&] {
  2233. svr.stop();
  2234. thread.join();
  2235. ASSERT_FALSE(svr.is_running());
  2236. });
  2237. svr.wait_until_ready();
  2238. Client cli(HOST, PORT);
  2239. cli.set_connection_timeout(std::chrono::seconds(5));
  2240. auto res =
  2241. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2242. "application/json", [](uint64_t, uint64_t) { return false; });
  2243. ASSERT_TRUE(!res);
  2244. EXPECT_EQ(Error::Canceled, res.error());
  2245. }
  2246. TEST(CancelTest, WithCancelLargePayloadPut) {
  2247. Server svr;
  2248. svr.set_payload_max_length(200 * 1024 * 1024);
  2249. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2250. res.set_content(LARGE_DATA, "text/plain");
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. Client cli(HOST, PORT);
  2260. cli.set_payload_max_length(200 * 1024 * 1024);
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. auto res =
  2263. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2264. "application/json", [](uint64_t, uint64_t) { return false; });
  2265. ASSERT_TRUE(!res);
  2266. EXPECT_EQ(Error::Canceled, res.error());
  2267. }
  2268. TEST(CancelTest, NoCancelPatch) {
  2269. Server svr;
  2270. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2271. res.set_content("Hello World!", "text/plain");
  2272. });
  2273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2274. auto se = detail::scope_exit([&] {
  2275. svr.stop();
  2276. thread.join();
  2277. ASSERT_FALSE(svr.is_running());
  2278. });
  2279. svr.wait_until_ready();
  2280. Client cli(HOST, PORT);
  2281. cli.set_connection_timeout(std::chrono::seconds(5));
  2282. auto res =
  2283. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2284. "application/json", [](uint64_t, uint64_t) { return true; });
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("Hello World!", res->body);
  2287. EXPECT_EQ(StatusCode::OK_200, res->status);
  2288. }
  2289. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2290. Server svr;
  2291. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2295. auto se = detail::scope_exit([&] {
  2296. svr.stop();
  2297. thread.join();
  2298. ASSERT_FALSE(svr.is_running());
  2299. });
  2300. svr.wait_until_ready();
  2301. Client cli(HOST, PORT);
  2302. cli.set_connection_timeout(std::chrono::seconds(5));
  2303. auto res =
  2304. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2305. "application/json", [](uint64_t, uint64_t) { return false; });
  2306. ASSERT_TRUE(!res);
  2307. EXPECT_EQ(Error::Canceled, res.error());
  2308. }
  2309. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2310. Server svr;
  2311. svr.set_payload_max_length(200 * 1024 * 1024);
  2312. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2313. res.set_content(LARGE_DATA, "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. Client cli(HOST, PORT);
  2323. cli.set_payload_max_length(200 * 1024 * 1024);
  2324. cli.set_connection_timeout(std::chrono::seconds(5));
  2325. auto res =
  2326. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2327. "application/json", [](uint64_t, uint64_t) { return false; });
  2328. ASSERT_TRUE(!res);
  2329. EXPECT_EQ(Error::Canceled, res.error());
  2330. }
  2331. TEST(CancelTest, NoCancelDelete) {
  2332. Server svr;
  2333. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2334. res.set_content("Hello World!", "text/plain");
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. Client cli(HOST, PORT);
  2344. cli.set_connection_timeout(std::chrono::seconds(5));
  2345. auto res =
  2346. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2347. "application/json", [](uint64_t, uint64_t) { return true; });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. EXPECT_EQ("Hello World!", res->body);
  2350. EXPECT_EQ(StatusCode::OK_200, res->status);
  2351. }
  2352. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2353. Server svr;
  2354. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. Client cli(HOST, PORT);
  2365. cli.set_connection_timeout(std::chrono::seconds(5));
  2366. auto res =
  2367. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2368. "application/json", [](uint64_t, uint64_t) { return false; });
  2369. ASSERT_TRUE(!res);
  2370. EXPECT_EQ(Error::Canceled, res.error());
  2371. }
  2372. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2373. Server svr;
  2374. svr.set_payload_max_length(200 * 1024 * 1024);
  2375. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2376. res.set_content(LARGE_DATA, "text/plain");
  2377. });
  2378. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2379. auto se = detail::scope_exit([&] {
  2380. svr.stop();
  2381. thread.join();
  2382. ASSERT_FALSE(svr.is_running());
  2383. });
  2384. svr.wait_until_ready();
  2385. Client cli(HOST, PORT);
  2386. cli.set_payload_max_length(200 * 1024 * 1024);
  2387. cli.set_connection_timeout(std::chrono::seconds(5));
  2388. auto res =
  2389. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2390. "application/json", [](uint64_t, uint64_t) { return false; });
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::Canceled, res.error());
  2393. }
  2394. static std::string remove_whitespace(const std::string &input) {
  2395. std::string output;
  2396. output.reserve(input.size());
  2397. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2398. [](unsigned char c) { return !std::isspace(c); });
  2399. return output;
  2400. }
  2401. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/basic-auth/hello/world"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. {
  2412. auto res = cli.Get(path);
  2413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2414. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2415. }
  2416. {
  2417. auto res = cli.Get(
  2418. path, Headers{make_basic_authentication_header("hello", "world")});
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. auto body = remove_whitespace(res->body);
  2421. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2422. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. }
  2425. {
  2426. cli.set_basic_auth("hello", "world");
  2427. auto res = cli.Get(path);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. auto body = remove_whitespace(res->body);
  2430. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2431. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2432. EXPECT_EQ(StatusCode::OK_200, res->status);
  2433. }
  2434. {
  2435. cli.set_basic_auth("hello", "bad");
  2436. auto res = cli.Get(path);
  2437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2438. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2439. }
  2440. {
  2441. cli.set_basic_auth("bad", "world");
  2442. auto res = cli.Get(path);
  2443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2444. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2445. }
  2446. }
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2449. auto host = "httpbingo.org";
  2450. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2451. auto paths = std::vector<std::string>{
  2452. "/digest-auth/auth/hello/world/MD5",
  2453. "/digest-auth/auth/hello/world/SHA-256",
  2454. };
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. {
  2458. auto res = cli.Get(unauth_path);
  2459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2460. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2461. }
  2462. {
  2463. cli.set_digest_auth("hello", "world");
  2464. for (const auto &path : paths) {
  2465. auto res = cli.Get(path.c_str());
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. auto body = remove_whitespace(res->body);
  2468. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2469. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. }
  2472. cli.set_digest_auth("hello", "bad");
  2473. for (const auto &path : paths) {
  2474. auto res = cli.Get(path.c_str());
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2477. }
  2478. }
  2479. }
  2480. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2481. // comma-separated list of challenges, and each challenge may itself carry a
  2482. // comma-separated auth-param list, so a server can legally offer Basic
  2483. // before Digest, either as two field lines or packed into one. Runs one 401
  2484. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2485. // value() joins them in receipt order) and checks that the retry carries a
  2486. // well-formed Digest Authorization header naming expected_realm.
  2487. static void
  2488. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2489. const std::string &expected_realm) {
  2490. std::atomic<int> hits{0};
  2491. Server svr;
  2492. svr.Get("/x", [&](const Request &req, Response &res) {
  2493. if (++hits == 1) {
  2494. res.status = StatusCode::Unauthorized_401;
  2495. for (const auto &challenge : challenges) {
  2496. res.set_header("WWW-Authenticate", challenge);
  2497. }
  2498. } else {
  2499. auto authorization = req.get_header_value("Authorization");
  2500. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2501. EXPECT_NE(std::string::npos,
  2502. authorization.find("realm=\"" + expected_realm + "\""));
  2503. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2504. res.set_content("ok", "text/plain");
  2505. }
  2506. });
  2507. auto port = svr.bind_to_any_port(HOST);
  2508. std::thread t([&]() { svr.listen_after_bind(); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. t.join();
  2512. });
  2513. svr.wait_until_ready();
  2514. Client cli(HOST, port);
  2515. cli.set_digest_auth("hello", "world");
  2516. auto res = cli.Get("/x");
  2517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2518. EXPECT_EQ(2, hits.load());
  2519. }
  2520. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2521. static const char *kDigestChallenge =
  2522. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2523. "algorithm=MD5";
  2524. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2525. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2526. "testrealm");
  2527. }
  2528. // Same challenge list with the schemes in the opposite order, to make sure
  2529. // the fix above didn't just special-case "Basic first".
  2530. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2531. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2532. "testrealm");
  2533. }
  2534. // A comma inside a quoted auth-param value must not be mistaken for the
  2535. // separator between two challenges (or two auth-params).
  2536. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2537. run_digest_challenge_list_test(
  2538. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2539. "algorithm=MD5"},
  2540. "test,realm");
  2541. }
  2542. #endif
  2543. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2544. auto host = "google.com";
  2545. auto another_host = "example.com";
  2546. auto wrong_ip = "0.0.0.0";
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLClient cli(host);
  2549. #else
  2550. Client cli(host);
  2551. #endif
  2552. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2553. auto res = cli.Get("/");
  2554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2555. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2556. }
  2557. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2558. auto host = "google.com";
  2559. auto wrong_ip = "0.0.0.0";
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. SSLClient cli(host);
  2562. #else
  2563. Client cli(host);
  2564. #endif
  2565. cli.set_hostname_addr_map({{host, wrong_ip}});
  2566. auto res = cli.Get("/");
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Connection, res.error());
  2569. }
  2570. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2571. // A mapped value that is not an IP literal must be resolved. "localhost"
  2572. // resolves from the hosts file, so this test needs no external DNS.
  2573. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2574. auto host = "target.invalid";
  2575. Server svr;
  2576. std::string received_host;
  2577. svr.Get("/hi", [&](const Request &req, Response &res) {
  2578. received_host = req.get_header_value("Host");
  2579. res.set_content("Hello World!", "text/plain");
  2580. });
  2581. auto port = svr.bind_to_any_port(HOST);
  2582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2583. auto se = detail::scope_exit([&] {
  2584. svr.stop();
  2585. thread.join();
  2586. ASSERT_FALSE(svr.is_running());
  2587. });
  2588. svr.wait_until_ready();
  2589. Client cli(host, port);
  2590. cli.set_hostname_addr_map({{host, HOST}});
  2591. auto res = cli.Get("/hi");
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. // The mapping only redirects the connection; the identity stays host_.
  2595. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2596. }
  2597. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2598. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2599. auto host = "target.invalid";
  2600. Server svr;
  2601. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2602. res.set_content("Hello World!", "text/plain");
  2603. });
  2604. auto port = svr.bind_to_any_port("127.0.0.1");
  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, "127.0.0.1"}});
  2614. auto res = cli.Get("/hi");
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2619. // An empty mapped value must leave host_ as the connection target. Without
  2620. // that guard the empty value would become the host argument, getaddrinfo
  2621. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2622. // loopback - silently connecting somewhere the caller never asked for.
  2623. // The server listens on loopback, so such a fallback would succeed and is
  2624. // therefore observable as a failure of this test.
  2625. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. auto port = svr.bind_to_any_port(HOST);
  2631. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2632. auto se = detail::scope_exit([&] {
  2633. svr.stop();
  2634. thread.join();
  2635. ASSERT_FALSE(svr.is_running());
  2636. });
  2637. svr.wait_until_ready();
  2638. Client cli(blackhole, port);
  2639. cli.set_hostname_addr_map({{blackhole, ""}});
  2640. cli.set_connection_timeout(1);
  2641. auto res = cli.Get("/hi");
  2642. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2643. }
  2644. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2645. auto host = "httpbingo.org";
  2646. auto path = std::string{"/absolute-redirect/3"};
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. SSLClient cli(host);
  2649. #else
  2650. Client cli(host);
  2651. #endif
  2652. cli.set_follow_location(true);
  2653. auto res = cli.Get(path);
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. }
  2657. TEST(RedirectTest, Redirect_Online) {
  2658. auto host = "httpbingo.org";
  2659. auto path = std::string{"/redirect/3"};
  2660. #ifdef CPPHTTPLIB_SSL_ENABLED
  2661. SSLClient cli(host);
  2662. #else
  2663. Client cli(host);
  2664. #endif
  2665. cli.set_follow_location(true);
  2666. auto res = cli.Get(path);
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ(StatusCode::OK_200, res->status);
  2669. }
  2670. TEST(RelativeRedirectTest, Redirect_Online) {
  2671. auto host = "httpbingo.org";
  2672. auto path = std::string{"/relative-redirect/3"};
  2673. #ifdef CPPHTTPLIB_SSL_ENABLED
  2674. SSLClient cli(host);
  2675. #else
  2676. Client cli(host);
  2677. #endif
  2678. cli.set_follow_location(true);
  2679. auto res = cli.Get(path);
  2680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2681. EXPECT_EQ(StatusCode::OK_200, res->status);
  2682. }
  2683. TEST(TooManyRedirectTest, Redirect_Online) {
  2684. auto host = "httpbingo.org";
  2685. auto path = std::string{"/redirect/21"};
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. SSLClient cli(host);
  2688. #else
  2689. Client cli(host);
  2690. #endif
  2691. cli.set_follow_location(true);
  2692. auto res = cli.Get(path);
  2693. ASSERT_TRUE(!res);
  2694. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2695. }
  2696. #ifdef CPPHTTPLIB_SSL_ENABLED
  2697. TEST(YahooRedirectTest, Redirect_Online) {
  2698. Client cli("yahoo.com");
  2699. auto res = cli.Get("/");
  2700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2702. cli.set_follow_location(true);
  2703. res = cli.Get("/");
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::OK_200, res->status);
  2706. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2707. }
  2708. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2709. #define REDIR_HOST "httpbingo.org"
  2710. #define REDIR_PATH "/redirect-to"
  2711. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2712. SSLClient cli(REDIR_HOST);
  2713. cli.set_follow_location(true);
  2714. auto res =
  2715. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ(StatusCode::OK_200, res->status);
  2718. }
  2719. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2720. SSLClient cli(REDIR_HOST);
  2721. cli.set_follow_location(true);
  2722. Params params;
  2723. params.emplace("url", "http://example.com");
  2724. params.emplace("status_code", "302");
  2725. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2730. SSLClient cli(REDIR_HOST);
  2731. cli.set_follow_location(true);
  2732. Params params;
  2733. params.emplace("url", "http://example.com");
  2734. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2736. EXPECT_EQ(StatusCode::OK_200, res->status);
  2737. }
  2738. TEST(UrlWithSpace, Redirect_Online) {
  2739. SSLClient cli("edge.forgecdn.net");
  2740. cli.set_follow_location(true);
  2741. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2743. EXPECT_EQ(StatusCode::OK_200, res->status);
  2744. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2745. }
  2746. #endif
  2747. #if !defined(_WIN32) && !defined(_WIN64)
  2748. TEST(ReceiveSignals, Signal) {
  2749. auto setupSignalHandlers = []() {
  2750. struct sigaction act;
  2751. sigemptyset(&act.sa_mask);
  2752. act.sa_flags = SA_SIGINFO;
  2753. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2754. switch (sig) {
  2755. case SIGINT:
  2756. default: break;
  2757. }
  2758. };
  2759. ::sigaction(SIGINT, &act, nullptr);
  2760. };
  2761. Server svr;
  2762. int port = 0;
  2763. auto thread = std::thread([&]() {
  2764. setupSignalHandlers();
  2765. port = svr.bind_to_any_port(HOST);
  2766. svr.listen_after_bind();
  2767. });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. ASSERT_TRUE(svr.is_running());
  2775. pthread_kill(thread.native_handle(), SIGINT);
  2776. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2777. ASSERT_TRUE(svr.is_running());
  2778. }
  2779. #endif
  2780. TEST(RedirectToDifferentPort, Redirect) {
  2781. Server svr1;
  2782. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2783. res.set_content("Hello World!", "text/plain");
  2784. });
  2785. int svr1_port = 0;
  2786. auto thread1 = std::thread([&]() {
  2787. svr1_port = svr1.bind_to_any_port(HOST);
  2788. svr1.listen_after_bind();
  2789. });
  2790. Server svr2;
  2791. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2793. });
  2794. int svr2_port = 0;
  2795. auto thread2 = std::thread([&]() {
  2796. svr2_port = svr2.bind_to_any_port(HOST);
  2797. svr2.listen_after_bind();
  2798. });
  2799. auto se = detail::scope_exit([&] {
  2800. svr2.stop();
  2801. thread2.join();
  2802. svr1.stop();
  2803. thread1.join();
  2804. ASSERT_FALSE(svr2.is_running());
  2805. ASSERT_FALSE(svr1.is_running());
  2806. });
  2807. svr1.wait_until_ready();
  2808. svr2.wait_until_ready();
  2809. Client cli("localhost", svr2_port);
  2810. cli.set_follow_location(true);
  2811. auto res = cli.Get("/2");
  2812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2813. EXPECT_EQ(StatusCode::OK_200, res->status);
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. }
  2816. static void
  2817. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2818. Server svr1;
  2819. std::string captured_authorization;
  2820. svr1.Get("/target", [&](const Request &req, Response &res) {
  2821. captured_authorization = req.get_header_value("Authorization");
  2822. res.set_content("OK", "text/plain");
  2823. });
  2824. int svr1_port = 0;
  2825. auto thread1 = std::thread([&]() {
  2826. svr1_port = svr1.bind_to_any_port(HOST);
  2827. svr1.listen_after_bind();
  2828. });
  2829. Server svr2;
  2830. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2831. res.set_redirect(
  2832. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2833. });
  2834. int svr2_port = 0;
  2835. auto thread2 = std::thread([&]() {
  2836. svr2_port = svr2.bind_to_any_port(HOST);
  2837. svr2.listen_after_bind();
  2838. });
  2839. auto se = detail::scope_exit([&] {
  2840. svr2.stop();
  2841. thread2.join();
  2842. svr1.stop();
  2843. thread1.join();
  2844. ASSERT_FALSE(svr2.is_running());
  2845. ASSERT_FALSE(svr1.is_running());
  2846. });
  2847. svr1.wait_until_ready();
  2848. svr2.wait_until_ready();
  2849. Client cli("localhost", svr2_port);
  2850. cli.set_follow_location(true);
  2851. set_auth(cli);
  2852. auto res = cli.Get("/redir");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2856. EXPECT_TRUE(captured_authorization.empty());
  2857. }
  2858. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2859. TestDoNotForwardCredentialsOnRedirect(
  2860. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2861. }
  2862. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2863. TestDoNotForwardCredentialsOnRedirect(
  2864. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2865. }
  2866. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2867. Server svr1;
  2868. std::string captured_cookie;
  2869. bool target_hit = false;
  2870. svr1.Get("/target", [&](const Request &req, Response &res) {
  2871. captured_cookie = req.get_header_value("Cookie");
  2872. target_hit = true;
  2873. res.set_content("OK", "text/plain");
  2874. });
  2875. int svr1_port = 0;
  2876. auto thread1 = std::thread([&]() {
  2877. svr1_port = svr1.bind_to_any_port(HOST);
  2878. svr1.listen_after_bind();
  2879. });
  2880. Server svr2;
  2881. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2882. res.set_redirect(
  2883. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2884. });
  2885. int svr2_port = 0;
  2886. auto thread2 = std::thread([&]() {
  2887. svr2_port = svr2.bind_to_any_port(HOST);
  2888. svr2.listen_after_bind();
  2889. });
  2890. auto se = detail::scope_exit([&] {
  2891. svr2.stop();
  2892. thread2.join();
  2893. svr1.stop();
  2894. thread1.join();
  2895. ASSERT_FALSE(svr2.is_running());
  2896. ASSERT_FALSE(svr1.is_running());
  2897. });
  2898. svr1.wait_until_ready();
  2899. svr2.wait_until_ready();
  2900. Client cli("localhost", svr2_port);
  2901. cli.set_follow_location(true);
  2902. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2903. auto res = cli.Get("/redir", headers);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_TRUE(target_hit);
  2907. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2908. EXPECT_TRUE(captured_cookie.empty());
  2909. }
  2910. TEST(RedirectToSamePort, ForwardCookie) {
  2911. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2912. // header so that ordinary session flows keep working.
  2913. Server svr;
  2914. std::string captured_cookie;
  2915. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2916. res.set_redirect("/target", 302);
  2917. });
  2918. svr.Get("/target", [&](const Request &req, Response &res) {
  2919. captured_cookie = req.get_header_value("Cookie");
  2920. res.set_content("OK", "text/plain");
  2921. });
  2922. auto port = svr.bind_to_any_port(HOST);
  2923. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli(HOST, port);
  2931. cli.set_follow_location(true);
  2932. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2933. auto res = cli.Get("/redir", headers);
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2937. }
  2938. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2939. Server svr;
  2940. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2941. // Port number that overflows int — should not crash
  2942. res.set_redirect("http://localhost:99999999999999999999/target");
  2943. });
  2944. auto port = svr.bind_to_any_port(HOST);
  2945. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2946. auto se = detail::scope_exit([&] {
  2947. svr.stop();
  2948. thread.join();
  2949. ASSERT_FALSE(svr.is_running());
  2950. });
  2951. svr.wait_until_ready();
  2952. Client cli(HOST, port);
  2953. cli.set_follow_location(true);
  2954. auto res = cli.Get("/redir");
  2955. // Should fail gracefully, not crash (no valid response due to bad port)
  2956. EXPECT_FALSE(res);
  2957. }
  2958. TEST(RedirectFromPageWithContent, Redirect) {
  2959. Server svr;
  2960. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("___", "text/plain");
  2962. res.set_redirect("/2");
  2963. });
  2964. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2965. res.set_content("Hello World!", "text/plain");
  2966. });
  2967. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2968. auto se = detail::scope_exit([&] {
  2969. svr.stop();
  2970. th.join();
  2971. ASSERT_FALSE(svr.is_running());
  2972. });
  2973. svr.wait_until_ready();
  2974. {
  2975. Client cli("localhost", PORT);
  2976. cli.set_follow_location(true);
  2977. std::string body;
  2978. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2979. body.append(data, data_length);
  2980. return true;
  2981. });
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("Hello World!", body);
  2985. }
  2986. {
  2987. Client cli("localhost", PORT);
  2988. std::string body;
  2989. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2990. body.append(data, data_length);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2994. EXPECT_EQ(StatusCode::Found_302, res->status);
  2995. EXPECT_EQ("___", body);
  2996. }
  2997. }
  2998. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2999. Server svr;
  3000. auto port_str = std::to_string(PORT);
  3001. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3002. auto expected_host = "[::1]:" + port_str;
  3003. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3004. res.set_content("___", "text/plain");
  3005. // res.set_redirect("/2");
  3006. res.set_redirect(redirect_url);
  3007. });
  3008. svr.Get("/2", [&](const Request &req, Response &res) {
  3009. auto host_header = req.headers.find("Host");
  3010. ASSERT_TRUE(host_header != req.headers.end());
  3011. EXPECT_EQ(expected_host, host_header->second);
  3012. res.set_content("Hello World!", "text/plain");
  3013. });
  3014. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3015. auto se = detail::scope_exit([&] {
  3016. svr.stop();
  3017. th.join();
  3018. ASSERT_FALSE(svr.is_running());
  3019. });
  3020. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3021. // actually starts anything, so the condition !svr.is_running() will
  3022. // always remain true, and the loop never stops.
  3023. // This basically counts how many milliseconds have passed since the
  3024. // call to svr.listen(), and if after 5 seconds nothing started yet
  3025. // aborts the test.
  3026. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3027. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3028. ASSERT_LT(milliseconds, 5000U);
  3029. }
  3030. {
  3031. Client cli("::1", PORT);
  3032. cli.set_follow_location(true);
  3033. std::string body;
  3034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3035. body.append(data, data_length);
  3036. return true;
  3037. });
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::OK_200, res->status);
  3040. EXPECT_EQ("Hello World!", body);
  3041. }
  3042. {
  3043. Client cli("::1", PORT);
  3044. std::string body;
  3045. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3046. body.append(data, data_length);
  3047. return true;
  3048. });
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::Found_302, res->status);
  3051. EXPECT_EQ("___", body);
  3052. }
  3053. }
  3054. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3055. Server svr;
  3056. svr.Get("/foo", [](const Request &req, Response &res) {
  3057. auto a = req.params.find("a");
  3058. if (a != req.params.end()) {
  3059. res.set_content((*a).second, "text/plain");
  3060. res.status = StatusCode::OK_200;
  3061. } else {
  3062. res.status = StatusCode::BadRequest_400;
  3063. }
  3064. });
  3065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. {
  3073. Client cli(HOST, PORT);
  3074. cli.set_path_encode(false);
  3075. auto res = cli.Get("/foo?a=explicitly+encoded");
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. // This expects it back with a space, as the `+` won't have been
  3079. // url-encoded, and server-side the params get decoded turning `+`
  3080. // into spaces.
  3081. EXPECT_EQ("explicitly encoded", res->body);
  3082. }
  3083. }
  3084. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3085. // When path encoding is disabled the client must transmit the supplied
  3086. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3087. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3088. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3089. // than a space (0x20). Assert on the raw wire target to catch this.
  3090. Server svr;
  3091. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3092. svr.Get("/foo", [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(expected_target, req.target);
  3094. res.status = StatusCode::OK_200;
  3095. });
  3096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. thread.join();
  3100. ASSERT_FALSE(svr.is_running());
  3101. });
  3102. svr.wait_until_ready();
  3103. {
  3104. Client cli(HOST, PORT);
  3105. cli.set_path_encode(false);
  3106. auto res = cli.Get(expected_target.c_str());
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. }
  3110. }
  3111. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3112. // `open_stream()` used to skip the path encoding that the buffered send
  3113. // path applies, so the same `path` produced different bytes in the request
  3114. // line depending on which API was used. Assert the two agree.
  3115. Server svr;
  3116. std::string target;
  3117. svr.Get(".*", [&](const Request &req, Response &res) {
  3118. target = req.target;
  3119. res.status = StatusCode::OK_200;
  3120. });
  3121. auto port = svr.bind_to_any_port(HOST);
  3122. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. struct {
  3130. const char *path;
  3131. const char *expected;
  3132. } cases[] = {
  3133. {"/a b?x=1", "/a%20b?x=1"},
  3134. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3135. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3136. };
  3137. for (const auto &c : cases) {
  3138. Client cli(HOST, port);
  3139. target.clear();
  3140. auto res = cli.Get(c.path);
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3143. auto buffered_target = target;
  3144. target.clear();
  3145. auto handle = cli.open_stream("GET", c.path);
  3146. EXPECT_TRUE(handle.is_valid())
  3147. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3148. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3149. }
  3150. }
  3151. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3152. // The `set_path_encode(false)` contract — transmit the supplied target
  3153. // verbatim — must hold for the streaming API too.
  3154. Server svr;
  3155. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3156. std::string target;
  3157. svr.Get("/foo", [&](const Request &req, Response &res) {
  3158. target = req.target;
  3159. res.status = StatusCode::OK_200;
  3160. });
  3161. auto port = svr.bind_to_any_port(HOST);
  3162. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. thread.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. {
  3170. Client cli(HOST, port);
  3171. cli.set_path_encode(false);
  3172. auto handle = cli.open_stream("GET", expected_target);
  3173. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3174. EXPECT_EQ(expected_target, target);
  3175. }
  3176. }
  3177. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3178. // With path encoding enabled a CR/LF in the target is percent-encoded
  3179. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3180. // write_request_line still backstops `set_path_encode(false)`, which is
  3181. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3182. Server svr;
  3183. // Captured before routing: the decoded path contains a newline, which a
  3184. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3185. std::string target;
  3186. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3187. target = req.target;
  3188. res.status = StatusCode::OK_200;
  3189. return Server::HandlerResponse::Handled;
  3190. });
  3191. auto port = svr.bind_to_any_port(HOST);
  3192. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3193. auto se = detail::scope_exit([&] {
  3194. svr.stop();
  3195. thread.join();
  3196. ASSERT_FALSE(svr.is_running());
  3197. });
  3198. svr.wait_until_ready();
  3199. {
  3200. Client cli(HOST, port);
  3201. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3202. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3203. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3204. }
  3205. }
  3206. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3207. // Nothing may reach the wire: a raw CR/LF target would split the request
  3208. // line and inject headers.
  3209. Server svr;
  3210. // Pre-routing so that "not called" means nothing reached the server at all,
  3211. // rather than merely failing to match a handler pattern.
  3212. auto handler_called = false;
  3213. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3214. handler_called = true;
  3215. res.status = StatusCode::OK_200;
  3216. return Server::HandlerResponse::Handled;
  3217. });
  3218. auto port = svr.bind_to_any_port(HOST);
  3219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3220. auto se = detail::scope_exit([&] {
  3221. svr.stop();
  3222. thread.join();
  3223. ASSERT_FALSE(svr.is_running());
  3224. });
  3225. svr.wait_until_ready();
  3226. {
  3227. Client cli(HOST, port);
  3228. cli.set_path_encode(false);
  3229. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3230. EXPECT_FALSE(handle.is_valid());
  3231. EXPECT_EQ(Error::Write, handle.error);
  3232. EXPECT_FALSE(handler_called);
  3233. }
  3234. }
  3235. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3236. // Which of the two branches runs is decided by whether the query component
  3237. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3238. // an empty query and must still fall back to building one from
  3239. // `req.params`, while a non-empty query must win over `req.params`.
  3240. Server svr;
  3241. std::string target;
  3242. svr.Get("/foo", [&](const Request &req, Response &res) {
  3243. target = req.target;
  3244. res.status = StatusCode::OK_200;
  3245. });
  3246. auto port = svr.bind_to_any_port(HOST);
  3247. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3248. auto se = detail::scope_exit([&] {
  3249. svr.stop();
  3250. thread.join();
  3251. ASSERT_FALSE(svr.is_running());
  3252. });
  3253. svr.wait_until_ready();
  3254. {
  3255. // Trailing `?` -> empty query component -> `req.params` is used.
  3256. Client cli(HOST, port);
  3257. Request req;
  3258. req.method = "GET";
  3259. req.path = "/foo?";
  3260. req.params.emplace("a", "1");
  3261. target.clear();
  3262. auto res = cli.send(req);
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ("/foo?a=1", target);
  3265. }
  3266. {
  3267. // Non-empty query in `req.path` -> `req.params` is not appended.
  3268. Client cli(HOST, port);
  3269. Request req;
  3270. req.method = "GET";
  3271. req.path = "/foo?b=2";
  3272. req.params.emplace("a", "1");
  3273. target.clear();
  3274. auto res = cli.send(req);
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ("/foo?b=2", target);
  3277. }
  3278. }
  3279. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3280. Server svr;
  3281. svr.Get("/", [](const Request &req, Response &) {
  3282. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3283. });
  3284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3285. auto se = detail::scope_exit([&] {
  3286. svr.stop();
  3287. thread.join();
  3288. ASSERT_FALSE(svr.is_running());
  3289. });
  3290. svr.wait_until_ready();
  3291. {
  3292. Client cli(HOST, PORT);
  3293. cli.set_path_encode(false);
  3294. auto res = cli.Get("/?something=%0A");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. }
  3299. TEST(BindServerTest, BindDualStack) {
  3300. Server svr;
  3301. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content("Hello World!", "text/plain");
  3303. });
  3304. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. {
  3312. Client cli("127.0.0.1", PORT);
  3313. auto res = cli.Get("/1");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ("Hello World!", res->body);
  3317. }
  3318. {
  3319. Client cli("::1", PORT);
  3320. auto res = cli.Get("/1");
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. EXPECT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ("Hello World!", res->body);
  3324. }
  3325. }
  3326. TEST(BindServerTest, BindAndListenSeparately) {
  3327. Server svr;
  3328. int port = svr.bind_to_any_port("0.0.0.0");
  3329. ASSERT_TRUE(svr.is_valid());
  3330. ASSERT_TRUE(port > 0);
  3331. svr.stop();
  3332. }
  3333. // Reports whether anything is still listening on a loopback port. A plain
  3334. // connect() is used instead of a Client request because a socket left bound by
  3335. // mistake accepts the connection into its backlog and never answers, which
  3336. // would hang the test instead of failing it.
  3337. static bool is_loopback_port_accepting(int port) {
  3338. sockaddr_in addr{};
  3339. addr.sin_family = AF_INET;
  3340. addr.sin_port = htons(static_cast<uint16_t>(port));
  3341. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3342. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3343. EXPECT_NE(sock, INVALID_SOCKET);
  3344. if (sock == INVALID_SOCKET) { return false; }
  3345. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3346. static_cast<socklen_t>(sizeof(addr)));
  3347. detail::close_socket(sock);
  3348. return ret == 0;
  3349. }
  3350. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3351. Server svr;
  3352. auto port = svr.bind_to_any_port("127.0.0.1");
  3353. ASSERT_TRUE(port > 0);
  3354. svr.stop();
  3355. // bind_to_any_port() already called listen(2), so until stop() closed the
  3356. // descriptor the port kept accepting connections into the backlog. ASSERT
  3357. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3358. // below blocks forever in the accept loop.
  3359. ASSERT_FALSE(is_loopback_port_accepting(port));
  3360. // Nothing is left to accept on, so listen_after_bind() must report failure
  3361. // instead of returning success without ever serving.
  3362. EXPECT_FALSE(svr.listen_after_bind());
  3363. // The failed listen marks the server decommissioned, so a waiter returns
  3364. // instead of spinning forever.
  3365. svr.wait_until_ready();
  3366. }
  3367. #ifdef CPPHTTPLIB_SSL_ENABLED
  3368. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3370. CLIENT_CA_CERT_DIR);
  3371. int port = svr.bind_to_any_port("0.0.0.0");
  3372. ASSERT_TRUE(svr.is_valid());
  3373. ASSERT_TRUE(port > 0);
  3374. svr.stop();
  3375. }
  3376. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3377. // or a rejected CustomRoute() registration would not stop the server binding.
  3378. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3380. CLIENT_CA_CERT_DIR);
  3381. ASSERT_TRUE(svr.is_valid());
  3382. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3383. EXPECT_FALSE(svr.is_valid());
  3384. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3385. }
  3386. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3387. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3388. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3389. int port = svr.bind_to_any_port("0.0.0.0");
  3390. ASSERT_TRUE(svr.is_valid());
  3391. ASSERT_TRUE(port > 0);
  3392. svr.stop();
  3393. }
  3394. TEST(BindServerTest, UpdateCertsPem) {
  3395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3396. int port = svr.bind_to_any_port("0.0.0.0");
  3397. ASSERT_TRUE(svr.is_valid());
  3398. ASSERT_TRUE(port > 0);
  3399. // Read PEM files
  3400. std::string cert_pem, key_pem, ca_pem;
  3401. read_file(SERVER_CERT_FILE, cert_pem);
  3402. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3403. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3404. // Update server certificates using PEM API
  3405. ASSERT_TRUE(
  3406. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3407. ASSERT_TRUE(svr.is_valid());
  3408. svr.stop();
  3409. }
  3410. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3411. // Start server with client CA (enables client auth)
  3412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3413. ASSERT_TRUE(svr.is_valid());
  3414. bool handler_called = false;
  3415. svr.Get("/test", [&](const Request &req, Response &res) {
  3416. handler_called = true;
  3417. // Verify client certificate is present
  3418. auto cert = req.peer_cert();
  3419. EXPECT_TRUE(static_cast<bool>(cert));
  3420. res.set_content("ok", "text/plain");
  3421. });
  3422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3423. auto se = detail::scope_exit([&] {
  3424. svr.stop();
  3425. t.join();
  3426. ASSERT_FALSE(svr.is_running());
  3427. });
  3428. svr.wait_until_ready();
  3429. // Read PEM files
  3430. std::string cert_pem, key_pem, ca_pem;
  3431. read_file(SERVER_CERT_FILE, cert_pem);
  3432. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3433. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3434. // Update server certificates and client CA using PEM API while server running
  3435. ASSERT_TRUE(
  3436. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3437. // Connect with client certificate
  3438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3439. cli.enable_server_certificate_verification(false);
  3440. cli.set_connection_timeout(30);
  3441. auto res = cli.Get("/test");
  3442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3443. ASSERT_EQ(StatusCode::OK_200, res->status);
  3444. ASSERT_TRUE(handler_called);
  3445. EXPECT_EQ("ok", res->body);
  3446. }
  3447. #endif
  3448. TEST(ErrorHandlerTest, ContentLength) {
  3449. Server svr;
  3450. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3451. res.status = StatusCode::OK_200;
  3452. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3453. "text/html"); // <= Content-Length still 13
  3454. });
  3455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3456. res.set_content("Hello World!\n", "text/plain");
  3457. res.status = 524;
  3458. });
  3459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. {
  3467. Client cli(HOST, PORT);
  3468. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3473. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3474. }
  3475. }
  3476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3477. TEST(ExceptionTest, WithoutExceptionHandler) {
  3478. Server svr;
  3479. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3480. throw std::runtime_error("exception...");
  3481. });
  3482. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3483. throw std::runtime_error("exception\r\n...");
  3484. });
  3485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. listen_thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. svr.wait_until_ready();
  3492. Client cli("localhost", PORT);
  3493. {
  3494. auto res = cli.Get("/exception");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3497. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3498. }
  3499. {
  3500. auto res = cli.Get("/unknown");
  3501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3503. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3504. }
  3505. }
  3506. TEST(ExceptionTest, WithExceptionHandler) {
  3507. Server svr;
  3508. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3509. std::exception_ptr ep) {
  3510. EXPECT_FALSE(ep == nullptr);
  3511. try {
  3512. std::rethrow_exception(ep);
  3513. } catch (std::exception &e) {
  3514. EXPECT_EQ("abc", std::string(e.what()));
  3515. } catch (...) {}
  3516. res.status = StatusCode::InternalServerError_500;
  3517. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3518. "text/html"); // <= Content-Length still 13 at this point
  3519. });
  3520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3521. res.set_content("Hello World!\n", "text/plain");
  3522. throw std::runtime_error("abc");
  3523. });
  3524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3525. auto se = detail::scope_exit([&] {
  3526. svr.stop();
  3527. thread.join();
  3528. ASSERT_FALSE(svr.is_running());
  3529. });
  3530. svr.wait_until_ready();
  3531. for (size_t i = 0; i < 10; i++) {
  3532. Client cli(HOST, PORT);
  3533. for (size_t j = 0; j < 100; j++) {
  3534. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3539. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3540. }
  3541. cli.set_keep_alive(true);
  3542. for (size_t j = 0; j < 100; j++) {
  3543. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3545. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3546. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3547. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3548. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3549. }
  3550. }
  3551. }
  3552. TEST(ExceptionTest, AndErrorHandler) {
  3553. Server svr;
  3554. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3555. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3556. });
  3557. svr.set_exception_handler(
  3558. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3559. EXPECT_FALSE(ep == nullptr);
  3560. try {
  3561. std::rethrow_exception(ep);
  3562. } catch (std::exception &e) {
  3563. res.set_content(e.what(), "text/html");
  3564. } catch (...) {}
  3565. res.status = StatusCode::InternalServerError_500;
  3566. });
  3567. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3568. throw std::runtime_error("EXCEPTION");
  3569. });
  3570. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3571. res.set_content("ERROR", "text/html");
  3572. res.status = StatusCode::InternalServerError_500;
  3573. });
  3574. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. thread.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. Client cli(HOST, PORT);
  3582. {
  3583. auto res = cli.Get("/exception");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3586. EXPECT_EQ("EXCEPTION", res->body);
  3587. }
  3588. {
  3589. auto res = cli.Get("/error");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3592. EXPECT_EQ("ERROR", res->body);
  3593. }
  3594. {
  3595. auto res = cli.Get("/invalid");
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3598. EXPECT_EQ("NOT_FOUND", res->body);
  3599. }
  3600. }
  3601. #endif
  3602. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3603. // process_request() wraps only routing() in a try/catch, so an exception from
  3604. // any other user callback used to unwind into the task queue - which does not
  3605. // catch - and terminate the process. Each test below runs the server on a
  3606. // single worker thread: a guard that catches the exception but still loses the
  3607. // thread would otherwise be hidden by a spare worker serving the follow-up
  3608. // request. Note that a regression here aborts the whole test binary rather
  3609. // than failing one test.
  3610. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3611. Server svr;
  3612. svr.new_task_queue = [] { return new ThreadPool(1); };
  3613. std::atomic<int> reported{0};
  3614. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3615. if (err == Error::UserCallbackException) { reported++; }
  3616. });
  3617. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3618. res.set_content_provider(
  3619. 1024, "text/plain",
  3620. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3621. sink.write("hello", 5);
  3622. throw std::runtime_error("from the content provider");
  3623. });
  3624. });
  3625. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3626. res.set_content("ok", "text/plain");
  3627. });
  3628. auto port = svr.bind_to_any_port(HOST);
  3629. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3630. auto se = detail::scope_exit([&] {
  3631. svr.stop();
  3632. listen_thread.join();
  3633. ASSERT_FALSE(svr.is_running());
  3634. });
  3635. svr.wait_until_ready();
  3636. {
  3637. Client cli(HOST, port);
  3638. cli.set_read_timeout(5, 0);
  3639. EXPECT_FALSE(cli.Get("/throw"));
  3640. }
  3641. EXPECT_TRUE(svr.is_running());
  3642. EXPECT_EQ(1, reported.load());
  3643. // A request on a fresh connection is still served.
  3644. {
  3645. Client cli(HOST, port);
  3646. auto res = cli.Get("/ok");
  3647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3648. EXPECT_EQ(StatusCode::OK_200, res->status);
  3649. EXPECT_EQ("ok", res->body);
  3650. }
  3651. }
  3652. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3653. Server svr;
  3654. svr.new_task_queue = [] { return new ThreadPool(1); };
  3655. std::atomic<bool> should_throw{true};
  3656. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3657. res.set_content("hi", "text/plain");
  3658. });
  3659. svr.set_post_routing_handler(
  3660. [&](const Request & /*req*/, Response & /*res*/) {
  3661. if (should_throw) {
  3662. throw std::runtime_error("from the post-routing handler");
  3663. }
  3664. });
  3665. auto port = svr.bind_to_any_port(HOST);
  3666. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3667. auto se = detail::scope_exit([&] {
  3668. svr.stop();
  3669. listen_thread.join();
  3670. ASSERT_FALSE(svr.is_running());
  3671. });
  3672. svr.wait_until_ready();
  3673. {
  3674. Client cli(HOST, port);
  3675. cli.set_read_timeout(5, 0);
  3676. EXPECT_FALSE(cli.Get("/hi"));
  3677. }
  3678. EXPECT_TRUE(svr.is_running());
  3679. should_throw = false;
  3680. {
  3681. Client cli(HOST, port);
  3682. auto res = cli.Get("/hi");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ("hi", res->body);
  3686. }
  3687. }
  3688. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3689. // The guard reports the caught exception through the error logger, which is
  3690. // a user callback too. A logger that throws has to be contained as well, or
  3691. // the process would terminate from inside the catch.
  3692. Server svr;
  3693. svr.new_task_queue = [] { return new ThreadPool(1); };
  3694. std::atomic<int> reported{0};
  3695. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3696. if (err == Error::UserCallbackException) {
  3697. reported++;
  3698. throw std::runtime_error("from the error logger");
  3699. }
  3700. });
  3701. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3702. res.set_content_provider(
  3703. 1024, "text/plain",
  3704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3705. sink.write("hello", 5);
  3706. throw std::runtime_error("from the content provider");
  3707. });
  3708. });
  3709. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3710. res.set_content("ok", "text/plain");
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. listen_thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. {
  3721. Client cli(HOST, port);
  3722. cli.set_read_timeout(5, 0);
  3723. EXPECT_FALSE(cli.Get("/throw"));
  3724. }
  3725. EXPECT_TRUE(svr.is_running());
  3726. EXPECT_EQ(1, reported.load());
  3727. {
  3728. Client cli(HOST, port);
  3729. auto res = cli.Get("/ok");
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("ok", res->body);
  3733. }
  3734. }
  3735. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3736. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3737. // so the exception unwinds through the ws::WebSocket object on its way to
  3738. // the guard. None of the HTTP cases above cross that.
  3739. Server svr;
  3740. svr.new_task_queue = [] { return new ThreadPool(1); };
  3741. std::atomic<int> reported{0};
  3742. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3743. if (err == Error::UserCallbackException) { reported++; }
  3744. });
  3745. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3746. throw std::runtime_error("from the WebSocket handler");
  3747. });
  3748. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3749. res.set_content("ok", "text/plain");
  3750. });
  3751. auto port = svr.bind_to_any_port(HOST);
  3752. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3753. auto se = detail::scope_exit([&] {
  3754. svr.stop();
  3755. listen_thread.join();
  3756. ASSERT_FALSE(svr.is_running());
  3757. });
  3758. svr.wait_until_ready();
  3759. {
  3760. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3761. "/ws");
  3762. auto res = client.connect();
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. // The server dropped the connection instead of dying.
  3765. std::string msg;
  3766. EXPECT_FALSE(client.read(msg));
  3767. client.close();
  3768. }
  3769. EXPECT_TRUE(svr.is_running());
  3770. EXPECT_EQ(1, reported.load());
  3771. {
  3772. Client cli(HOST, port);
  3773. auto res = cli.Get("/ok");
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. EXPECT_EQ("ok", res->body);
  3777. }
  3778. }
  3779. #ifdef CPPHTTPLIB_SSL_ENABLED
  3780. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3781. // SSLServer::process_and_close_socket() is a separate overload with its own
  3782. // guard, so it is exercised on its own.
  3783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3784. ASSERT_TRUE(svr.is_valid());
  3785. svr.new_task_queue = [] { return new ThreadPool(1); };
  3786. std::atomic<int> reported{0};
  3787. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3788. if (err == Error::UserCallbackException) { reported++; }
  3789. });
  3790. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3791. res.set_content_provider(
  3792. 1024, "text/plain",
  3793. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3794. sink.write("hello", 5);
  3795. throw std::runtime_error("from the content provider");
  3796. });
  3797. });
  3798. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3799. res.set_content("ok", "text/plain");
  3800. });
  3801. auto port = svr.bind_to_any_port(HOST);
  3802. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3803. auto se = detail::scope_exit([&] {
  3804. svr.stop();
  3805. listen_thread.join();
  3806. ASSERT_FALSE(svr.is_running());
  3807. });
  3808. svr.wait_until_ready();
  3809. {
  3810. SSLClient cli(HOST, port);
  3811. cli.enable_server_certificate_verification(false);
  3812. cli.set_read_timeout(5, 0);
  3813. EXPECT_FALSE(cli.Get("/throw"));
  3814. }
  3815. EXPECT_TRUE(svr.is_running());
  3816. EXPECT_EQ(1, reported.load());
  3817. {
  3818. SSLClient cli(HOST, port);
  3819. cli.enable_server_certificate_verification(false);
  3820. auto res = cli.Get("/ok");
  3821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. EXPECT_EQ("ok", res->body);
  3824. }
  3825. }
  3826. #endif
  3827. #endif
  3828. TEST(NoContentTest, ContentLength) {
  3829. Server svr;
  3830. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3831. res.status = StatusCode::NoContent_204;
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. {
  3841. Client cli(HOST, PORT);
  3842. auto res = cli.Get("/hi");
  3843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3844. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3845. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3846. }
  3847. }
  3848. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3849. #ifdef CPPHTTPLIB_SSL_ENABLED
  3850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3851. ASSERT_TRUE(svr.is_valid());
  3852. #else
  3853. Server svr;
  3854. #endif
  3855. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3856. if (req.path == "/routing_handler") {
  3857. res.set_header("PRE_ROUTING", "on");
  3858. res.set_content("Routing Handler", "text/plain");
  3859. return httplib::Server::HandlerResponse::Handled;
  3860. }
  3861. return httplib::Server::HandlerResponse::Unhandled;
  3862. });
  3863. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3864. res.set_content("Error", "text/html");
  3865. });
  3866. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3867. if (req.path == "/routing_handler") {
  3868. res.set_header("POST_ROUTING", "on");
  3869. }
  3870. });
  3871. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3872. res.set_content("Hello World!\n", "text/plain");
  3873. });
  3874. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3875. auto se = detail::scope_exit([&] {
  3876. svr.stop();
  3877. thread.join();
  3878. ASSERT_FALSE(svr.is_running());
  3879. });
  3880. svr.wait_until_ready();
  3881. {
  3882. #ifdef CPPHTTPLIB_SSL_ENABLED
  3883. SSLClient cli(HOST, PORT);
  3884. cli.enable_server_certificate_verification(false);
  3885. #else
  3886. Client cli(HOST, PORT);
  3887. #endif
  3888. auto res = cli.Get("/routing_handler");
  3889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3890. EXPECT_EQ(StatusCode::OK_200, res->status);
  3891. EXPECT_EQ("Routing Handler", res->body);
  3892. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3893. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3894. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3895. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3896. }
  3897. {
  3898. #ifdef CPPHTTPLIB_SSL_ENABLED
  3899. SSLClient cli(HOST, PORT);
  3900. cli.enable_server_certificate_verification(false);
  3901. #else
  3902. Client cli(HOST, PORT);
  3903. #endif
  3904. auto res = cli.Get("/hi");
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ(StatusCode::OK_200, res->status);
  3907. EXPECT_EQ("Hello World!\n", res->body);
  3908. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3909. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3910. }
  3911. {
  3912. #ifdef CPPHTTPLIB_SSL_ENABLED
  3913. SSLClient cli(HOST, PORT);
  3914. cli.enable_server_certificate_verification(false);
  3915. #else
  3916. Client cli(HOST, PORT);
  3917. #endif
  3918. auto res = cli.Get("/aaa");
  3919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3921. EXPECT_EQ("Error", res->body);
  3922. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3923. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3924. }
  3925. }
  3926. TEST(RequestHandlerTest, PreRequestHandler) {
  3927. auto route_path = "/user/:user";
  3928. Server svr;
  3929. svr.Get("/hi", [](const Request &, Response &res) {
  3930. res.set_content("hi", "text/plain");
  3931. });
  3932. svr.Get(route_path, [](const Request &req, Response &res) {
  3933. res.set_content(req.path_params.at("user"), "text/plain");
  3934. });
  3935. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3936. if (req.matched_route == route_path) {
  3937. auto user = req.path_params.at("user");
  3938. if (user != "john") {
  3939. res.status = StatusCode::Forbidden_403;
  3940. res.set_content("error", "text/html");
  3941. return Server::HandlerResponse::Handled;
  3942. }
  3943. }
  3944. return Server::HandlerResponse::Unhandled;
  3945. });
  3946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3947. auto se = detail::scope_exit([&] {
  3948. svr.stop();
  3949. thread.join();
  3950. ASSERT_FALSE(svr.is_running());
  3951. });
  3952. svr.wait_until_ready();
  3953. Client cli(HOST, PORT);
  3954. {
  3955. auto res = cli.Get("/hi");
  3956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. EXPECT_EQ("hi", res->body);
  3959. }
  3960. {
  3961. auto res = cli.Get("/user/john");
  3962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. EXPECT_EQ("john", res->body);
  3965. }
  3966. {
  3967. auto res = cli.Get("/user/invalid-user");
  3968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3969. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3970. EXPECT_EQ("error", res->body);
  3971. }
  3972. }
  3973. // The pre-request handler must run before the request body is read, so a
  3974. // rejected request never forces the server to buffer a (potentially large)
  3975. // body. Here the posted body is larger than the payload limit: if the body
  3976. // were read first the server would answer 413, but because the pre-request
  3977. // handler runs first it answers 403 and the body is never read.
  3978. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3979. Server svr;
  3980. svr.set_payload_max_length(8);
  3981. auto handler_ran = false;
  3982. svr.Post("/reject", [&](const Request &req, Response &res) {
  3983. handler_ran = true;
  3984. res.set_content(req.body, "text/plain");
  3985. });
  3986. svr.Post("/accept", [](const Request &req, Response &res) {
  3987. res.set_content(req.body, "text/plain");
  3988. });
  3989. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3990. if (req.matched_route == "/reject") {
  3991. res.status = StatusCode::Forbidden_403;
  3992. res.set_content("denied", "text/plain");
  3993. return Server::HandlerResponse::Handled;
  3994. }
  3995. return Server::HandlerResponse::Unhandled;
  3996. });
  3997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3998. auto se = detail::scope_exit([&] {
  3999. svr.stop();
  4000. thread.join();
  4001. ASSERT_FALSE(svr.is_running());
  4002. });
  4003. svr.wait_until_ready();
  4004. Client cli(HOST, PORT);
  4005. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4006. // rejects with 403 before the body is read, so 413 is never reached.
  4007. {
  4008. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4010. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4011. EXPECT_EQ("denied", res->body);
  4012. EXPECT_FALSE(handler_ran);
  4013. }
  4014. // An approved route still reads the body and enforces the payload limit.
  4015. {
  4016. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4018. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4019. }
  4020. }
  4021. TEST(UserDataTest, BasicOperations) {
  4022. httplib::UserData ud;
  4023. // Initially empty
  4024. EXPECT_FALSE(ud.has("key"));
  4025. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4026. // set and get
  4027. ud.set("key", 42);
  4028. EXPECT_TRUE(ud.has("key"));
  4029. auto *p = ud.get<int>("key");
  4030. ASSERT_NE(nullptr, p);
  4031. EXPECT_EQ(42, *p);
  4032. // Type mismatch → nullptr
  4033. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4034. // Overwrite with different type
  4035. ud.set("key", std::string("hello"));
  4036. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4037. auto *s = ud.get<std::string>("key");
  4038. ASSERT_NE(nullptr, s);
  4039. EXPECT_EQ("hello", *s);
  4040. // erase
  4041. ud.erase("key");
  4042. EXPECT_FALSE(ud.has("key"));
  4043. // clear
  4044. ud.set("a", 1);
  4045. ud.set("b", 2);
  4046. ud.clear();
  4047. EXPECT_FALSE(ud.has("a"));
  4048. EXPECT_FALSE(ud.has("b"));
  4049. }
  4050. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4051. struct AuthCtx {
  4052. std::string user_id;
  4053. };
  4054. Server svr;
  4055. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4056. res.user_data.set("auth", AuthCtx{"alice"});
  4057. return Server::HandlerResponse::Unhandled;
  4058. });
  4059. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4060. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4061. ASSERT_NE(nullptr, ctx);
  4062. res.set_content("Hello " + ctx->user_id, "text/plain");
  4063. });
  4064. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4065. auto se = detail::scope_exit([&] {
  4066. svr.stop();
  4067. thread.join();
  4068. ASSERT_FALSE(svr.is_running());
  4069. });
  4070. svr.wait_until_ready();
  4071. Client cli(HOST, PORT);
  4072. auto res = cli.Get("/me");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. EXPECT_EQ("Hello alice", res->body);
  4076. }
  4077. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4078. struct RoleCtx {
  4079. std::string role;
  4080. };
  4081. Server svr;
  4082. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4083. res.user_data.set("role", RoleCtx{"admin"});
  4084. return Server::HandlerResponse::Unhandled;
  4085. });
  4086. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4087. auto *ctx = res.user_data.get<RoleCtx>("role");
  4088. ASSERT_NE(nullptr, ctx);
  4089. res.set_content(ctx->role, "text/plain");
  4090. });
  4091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4092. auto se = detail::scope_exit([&] {
  4093. svr.stop();
  4094. thread.join();
  4095. ASSERT_FALSE(svr.is_running());
  4096. });
  4097. svr.wait_until_ready();
  4098. Client cli(HOST, PORT);
  4099. auto res = cli.Get("/role");
  4100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4101. EXPECT_EQ(StatusCode::OK_200, res->status);
  4102. EXPECT_EQ("admin", res->body);
  4103. }
  4104. TEST(InvalidFormatTest, StatusCode) {
  4105. Server svr;
  4106. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4107. res.set_content("Hello World!\n", "text/plain");
  4108. res.status = 9999; // Status should be a three-digit code...
  4109. });
  4110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. {
  4118. Client cli(HOST, PORT);
  4119. auto res = cli.Get("/hi");
  4120. ASSERT_FALSE(res);
  4121. }
  4122. }
  4123. TEST(URLFragmentTest, WithFragment) {
  4124. Server svr;
  4125. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4126. EXPECT_TRUE(req.target == "/hi");
  4127. });
  4128. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. thread.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. {
  4136. Client cli(HOST, PORT);
  4137. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4138. EXPECT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. res = cli.Get("/hi%23key1=val1=key2=val2");
  4141. EXPECT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4143. }
  4144. }
  4145. TEST(HeaderWriter, SetHeaderWriter) {
  4146. Server svr;
  4147. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4148. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4149. return detail::write_headers(strm, hdrs);
  4150. });
  4151. svr.Get("/hi", [](const Request &req, Response &res) {
  4152. auto it = req.headers.find("CustomClientHeader");
  4153. EXPECT_TRUE(it != req.headers.end());
  4154. EXPECT_EQ(it->second, "CustomClientValue");
  4155. res.set_content("Hello World!\n", "text/plain");
  4156. });
  4157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4158. auto se = detail::scope_exit([&] {
  4159. svr.stop();
  4160. thread.join();
  4161. ASSERT_FALSE(svr.is_running());
  4162. });
  4163. svr.wait_until_ready();
  4164. {
  4165. Client cli(HOST, PORT);
  4166. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4167. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4168. return detail::write_headers(strm, hdrs);
  4169. });
  4170. auto res = cli.Get("/hi");
  4171. EXPECT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. auto it = res->headers.find("CustomServerHeader");
  4174. EXPECT_TRUE(it != res->headers.end());
  4175. EXPECT_EQ(it->second, "CustomServerValue");
  4176. }
  4177. }
  4178. class ServerTest : public ::testing::Test {
  4179. protected:
  4180. ServerTest()
  4181. : cli_(HOST, PORT)
  4182. #ifdef CPPHTTPLIB_SSL_ENABLED
  4183. ,
  4184. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4185. #endif
  4186. {
  4187. #ifdef CPPHTTPLIB_SSL_ENABLED
  4188. cli_.enable_server_certificate_verification(false);
  4189. #endif
  4190. // Allow LARGE_DATA (100MB) responses
  4191. cli_.set_payload_max_length(200 * 1024 * 1024);
  4192. }
  4193. virtual void SetUp() {
  4194. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4195. svr_.set_payload_max_length(200 * 1024 * 1024);
  4196. svr_.set_mount_point("/", "./www");
  4197. svr_.set_mount_point("/mount", "./www2");
  4198. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4199. svr_.Get("/hi",
  4200. [&](const Request & /*req*/, Response &res) {
  4201. res.set_content("Hello World!", "text/plain");
  4202. })
  4203. .Get("/file_content",
  4204. [&](const Request & /*req*/, Response &res) {
  4205. res.set_file_content("./www/dir/test.html");
  4206. })
  4207. .Get("/file_content_with_content_type",
  4208. [&](const Request & /*req*/, Response &res) {
  4209. res.set_file_content("./www/file", "text/plain");
  4210. })
  4211. .Get("/invalid_file_content",
  4212. [&](const Request & /*req*/, Response &res) {
  4213. res.set_file_content("./www/dir/invalid_file_path");
  4214. })
  4215. .Get("/http_response_splitting",
  4216. [&](const Request & /*req*/, Response &res) {
  4217. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4218. EXPECT_EQ(0U, res.headers.size());
  4219. EXPECT_FALSE(res.has_header("a"));
  4220. res.set_header("a", "1\nSet-Cookie: a=1");
  4221. EXPECT_EQ(0U, res.headers.size());
  4222. EXPECT_FALSE(res.has_header("a"));
  4223. res.set_header("a", "1\rSet-Cookie: a=1");
  4224. EXPECT_EQ(0U, res.headers.size());
  4225. EXPECT_FALSE(res.has_header("a"));
  4226. res.set_header("a\r\nb", "0");
  4227. EXPECT_EQ(0U, res.headers.size());
  4228. EXPECT_FALSE(res.has_header("a"));
  4229. res.set_header("a\rb", "0");
  4230. EXPECT_EQ(0U, res.headers.size());
  4231. EXPECT_FALSE(res.has_header("a"));
  4232. res.set_header("a\nb", "0");
  4233. EXPECT_EQ(0U, res.headers.size());
  4234. EXPECT_FALSE(res.has_header("a"));
  4235. res.set_redirect("1\r\nSet-Cookie: a=1");
  4236. EXPECT_EQ(0U, res.headers.size());
  4237. EXPECT_FALSE(res.has_header("Location"));
  4238. })
  4239. .Get("/slow",
  4240. [&](const Request & /*req*/, Response &res) {
  4241. std::this_thread::sleep_for(std::chrono::seconds(4));
  4242. res.set_content("slow", "text/plain");
  4243. })
  4244. #if 0
  4245. .Post("/slowpost",
  4246. [&](const Request & /*req*/, Response &res) {
  4247. std::this_thread::sleep_for(std::chrono::seconds(2));
  4248. res.set_content("slow", "text/plain");
  4249. })
  4250. #endif
  4251. .Get("/remote_addr",
  4252. [&](const Request &req, Response &res) {
  4253. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4254. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4255. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4256. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4257. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4258. #endif
  4259. res.set_content(req.remote_addr, "text/plain");
  4260. })
  4261. .Get("/local_addr",
  4262. [&](const Request &req, Response &res) {
  4263. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4264. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4265. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4266. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4267. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4268. #endif
  4269. auto local_addr = req.local_addr;
  4270. auto local_port = std::to_string(req.local_port);
  4271. res.set_content(local_addr.append(":").append(local_port),
  4272. "text/plain");
  4273. })
  4274. .Get("/endwith%",
  4275. [&](const Request & /*req*/, Response &res) {
  4276. res.set_content("Hello World!", "text/plain");
  4277. })
  4278. .Get("/a\\+\\+b",
  4279. [&](const Request &req, Response &res) {
  4280. ASSERT_TRUE(req.has_param("a +b"));
  4281. auto val = req.get_param_value("a +b");
  4282. res.set_content(val, "text/plain");
  4283. })
  4284. .Get("/", [&](const Request & /*req*/,
  4285. Response &res) { res.set_redirect("/hi"); })
  4286. .Post("/1",
  4287. [](const Request & /*req*/, Response &res) {
  4288. res.set_redirect("/2", StatusCode::SeeOther_303);
  4289. })
  4290. .Get("/2",
  4291. [](const Request & /*req*/, Response &res) {
  4292. res.set_content("redirected.", "text/plain");
  4293. res.status = StatusCode::OK_200;
  4294. })
  4295. .Post("/person",
  4296. [&](const Request &req, Response &res) {
  4297. if (req.has_param("name") && req.has_param("note")) {
  4298. persons_[req.get_param_value("name")] =
  4299. req.get_param_value("note");
  4300. } else {
  4301. res.status = StatusCode::BadRequest_400;
  4302. }
  4303. })
  4304. .Put("/person",
  4305. [&](const Request &req, Response &res) {
  4306. if (req.has_param("name") && req.has_param("note")) {
  4307. persons_[req.get_param_value("name")] =
  4308. req.get_param_value("note");
  4309. } else {
  4310. res.status = StatusCode::BadRequest_400;
  4311. }
  4312. })
  4313. .Get("/person/(.*)",
  4314. [&](const Request &req, Response &res) {
  4315. string name = req.matches[1];
  4316. if (persons_.find(name) != persons_.end()) {
  4317. auto note = persons_[name];
  4318. res.set_content(note, "text/plain");
  4319. } else {
  4320. res.status = StatusCode::NotFound_404;
  4321. }
  4322. })
  4323. .Delete("/person",
  4324. [&](const Request &req, Response &res) {
  4325. if (req.has_param("name")) {
  4326. string name = req.get_param_value("name");
  4327. if (persons_.find(name) != persons_.end()) {
  4328. persons_.erase(name);
  4329. res.set_content("DELETED", "text/plain");
  4330. } else {
  4331. res.status = StatusCode::NotFound_404;
  4332. }
  4333. } else {
  4334. res.status = StatusCode::BadRequest_400;
  4335. }
  4336. })
  4337. .Post("/x-www-form-urlencoded-json",
  4338. [&](const Request &req, Response &res) {
  4339. auto json = req.get_param_value("json");
  4340. ASSERT_EQ(JSON_DATA, json);
  4341. res.set_content(json, "appliation/json");
  4342. res.status = StatusCode::OK_200;
  4343. })
  4344. .Get("/streamed-chunked",
  4345. [&](const Request & /*req*/, Response &res) {
  4346. res.set_chunked_content_provider(
  4347. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4348. sink.os << "123";
  4349. sink.os << "456";
  4350. sink.os << "789";
  4351. sink.done();
  4352. return true;
  4353. });
  4354. })
  4355. .Get("/streamed-chunked-with-prohibited-trailer",
  4356. [&](const Request & /*req*/, Response &res) {
  4357. auto i = new int(0);
  4358. // Declare both a prohibited trailer (Content-Length) and an
  4359. // allowed one
  4360. res.set_header("Trailer", "Content-Length, X-Allowed");
  4361. res.set_chunked_content_provider(
  4362. "text/plain",
  4363. [i](size_t /*offset*/, DataSink &sink) {
  4364. switch (*i) {
  4365. case 0: sink.os << "123"; break;
  4366. case 1: sink.os << "456"; break;
  4367. case 2: sink.os << "789"; break;
  4368. case 3: {
  4369. sink.done_with_trailer(
  4370. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4371. } break;
  4372. }
  4373. (*i)++;
  4374. return true;
  4375. },
  4376. [i](bool success) {
  4377. EXPECT_TRUE(success);
  4378. delete i;
  4379. });
  4380. })
  4381. .Get("/streamed-chunked2",
  4382. [&](const Request & /*req*/, Response &res) {
  4383. auto i = new int(0);
  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: sink.done(); break;
  4392. }
  4393. (*i)++;
  4394. return true;
  4395. },
  4396. [i](bool success) {
  4397. EXPECT_TRUE(success);
  4398. delete i;
  4399. });
  4400. })
  4401. .Get("/streamed-chunked-with-trailer",
  4402. [&](const Request & /*req*/, Response &res) {
  4403. auto i = new int(0);
  4404. res.set_header("Trailer", "Dummy1, Dummy2");
  4405. res.set_chunked_content_provider(
  4406. "text/plain",
  4407. [i](size_t /*offset*/, DataSink &sink) {
  4408. switch (*i) {
  4409. case 0: sink.os << "123"; break;
  4410. case 1: sink.os << "456"; break;
  4411. case 2: sink.os << "789"; break;
  4412. case 3: {
  4413. sink.done_with_trailer(
  4414. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4415. } break;
  4416. }
  4417. (*i)++;
  4418. return true;
  4419. },
  4420. [i](bool success) {
  4421. EXPECT_TRUE(success);
  4422. delete i;
  4423. });
  4424. })
  4425. .Get("/streamed",
  4426. [&](const Request & /*req*/, Response &res) {
  4427. res.set_content_provider(
  4428. 6, "text/plain",
  4429. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4430. sink.os << (offset < 3 ? "a" : "b");
  4431. return true;
  4432. });
  4433. })
  4434. .Get("/streamed-without-length",
  4435. [&](const Request & /*req*/, Response &res) {
  4436. auto data = new std::string("abcdefg");
  4437. res.set_content_provider(
  4438. "text/plain",
  4439. [data](size_t offset, DataSink &sink) {
  4440. if (offset < data->size()) {
  4441. sink.os << data->substr(offset);
  4442. }
  4443. sink.done();
  4444. return true;
  4445. },
  4446. [data](bool success) {
  4447. EXPECT_TRUE(success);
  4448. delete data;
  4449. });
  4450. })
  4451. .Get("/streamed-with-range",
  4452. [&](const Request &req, Response &res) {
  4453. auto data = new std::string("abcdefg");
  4454. // An explicit status keeps the server from picking the 206 it
  4455. // would otherwise choose for a ranged request, so the response
  4456. // is not a partial representation.
  4457. auto status = req.get_param_value("status");
  4458. if (status == "200") {
  4459. res.status = StatusCode::OK_200;
  4460. } else if (status == "403") {
  4461. res.status = StatusCode::Forbidden_403;
  4462. }
  4463. res.set_content_provider(
  4464. data->size(), "text/plain",
  4465. [data](size_t offset, size_t length, DataSink &sink) {
  4466. size_t DATA_CHUNK_SIZE = 4;
  4467. const auto &d = *data;
  4468. auto out_len =
  4469. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4470. auto ret =
  4471. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4472. EXPECT_TRUE(ret);
  4473. return true;
  4474. },
  4475. [data, &req](bool success) {
  4476. EXPECT_EQ(success, !req.has_param("error"));
  4477. delete data;
  4478. });
  4479. })
  4480. .Get("/streamed-cancel",
  4481. [&](const Request & /*req*/, Response &res) {
  4482. res.set_content_provider(
  4483. size_t(-1), "text/plain",
  4484. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4485. sink.os << "data_chunk";
  4486. return true;
  4487. });
  4488. })
  4489. .Get("/regex-with-delimiter",
  4490. [&](const Request &req, Response & /*res*/) {
  4491. ASSERT_TRUE(req.has_param("key"));
  4492. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4493. })
  4494. .Get("/with-range",
  4495. [&](const Request & /*req*/, Response &res) {
  4496. res.set_content("abcdefg", "text/plain");
  4497. })
  4498. .Get("/test-start-time",
  4499. [&](const Request &req, Response & /*res*/) {
  4500. EXPECT_NE(req.start_time_,
  4501. std::chrono::steady_clock::time_point::min());
  4502. })
  4503. .Get("/with-range-customized-response",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. res.status = StatusCode::BadRequest_400;
  4506. res.set_content(JSON_DATA, "application/json");
  4507. })
  4508. .Post("/chunked",
  4509. [&](const Request &req, Response & /*res*/) {
  4510. EXPECT_EQ(req.body, "dechunked post body");
  4511. })
  4512. .Post("/large-chunked",
  4513. [&](const Request &req, Response & /*res*/) {
  4514. std::string expected(6 * 30 * 1024u, 'a');
  4515. EXPECT_EQ(req.body, expected);
  4516. })
  4517. .Post("/multipart",
  4518. [&](const Request &req, Response & /*res*/) {
  4519. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4520. req.form.get_field_count("text2") +
  4521. req.form.get_field_count("file3") +
  4522. req.form.get_field_count("file4"));
  4523. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4524. req.form.get_file_count("file2"));
  4525. ASSERT_TRUE(!req.form.has_file("???"));
  4526. ASSERT_TRUE(!req.form.has_field("???"));
  4527. ASSERT_TRUE(req.body.empty());
  4528. {
  4529. const auto &text = req.form.get_field("text1");
  4530. EXPECT_EQ("text default", text);
  4531. }
  4532. {
  4533. const auto &text = req.form.get_field("text2");
  4534. EXPECT_EQ("aωb", text);
  4535. }
  4536. {
  4537. const auto &file = req.form.get_file("file1");
  4538. EXPECT_EQ("hello.txt", file.filename);
  4539. EXPECT_EQ("text/plain", file.content_type);
  4540. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4541. }
  4542. {
  4543. const auto &file = req.form.get_file("file2");
  4544. EXPECT_EQ("world.json", file.filename);
  4545. EXPECT_EQ("application/json", file.content_type);
  4546. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4547. }
  4548. {
  4549. const auto &text = req.form.get_field("file3");
  4550. EXPECT_EQ(0u, text.size());
  4551. }
  4552. {
  4553. const auto &text = req.form.get_field("file4");
  4554. EXPECT_EQ(0u, text.size());
  4555. }
  4556. })
  4557. .Post("/multipart/multi_file_values",
  4558. [&](const Request &req, Response & /*res*/) {
  4559. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4560. req.form.get_field_count("multi_text1"));
  4561. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4562. ASSERT_TRUE(!req.form.has_file("???"));
  4563. ASSERT_TRUE(!req.form.has_field("???"));
  4564. ASSERT_TRUE(req.body.empty());
  4565. {
  4566. const auto &text = req.form.get_field("text");
  4567. EXPECT_EQ("default text", text);
  4568. }
  4569. {
  4570. const auto &text1_values = req.form.get_fields("multi_text1");
  4571. EXPECT_EQ(2u, text1_values.size());
  4572. EXPECT_EQ("aaaaa", text1_values[0]);
  4573. EXPECT_EQ("bbbbb", text1_values[1]);
  4574. }
  4575. {
  4576. const auto &file1_values = req.form.get_files("multi_file1");
  4577. EXPECT_EQ(2u, file1_values.size());
  4578. auto file1 = file1_values[0];
  4579. EXPECT_EQ(file1.filename, "hello.txt");
  4580. EXPECT_EQ(file1.content_type, "text/plain");
  4581. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4582. auto file2 = file1_values[1];
  4583. EXPECT_EQ(file2.filename, "world.json");
  4584. EXPECT_EQ(file2.content_type, "application/json");
  4585. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4586. }
  4587. })
  4588. .Post("/empty",
  4589. [&](const Request &req, Response &res) {
  4590. EXPECT_EQ(req.body, "");
  4591. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4592. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4593. res.set_content("empty", "text/plain");
  4594. })
  4595. .Post("/empty-no-content-type",
  4596. [&](const Request &req, Response &res) {
  4597. EXPECT_EQ(req.body, "");
  4598. EXPECT_FALSE(req.has_header("Content-Type"));
  4599. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4600. res.set_content("empty-no-content-type", "text/plain");
  4601. })
  4602. .Post("/path-only",
  4603. [&](const Request &req, Response &res) {
  4604. EXPECT_EQ(req.body, "");
  4605. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4606. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4607. res.set_content("path-only", "text/plain");
  4608. })
  4609. .Post("/path-headers-only",
  4610. [&](const Request &req, Response &res) {
  4611. EXPECT_EQ(req.body, "");
  4612. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4613. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4614. EXPECT_EQ("world", req.get_header_value("hello"));
  4615. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4616. res.set_content("path-headers-only", "text/plain");
  4617. })
  4618. .Post("/post-large",
  4619. [&](const Request &req, Response &res) {
  4620. EXPECT_EQ(req.body, LARGE_DATA);
  4621. res.set_content(req.body, "text/plain");
  4622. })
  4623. .Post("/post-loopback",
  4624. [&](const Request &, Response &res,
  4625. ContentReader const &content_reader) {
  4626. std::string body;
  4627. content_reader([&](const char *data, size_t data_length) {
  4628. body.append(data, data_length);
  4629. return true;
  4630. });
  4631. res.set_content(body, "text/plain");
  4632. })
  4633. .Put("/put-loopback",
  4634. [&](const Request &, Response &res,
  4635. ContentReader const &content_reader) {
  4636. std::string body;
  4637. content_reader([&](const char *data, size_t data_length) {
  4638. body.append(data, data_length);
  4639. return true;
  4640. });
  4641. res.set_content(body, "text/plain");
  4642. })
  4643. .Patch("/patch-loopback",
  4644. [&](const Request &, Response &res,
  4645. ContentReader const &content_reader) {
  4646. std::string body;
  4647. content_reader([&](const char *data, size_t data_length) {
  4648. body.append(data, data_length);
  4649. return true;
  4650. });
  4651. res.set_content(body, "text/plain");
  4652. })
  4653. .Put("/empty-no-content-type",
  4654. [&](const Request &req, Response &res) {
  4655. EXPECT_EQ(req.body, "");
  4656. EXPECT_FALSE(req.has_header("Content-Type"));
  4657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4658. res.set_content("empty-no-content-type", "text/plain");
  4659. })
  4660. .Put("/put",
  4661. [&](const Request &req, Response &res) {
  4662. EXPECT_EQ(req.body, "PUT");
  4663. res.set_content(req.body, "text/plain");
  4664. })
  4665. .Put("/put-large",
  4666. [&](const Request &req, Response &res) {
  4667. EXPECT_EQ(req.body, LARGE_DATA);
  4668. res.set_content(req.body, "text/plain");
  4669. })
  4670. .Patch("/patch",
  4671. [&](const Request &req, Response &res) {
  4672. EXPECT_EQ(req.body, "PATCH");
  4673. res.set_content(req.body, "text/plain");
  4674. })
  4675. .Delete("/delete",
  4676. [&](const Request & /*req*/, Response &res) {
  4677. res.set_content("DELETE", "text/plain");
  4678. })
  4679. .Delete("/delete-body",
  4680. [&](const Request &req, Response &res) {
  4681. EXPECT_EQ(req.body, "content");
  4682. res.set_content(req.body, "text/plain");
  4683. })
  4684. .Options(R"(\*)",
  4685. [&](const Request & /*req*/, Response &res) {
  4686. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4687. })
  4688. .CustomRoute("PROPFIND", "/dav/:id",
  4689. [&](const Request &req, Response &res) {
  4690. res.set_header("x-body-size",
  4691. std::to_string(req.body.size()));
  4692. res.set_header("x-matched-route", req.matched_route);
  4693. res.set_header("x-dav-id", req.path_params.at("id"));
  4694. res.status = StatusCode::MultiStatus_207;
  4695. res.set_content(req.body, "application/xml");
  4696. })
  4697. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4698. [&](const Request &req, Response &res) {
  4699. res.set_header("x-dav-match", req.matches[1]);
  4700. res.status = StatusCode::MultiStatus_207;
  4701. })
  4702. .CustomRoute("MKCOL", "/dav-mkcol",
  4703. [&](const Request &req, Response &res) {
  4704. EXPECT_TRUE(req.body.empty());
  4705. res.status = StatusCode::Created_201;
  4706. })
  4707. .CustomRoute(
  4708. "REPORT", "/dav-report",
  4709. [&](const Request & /*req*/, Response &res,
  4710. const ContentReader &content_reader) {
  4711. std::string body;
  4712. content_reader([&](const char *data, size_t data_length) {
  4713. body.append(data, data_length);
  4714. return true;
  4715. });
  4716. res.set_header("x-body-size", std::to_string(body.size()));
  4717. res.status = StatusCode::MultiStatus_207;
  4718. res.set_content(body, "application/xml");
  4719. })
  4720. .Get("/request-target",
  4721. [&](const Request &req, Response & /*res*/) {
  4722. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4723. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4724. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4725. })
  4726. .Get("/long-query-value",
  4727. [&](const Request &req, Response & /*res*/) {
  4728. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4729. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4730. })
  4731. .Get("/too-long-query-value",
  4732. [&](const Request &req, Response & /*res*/) {
  4733. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4734. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4735. })
  4736. .Get("/array-param",
  4737. [&](const Request &req, Response & /*res*/) {
  4738. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4739. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4740. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4741. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4742. })
  4743. .Get("/array-param-values",
  4744. [&](const Request &req, Response & /*res*/) {
  4745. auto values = req.get_param_values("array");
  4746. EXPECT_EQ(3u, values.size());
  4747. EXPECT_EQ("value1", values[0]);
  4748. EXPECT_EQ("value2", values[1]);
  4749. EXPECT_EQ("value3", values[2]);
  4750. auto empty = req.get_param_values("nonexistent");
  4751. EXPECT_TRUE(empty.empty());
  4752. })
  4753. .Post("/validate-no-multiple-headers",
  4754. [&](const Request &req, Response & /*res*/) {
  4755. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4756. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4757. })
  4758. .Post("/content_receiver",
  4759. [&](const Request &req, Response &res,
  4760. const ContentReader &content_reader) {
  4761. if (req.is_multipart_form_data()) {
  4762. std::vector<FormData> items;
  4763. content_reader(
  4764. [&](const FormData &file) {
  4765. items.push_back(file);
  4766. return true;
  4767. },
  4768. [&](const char *data, size_t data_length) {
  4769. items.back().content.append(data, data_length);
  4770. return true;
  4771. });
  4772. EXPECT_EQ(5u, items.size());
  4773. {
  4774. const auto &file = get_file_value(items, "text1");
  4775. EXPECT_TRUE(file.filename.empty());
  4776. EXPECT_EQ("text default", file.content);
  4777. }
  4778. {
  4779. const auto &file = get_file_value(items, "text2");
  4780. EXPECT_TRUE(file.filename.empty());
  4781. EXPECT_EQ("aωb", file.content);
  4782. }
  4783. {
  4784. const auto &file = get_file_value(items, "file1");
  4785. EXPECT_EQ("hello.txt", file.filename);
  4786. EXPECT_EQ("text/plain", file.content_type);
  4787. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4788. }
  4789. {
  4790. const auto &file = get_file_value(items, "file2");
  4791. EXPECT_EQ("world.json", file.filename);
  4792. EXPECT_EQ("application/json", file.content_type);
  4793. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4794. }
  4795. {
  4796. const auto &file = get_file_value(items, "file3");
  4797. EXPECT_TRUE(file.filename.empty());
  4798. EXPECT_EQ("application/octet-stream", file.content_type);
  4799. EXPECT_EQ(0u, file.content.size());
  4800. }
  4801. } else {
  4802. std::string body;
  4803. content_reader([&](const char *data, size_t data_length) {
  4804. EXPECT_EQ(7U, data_length);
  4805. body.append(data, data_length);
  4806. return true;
  4807. });
  4808. EXPECT_EQ(body, "content");
  4809. res.set_content(body, "text/plain");
  4810. }
  4811. })
  4812. .Put("/content_receiver",
  4813. [&](const Request & /*req*/, Response &res,
  4814. const ContentReader &content_reader) {
  4815. std::string body;
  4816. content_reader([&](const char *data, size_t data_length) {
  4817. body.append(data, data_length);
  4818. return true;
  4819. });
  4820. EXPECT_EQ(body, "content");
  4821. res.set_content(body, "text/plain");
  4822. })
  4823. .Patch("/content_receiver",
  4824. [&](const Request & /*req*/, Response &res,
  4825. const ContentReader &content_reader) {
  4826. std::string body;
  4827. content_reader([&](const char *data, size_t 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. .Post("/query-string-and-body",
  4835. [&](const Request &req, Response & /*res*/) {
  4836. ASSERT_TRUE(req.has_param("key"));
  4837. EXPECT_EQ(req.get_param_value("key"), "value");
  4838. EXPECT_EQ(req.body, "content");
  4839. })
  4840. .Get("/last-request",
  4841. [&](const Request &req, Response & /*res*/) {
  4842. EXPECT_EQ("close", req.get_header_value("Connection"));
  4843. })
  4844. .Get(R"(/redirect/(\d+))",
  4845. [&](const Request &req, Response &res) {
  4846. auto num = std::stoi(req.matches[1]) + 1;
  4847. std::string url = "/redirect/" + std::to_string(num);
  4848. res.set_redirect(url);
  4849. })
  4850. .Post("/binary",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(4U, req.body.size());
  4853. EXPECT_EQ("application/octet-stream",
  4854. req.get_header_value("Content-Type"));
  4855. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4856. res.set_content(req.body, "application/octet-stream");
  4857. })
  4858. .Put("/binary",
  4859. [&](const Request &req, Response &res) {
  4860. EXPECT_EQ(4U, req.body.size());
  4861. EXPECT_EQ("application/octet-stream",
  4862. req.get_header_value("Content-Type"));
  4863. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4864. res.set_content(req.body, "application/octet-stream");
  4865. })
  4866. .Patch("/binary",
  4867. [&](const Request &req, Response &res) {
  4868. EXPECT_EQ(4U, req.body.size());
  4869. EXPECT_EQ("application/octet-stream",
  4870. req.get_header_value("Content-Type"));
  4871. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4872. res.set_content(req.body, "application/octet-stream");
  4873. })
  4874. .Delete("/binary",
  4875. [&](const Request &req, Response &res) {
  4876. EXPECT_EQ(4U, req.body.size());
  4877. EXPECT_EQ("application/octet-stream",
  4878. req.get_header_value("Content-Type"));
  4879. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4880. res.set_content(req.body, "application/octet-stream");
  4881. })
  4882. .Get("/issue1772",
  4883. [&](const Request & /*req*/, Response &res) {
  4884. res.status = 401;
  4885. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4886. })
  4887. .Delete("/issue609",
  4888. [](const httplib::Request &, httplib::Response &res,
  4889. const httplib::ContentReader &) {
  4890. res.set_content("ok", "text/plain");
  4891. })
  4892. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4893. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4894. .Get("/compress",
  4895. [&](const Request & /*req*/, Response &res) {
  4896. res.set_content(
  4897. "12345678901234567890123456789012345678901234567890123456789"
  4898. "01234567890123456789012345678901234567890",
  4899. "text/plain");
  4900. })
  4901. .Get("/compress-with-charset",
  4902. [&](const Request & /*req*/, Response &res) {
  4903. res.set_content(
  4904. "12345678901234567890123456789012345678901234567890123456789"
  4905. "01234567890123456789012345678901234567890",
  4906. "application/json; charset=utf-8");
  4907. })
  4908. .Get("/nocompress",
  4909. [&](const Request & /*req*/, Response &res) {
  4910. res.set_content(
  4911. "12345678901234567890123456789012345678901234567890123456789"
  4912. "01234567890123456789012345678901234567890",
  4913. "application/octet-stream");
  4914. })
  4915. .Post("/compress-multipart",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. EXPECT_EQ(2u, req.form.fields.size());
  4918. ASSERT_TRUE(!req.form.has_field("???"));
  4919. {
  4920. const auto &text = req.form.get_field("key1");
  4921. EXPECT_EQ("test", text);
  4922. }
  4923. {
  4924. const auto &text = req.form.get_field("key2");
  4925. EXPECT_EQ("--abcdefg123", text);
  4926. }
  4927. })
  4928. #endif
  4929. ;
  4930. persons_["john"] = "programmer";
  4931. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4932. svr_.wait_until_ready();
  4933. }
  4934. virtual void TearDown() {
  4935. svr_.stop();
  4936. if (!request_threads_.empty()) {
  4937. std::this_thread::sleep_for(std::chrono::seconds(1));
  4938. for (auto &t : request_threads_) {
  4939. t.join();
  4940. }
  4941. }
  4942. t_.join();
  4943. }
  4944. map<string, string> persons_;
  4945. #ifdef CPPHTTPLIB_SSL_ENABLED
  4946. SSLClient cli_;
  4947. SSLServer svr_;
  4948. #else
  4949. Client cli_;
  4950. Server svr_;
  4951. #endif
  4952. thread t_;
  4953. std::vector<thread> request_threads_;
  4954. };
  4955. TEST_F(ServerTest, GetMethod200) {
  4956. auto res = cli_.Get("/hi");
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ("HTTP/1.1", res->version);
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. EXPECT_EQ("OK", res->reason);
  4961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4962. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4963. EXPECT_EQ("Hello World!", res->body);
  4964. }
  4965. TEST_F(ServerTest, GetEmptyFile) {
  4966. auto res = cli_.Get("/empty_file");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4970. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4971. EXPECT_EQ("", res->body);
  4972. }
  4973. TEST_F(ServerTest, GetFileContent) {
  4974. auto res = cli_.Get("/file_content");
  4975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4978. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4979. EXPECT_EQ("test.html", res->body);
  4980. }
  4981. TEST_F(ServerTest, GetFileContentWithRange) {
  4982. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4985. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4986. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4987. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4988. EXPECT_EQ("est", res->body);
  4989. }
  4990. TEST_F(ServerTest, GetFileContentWithContentType) {
  4991. auto res = cli_.Get("/file_content_with_content_type");
  4992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4995. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4996. EXPECT_EQ("file\n", res->body);
  4997. }
  4998. TEST_F(ServerTest, GetInvalidFileContent) {
  4999. auto res = cli_.Get("/invalid_file_content");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5002. }
  5003. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5004. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ("HTTP/1.1", res->version);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5009. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5010. EXPECT_EQ("Hello World!", res->body);
  5011. }
  5012. TEST_F(ServerTest, GetMethod302) {
  5013. auto res = cli_.Get("/");
  5014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5015. EXPECT_EQ(StatusCode::Found_302, res->status);
  5016. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5017. }
  5018. TEST_F(ServerTest, GetMethod302Redirect) {
  5019. cli_.set_follow_location(true);
  5020. auto res = cli_.Get("/");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("Hello World!", res->body);
  5024. EXPECT_EQ("/hi", res->location);
  5025. }
  5026. TEST_F(ServerTest, GetMethod404) {
  5027. auto res = cli_.Get("/invalid");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5030. }
  5031. TEST_F(ServerTest, HeadMethod200) {
  5032. auto res = cli_.Head("/hi");
  5033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_TRUE(res->body.empty());
  5037. }
  5038. TEST_F(ServerTest, HeadMethod200Static) {
  5039. auto res = cli_.Head("/mount/dir/index.html");
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5043. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5044. EXPECT_TRUE(res->body.empty());
  5045. }
  5046. TEST_F(ServerTest, HeadMethod404) {
  5047. auto res = cli_.Head("/invalid");
  5048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5049. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5050. EXPECT_TRUE(res->body.empty());
  5051. }
  5052. TEST_F(ServerTest, GetMethodPersonJohn) {
  5053. auto res = cli_.Get("/person/john");
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5057. EXPECT_EQ("programmer", res->body);
  5058. }
  5059. TEST_F(ServerTest, PostMethod1) {
  5060. auto res = cli_.Get("/person/john1");
  5061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5062. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5063. res = cli_.Post("/person", "name=john1&note=coder",
  5064. "application/x-www-form-urlencoded");
  5065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5066. ASSERT_EQ(StatusCode::OK_200, res->status);
  5067. res = cli_.Get("/person/john1");
  5068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5069. ASSERT_EQ(StatusCode::OK_200, res->status);
  5070. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5071. ASSERT_EQ("coder", res->body);
  5072. }
  5073. TEST_F(ServerTest, PostMethod2) {
  5074. auto res = cli_.Get("/person/john2");
  5075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5076. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5077. Params params;
  5078. params.emplace("name", "john2");
  5079. params.emplace("note", "coder");
  5080. res = cli_.Post("/person", params);
  5081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5082. ASSERT_EQ(StatusCode::OK_200, res->status);
  5083. res = cli_.Get("/person/john2");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5087. ASSERT_EQ("coder", res->body);
  5088. }
  5089. TEST_F(ServerTest, PutMethod3) {
  5090. auto res = cli_.Get("/person/john3");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5093. Params params;
  5094. params.emplace("name", "john3");
  5095. params.emplace("note", "coder");
  5096. res = cli_.Put("/person", params);
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. ASSERT_EQ(StatusCode::OK_200, res->status);
  5099. res = cli_.Get("/person/john3");
  5100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5101. ASSERT_EQ(StatusCode::OK_200, res->status);
  5102. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5103. ASSERT_EQ("coder", res->body);
  5104. }
  5105. TEST_F(ServerTest, DeleteMethod1) {
  5106. auto res = cli_.Get("/person/john4");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5109. Params params;
  5110. params.emplace("name", "john4");
  5111. params.emplace("note", "coder");
  5112. res = cli_.Post("/person", params);
  5113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5114. ASSERT_EQ(StatusCode::OK_200, res->status);
  5115. res = cli_.Get("/person/john4");
  5116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5117. ASSERT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5119. ASSERT_EQ("coder", res->body);
  5120. Params delete_params;
  5121. delete_params.emplace("name", "john4");
  5122. res = cli_.Delete("/person", delete_params);
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("DELETED", res->body);
  5126. res = cli_.Get("/person/john4");
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5129. }
  5130. TEST_F(ServerTest, DeleteMethod2) {
  5131. auto res = cli_.Get("/person/john5");
  5132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5133. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5134. Params params;
  5135. params.emplace("name", "john5");
  5136. params.emplace("note", "developer");
  5137. res = cli_.Post("/person", params);
  5138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5139. ASSERT_EQ(StatusCode::OK_200, res->status);
  5140. res = cli_.Get("/person/john5");
  5141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5142. ASSERT_EQ(StatusCode::OK_200, res->status);
  5143. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5144. ASSERT_EQ("developer", res->body);
  5145. Params delete_params;
  5146. delete_params.emplace("name", "john5");
  5147. Headers headers;
  5148. headers.emplace("Custom-Header", "test-value");
  5149. res = cli_.Delete("/person", headers, delete_params);
  5150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5151. ASSERT_EQ(StatusCode::OK_200, res->status);
  5152. ASSERT_EQ("DELETED", res->body);
  5153. res = cli_.Get("/person/john5");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5156. }
  5157. TEST_F(ServerTest, DeleteMethod3) {
  5158. auto res = cli_.Get("/person/john6");
  5159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5160. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5161. Params params;
  5162. params.emplace("name", "john6");
  5163. params.emplace("note", "tester");
  5164. res = cli_.Post("/person", params);
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. ASSERT_EQ(StatusCode::OK_200, res->status);
  5167. res = cli_.Get("/person/john6");
  5168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5169. ASSERT_EQ(StatusCode::OK_200, res->status);
  5170. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5171. ASSERT_EQ("tester", res->body);
  5172. Params delete_params;
  5173. delete_params.emplace("name", "john6");
  5174. Headers headers;
  5175. headers.emplace("Custom-Header", "test-value");
  5176. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. ASSERT_EQ(StatusCode::OK_200, res->status);
  5179. ASSERT_EQ("DELETED", res->body);
  5180. res = cli_.Get("/person/john6");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5183. }
  5184. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5185. Params params;
  5186. params.emplace("json", JSON_DATA);
  5187. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. ASSERT_EQ(StatusCode::OK_200, res->status);
  5190. ASSERT_EQ(JSON_DATA, res->body);
  5191. }
  5192. TEST_F(ServerTest, PostEmptyContent) {
  5193. auto res = cli_.Post("/empty", "", "text/plain");
  5194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5195. ASSERT_EQ(StatusCode::OK_200, res->status);
  5196. ASSERT_EQ("empty", res->body);
  5197. }
  5198. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5199. auto res = cli_.Post("/empty-no-content-type");
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. ASSERT_EQ(StatusCode::OK_200, res->status);
  5202. ASSERT_EQ("empty-no-content-type", res->body);
  5203. }
  5204. TEST_F(ServerTest, PostPathOnly) {
  5205. auto res = cli_.Post("/path-only");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. ASSERT_EQ(StatusCode::OK_200, res->status);
  5208. ASSERT_EQ("path-only", res->body);
  5209. }
  5210. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5211. auto res = cli_.Post("/path-headers-only",
  5212. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. ASSERT_EQ(StatusCode::OK_200, res->status);
  5215. ASSERT_EQ("path-headers-only", res->body);
  5216. }
  5217. TEST_F(ServerTest, PostLarge) {
  5218. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. ASSERT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ(LARGE_DATA, res->body);
  5222. }
  5223. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5224. auto res = cli_.Put("/empty-no-content-type");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. ASSERT_EQ(StatusCode::OK_200, res->status);
  5227. ASSERT_EQ("empty-no-content-type", res->body);
  5228. }
  5229. TEST_F(ServerTest, GetMethodDir) {
  5230. auto res = cli_.Get("/dir/");
  5231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5232. EXPECT_EQ(StatusCode::OK_200, res->status);
  5233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5234. auto body = R"(<html>
  5235. <head>
  5236. </head>
  5237. <body>
  5238. <a href="/dir/test.html">Test</a>
  5239. <a href="/hi">hi</a>
  5240. </body>
  5241. </html>
  5242. )";
  5243. EXPECT_EQ(body, res->body);
  5244. }
  5245. TEST_F(ServerTest, GetMethodDirTest) {
  5246. auto res = cli_.Get("/dir/test.html");
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. EXPECT_EQ(StatusCode::OK_200, res->status);
  5249. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5250. EXPECT_EQ("test.html", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5253. auto res = cli_.Get("/dir/../dir/test.html");
  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. EXPECT_EQ("test.html", res->body);
  5258. }
  5259. TEST_F(ServerTest, GetMethodInvalidPath) {
  5260. auto res = cli_.Get("/dir/../test.html");
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5263. }
  5264. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5265. auto res = cli_.Get("/../www/dir/test.html");
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5268. }
  5269. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5270. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5273. }
  5274. TEST_F(ServerTest, GetMethodDirMountTest) {
  5275. auto res = cli_.Get("/mount/dir/test.html");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5279. EXPECT_EQ("test.html", res->body);
  5280. }
  5281. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5282. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5286. EXPECT_EQ("test.html", res->body);
  5287. }
  5288. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5289. auto res = cli_.Get("/mount/dir/../test.html");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5292. }
  5293. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5294. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5297. }
  5298. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5299. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5301. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5302. }
  5303. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5304. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5307. }
  5308. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5309. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5312. }
  5313. TEST_F(ServerTest, PostMethod303) {
  5314. auto res = cli_.Post("/1", "body", "text/plain");
  5315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5316. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5317. EXPECT_EQ("/2", res->get_header_value("Location"));
  5318. }
  5319. TEST_F(ServerTest, PostMethod303Redirect) {
  5320. cli_.set_follow_location(true);
  5321. auto res = cli_.Post("/1", "body", "text/plain");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("redirected.", res->body);
  5325. EXPECT_EQ("/2", res->location);
  5326. }
  5327. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5328. auto res = cli_.Get("/dir/test.abcde");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5332. EXPECT_EQ("abcde", res->body);
  5333. }
  5334. TEST_F(ServerTest, StaticFileRange) {
  5335. auto res =
  5336. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5339. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5340. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5341. EXPECT_EQ(true, res->has_header("Content-Range"));
  5342. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5343. EXPECT_EQ(std::string("cd"), res->body);
  5344. }
  5345. TEST_F(ServerTest, StaticFileRanges) {
  5346. auto res = cli_.Get("/dir/test.abcde",
  5347. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5350. EXPECT_TRUE(
  5351. res->get_header_value("Content-Type")
  5352. .find(
  5353. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5354. 0);
  5355. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5356. }
  5357. TEST_F(ServerTest, StaticFileRangeHead) {
  5358. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5361. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5362. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5363. EXPECT_EQ(true, res->has_header("Content-Range"));
  5364. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5365. }
  5366. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5367. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5372. EXPECT_EQ(true, res->has_header("Content-Range"));
  5373. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5374. res->get_header_value("Content-Range"));
  5375. EXPECT_EQ("LAST\n", res->body);
  5376. }
  5377. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5378. auto res =
  5379. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5384. EXPECT_EQ(true, res->has_header("Content-Range"));
  5385. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5386. }
  5387. TEST_F(ServerTest, StaticFileBigFile) {
  5388. auto res = cli_.Get("/dir/1MB.txt");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5392. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5393. }
  5394. TEST_F(ServerTest, InvalidBaseDirMount) {
  5395. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5396. }
  5397. TEST_F(ServerTest, Binary) {
  5398. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5399. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5400. "application/octet-stream");
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. ASSERT_EQ(StatusCode::OK_200, res->status);
  5403. ASSERT_EQ(4U, res->body.size());
  5404. res = cli_.Put("/binary", binary.data(), binary.size(),
  5405. "application/octet-stream");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. ASSERT_EQ(StatusCode::OK_200, res->status);
  5408. ASSERT_EQ(4U, res->body.size());
  5409. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5410. "application/octet-stream");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. ASSERT_EQ(StatusCode::OK_200, res->status);
  5413. ASSERT_EQ(4U, res->body.size());
  5414. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5415. "application/octet-stream");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::OK_200, res->status);
  5418. ASSERT_EQ(4U, res->body.size());
  5419. }
  5420. TEST_F(ServerTest, BinaryString) {
  5421. auto binary = std::string("\x00\x01\x02\x03", 4);
  5422. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. ASSERT_EQ(StatusCode::OK_200, res->status);
  5425. ASSERT_EQ(4U, res->body.size());
  5426. res = cli_.Put("/binary", binary, "application/octet-stream");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. ASSERT_EQ(StatusCode::OK_200, res->status);
  5429. ASSERT_EQ(4U, res->body.size());
  5430. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. ASSERT_EQ(StatusCode::OK_200, res->status);
  5433. ASSERT_EQ(4U, res->body.size());
  5434. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5436. ASSERT_EQ(StatusCode::OK_200, res->status);
  5437. ASSERT_EQ(4U, res->body.size());
  5438. }
  5439. TEST_F(ServerTest, EmptyRequest) {
  5440. auto res = cli_.Get("");
  5441. ASSERT_TRUE(!res);
  5442. EXPECT_EQ(Error::Connection, res.error());
  5443. }
  5444. TEST_F(ServerTest, LongRequest) {
  5445. std::string request;
  5446. for (size_t i = 0; i < 545; i++) {
  5447. request += "/TooLongRequest";
  5448. }
  5449. request += "OK";
  5450. auto res = cli_.Get(request.c_str());
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5453. }
  5454. TEST_F(ServerTest, TooLongRequest) {
  5455. std::string request;
  5456. for (size_t i = 0; i < 546; i++) {
  5457. request += "/TooLongRequest";
  5458. }
  5459. request += "_NG";
  5460. auto start = std::chrono::high_resolution_clock::now();
  5461. cli_.set_keep_alive(true);
  5462. auto res = cli_.Get(request.c_str());
  5463. auto end = std::chrono::high_resolution_clock::now();
  5464. auto elapsed =
  5465. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5466. .count();
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5469. EXPECT_LE(elapsed, 1000);
  5470. EXPECT_EQ("close", res->get_header_value("Connection"));
  5471. EXPECT_FALSE(cli_.is_socket_open());
  5472. }
  5473. TEST_F(ServerTest, AlmostTooLongRequest) {
  5474. // test for #2046 - URI length check shouldn't include other content on req
  5475. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5476. // leading /, space, HTTP/1.1)
  5477. std::string request =
  5478. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5479. auto res = cli_.Get(request.c_str());
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5482. }
  5483. TEST_F(ServerTest, LongHeader) {
  5484. Request req;
  5485. req.method = "GET";
  5486. req.path = "/hi";
  5487. std::string host_and_port;
  5488. host_and_port += HOST;
  5489. host_and_port += ":";
  5490. host_and_port += std::to_string(PORT);
  5491. req.headers.emplace("Host", host_and_port.c_str());
  5492. req.headers.emplace("Accept", "*/*");
  5493. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5494. req.headers.emplace(
  5495. "Header-Name",
  5496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5524. "@@@@@@@@@@@@@@@@");
  5525. auto res = std::make_shared<Response>();
  5526. auto error = Error::Success;
  5527. auto ret = cli_.send(req, *res, error);
  5528. ASSERT_TRUE(ret);
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. }
  5531. TEST_F(ServerTest, LongQueryValue) {
  5532. auto start = std::chrono::high_resolution_clock::now();
  5533. cli_.set_keep_alive(true);
  5534. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5535. auto end = std::chrono::high_resolution_clock::now();
  5536. auto elapsed =
  5537. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5538. .count();
  5539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5540. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5541. EXPECT_LE(elapsed, 1000);
  5542. EXPECT_EQ("close", res->get_header_value("Connection"));
  5543. EXPECT_FALSE(cli_.is_socket_open());
  5544. }
  5545. TEST_F(ServerTest, TooLongQueryValue) {
  5546. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5547. ASSERT_FALSE(res);
  5548. EXPECT_EQ(Error::Read, res.error());
  5549. }
  5550. TEST_F(ServerTest, TooLongHeader) {
  5551. Request req;
  5552. req.method = "GET";
  5553. req.path = "/hi";
  5554. std::string host_and_port;
  5555. host_and_port += HOST;
  5556. host_and_port += ":";
  5557. host_and_port += std::to_string(PORT);
  5558. req.headers.emplace("Host", host_and_port.c_str());
  5559. req.headers.emplace("Accept", "*/*");
  5560. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5561. req.headers.emplace(
  5562. "Header-Name",
  5563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5591. "@@@@@@@@@@@@@@@@@");
  5592. auto res = std::make_shared<Response>();
  5593. auto error = Error::Success;
  5594. auto ret = cli_.send(req, *res, error);
  5595. ASSERT_TRUE(ret);
  5596. EXPECT_EQ(StatusCode::OK_200, res->status);
  5597. }
  5598. TEST_F(ServerTest, HeaderCountAtLimit) {
  5599. // Test with headers just under the 100 limit
  5600. httplib::Headers headers;
  5601. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5602. // This should keep us just under the 100 header limit
  5603. for (int i = 0; i < 95; i++) {
  5604. std::string name = "X-Test-Header-" + std::to_string(i);
  5605. std::string value = "value" + std::to_string(i);
  5606. headers.emplace(name, value);
  5607. }
  5608. // This should work fine as we're under the limit
  5609. auto res = cli_.Get("/hi", headers);
  5610. EXPECT_TRUE(res);
  5611. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5612. }
  5613. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5614. // Test with many headers to exceed the 100 limit
  5615. httplib::Headers headers;
  5616. // Add 150 headers to definitely exceed the 100 limit
  5617. for (int i = 0; i < 150; i++) {
  5618. std::string name = "X-Test-Header-" + std::to_string(i);
  5619. std::string value = "value" + std::to_string(i);
  5620. headers.emplace(name, value);
  5621. }
  5622. // This should fail due to exceeding header count limit
  5623. cli_.set_keep_alive(true);
  5624. auto res = cli_.Get("/hi", headers);
  5625. // The server should respond with 400 Bad Request
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5628. EXPECT_EQ("close", res->get_header_value("Connection"));
  5629. EXPECT_FALSE(cli_.is_socket_open());
  5630. }
  5631. TEST_F(ServerTest, PercentEncoding) {
  5632. auto res = cli_.Get("/e%6edwith%");
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. }
  5636. TEST_F(ServerTest, PercentEncodingUnicode) {
  5637. auto res = cli_.Get("/e%u006edwith%");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. EXPECT_EQ(StatusCode::OK_200, res->status);
  5640. }
  5641. TEST_F(ServerTest, InvalidPercentEncoding) {
  5642. auto res = cli_.Get("/%endwith%");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5645. }
  5646. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5647. auto res = cli_.Get("/%uendwith%");
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5650. }
  5651. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5652. auto res = cli_.Get("/hello?aaa=bbb%");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5655. }
  5656. TEST_F(ServerTest, PlusSignEncoding) {
  5657. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. EXPECT_EQ("a +b", res->body);
  5661. }
  5662. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5663. // This test simulates a potential DoS attack using many headers
  5664. // to verify our security fix prevents memory exhaustion
  5665. httplib::Headers attack_headers;
  5666. // Attempt to add many headers like an attacker would (200 headers to far
  5667. // exceed limit)
  5668. for (int i = 0; i < 200; i++) {
  5669. std::string name = "X-Attack-Header-" + std::to_string(i);
  5670. std::string value = "attack_payload_" + std::to_string(i);
  5671. attack_headers.emplace(name, value);
  5672. }
  5673. // Try to POST with excessive headers
  5674. cli_.set_keep_alive(true);
  5675. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5676. // Should either fail or return 400 Bad Request due to security limit
  5677. if (res) {
  5678. // If we get a response, it should be 400 Bad Request
  5679. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5680. EXPECT_EQ("close", res->get_header_value("Connection"));
  5681. }
  5682. EXPECT_FALSE(cli_.is_socket_open());
  5683. }
  5684. TEST_F(ServerTest, MultipartFormData) {
  5685. UploadFormDataItems items = {
  5686. {"text1", "text default", "", ""},
  5687. {"text2", "aωb", "", ""},
  5688. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5689. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5690. {"file3", "", "", "application/octet-stream"},
  5691. {"file4", "", "", " application/json tmp-string "}};
  5692. auto res = cli_.Post("/multipart", items);
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::OK_200, res->status);
  5695. }
  5696. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5697. UploadFormDataItems items = {
  5698. {"text", "default text", "", ""},
  5699. {"multi_text1", "aaaaa", "", ""},
  5700. {"multi_text1", "bbbbb", "", ""},
  5701. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5702. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5703. "application/json"},
  5704. };
  5705. auto res = cli_.Post("/multipart/multi_file_values", items);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. EXPECT_EQ(StatusCode::OK_200, res->status);
  5708. }
  5709. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5710. auto res = cli_.Get("/hi");
  5711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5714. EXPECT_EQ("Hello World!", res->body);
  5715. }
  5716. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5717. Request req;
  5718. req.method = "POST";
  5719. req.path = "/chunked";
  5720. std::string host_and_port;
  5721. host_and_port += HOST;
  5722. host_and_port += ":";
  5723. host_and_port += std::to_string(PORT);
  5724. req.headers.emplace("Host", host_and_port.c_str());
  5725. req.headers.emplace("Accept", "*/*");
  5726. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5727. req.headers.emplace("Content-Type", "text/plain");
  5728. req.headers.emplace("Content-Length", "0");
  5729. req.headers.emplace(
  5730. "Transfer-Encoding",
  5731. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5732. // Client does not chunk, so make a chunked body manually.
  5733. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5734. auto res = std::make_shared<Response>();
  5735. auto error = Error::Success;
  5736. auto ret = cli_.send(req, *res, error);
  5737. ASSERT_TRUE(ret);
  5738. EXPECT_EQ(StatusCode::OK_200, res->status);
  5739. }
  5740. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5741. // rather than treat them as valid lengths.
  5742. template <typename ClientT>
  5743. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5744. Request req;
  5745. req.method = "POST";
  5746. req.path = "/chunked";
  5747. std::string host_and_port;
  5748. host_and_port += HOST;
  5749. host_and_port += ":";
  5750. host_and_port += std::to_string(PORT);
  5751. req.headers.emplace("Host", host_and_port.c_str());
  5752. req.headers.emplace("Content-Length", "0");
  5753. req.headers.emplace("Transfer-Encoding", "chunked");
  5754. req.body = body;
  5755. auto res = std::make_shared<Response>();
  5756. auto error = Error::Success;
  5757. ASSERT_TRUE(cli.send(req, *res, error));
  5758. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5759. }
  5760. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5761. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5762. }
  5763. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5764. expect_chunked_body_rejected(
  5765. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5766. }
  5767. TEST_F(ServerTest, GetStreamed2) {
  5768. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5771. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5772. EXPECT_EQ(true, res->has_header("Content-Range"));
  5773. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5774. EXPECT_EQ(std::string("ab"), res->body);
  5775. }
  5776. TEST_F(ServerTest, GetStreamed) {
  5777. auto res = cli_.Get("/streamed");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5781. EXPECT_EQ(std::string("aaabbb"), res->body);
  5782. }
  5783. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5784. auto res = cli_.Get("/streamed-without-length",
  5785. Headers{make_range_header({{0, -1}})});
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. EXPECT_EQ(false, res->has_header("Content-Length"));
  5789. EXPECT_EQ(false, res->has_header("Content-Range"));
  5790. EXPECT_EQ(std::string("abcdefg"), res->body);
  5791. }
  5792. TEST_F(ServerTest, GetStreamedWithRange1) {
  5793. auto res =
  5794. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5797. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5798. EXPECT_EQ(true, res->has_header("Content-Range"));
  5799. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5800. EXPECT_EQ(std::string("def"), res->body);
  5801. }
  5802. TEST_F(ServerTest, GetStreamedWithRange2) {
  5803. auto res =
  5804. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5807. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5808. EXPECT_EQ(true, res->has_header("Content-Range"));
  5809. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5810. EXPECT_EQ(std::string("bcdefg"), res->body);
  5811. }
  5812. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5813. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5816. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5817. EXPECT_EQ(true, res->has_header("Content-Range"));
  5818. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5819. EXPECT_EQ(std::string("efg"), res->body);
  5820. }
  5821. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5822. auto res =
  5823. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5826. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5827. EXPECT_EQ(false, res->has_header("Content-Range"));
  5828. EXPECT_EQ(0U, res->body.size());
  5829. }
  5830. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5831. // Only a 206 is served as a partial representation. Under any other status
  5832. // `apply_ranges()` reported the full content length, so the body must match
  5833. // that header, and the content provider must never be asked for an offset
  5834. // outside the representation.
  5835. auto check = [&](int status, const char *range) {
  5836. auto path =
  5837. std::string("/streamed-with-range?status=") + std::to_string(status);
  5838. auto ctx = path + " Range: " + range;
  5839. auto res = cli_.Get(path, Headers{{"Range", range}});
  5840. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5841. EXPECT_EQ(status, res->status) << ctx;
  5842. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5844. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5845. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5846. };
  5847. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5848. check(403, "bytes=3-5");
  5849. // The offset is far past the representation.
  5850. check(403, "bytes=100000-100200");
  5851. // `first_pos` is still -1 here, and the bounds asserts in
  5852. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5853. check(403, "bytes=-3");
  5854. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5855. // multipart branch would have written one that is empty.
  5856. check(403, "bytes=1-2, 4-5");
  5857. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5858. // covers the whole representation.
  5859. check(200, "bytes=3-5");
  5860. check(200, "bytes=1-2, 4-5");
  5861. }
  5862. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5863. auto res =
  5864. cli_.Get("/streamed-with-range",
  5865. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5866. "92233720368547758079223372036854775807"}});
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5869. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5870. EXPECT_EQ(false, res->has_header("Content-Range"));
  5871. EXPECT_EQ(0U, res->body.size());
  5872. }
  5873. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5874. auto res = cli_.Get(
  5875. "/with-range",
  5876. Headers{{"Range",
  5877. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5878. {"Accept-Encoding", ""}});
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5881. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5882. EXPECT_EQ(true, res->has_header("Content-Range"));
  5883. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5884. EXPECT_EQ(std::string("abcdefg"), res->body);
  5885. }
  5886. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5887. auto res = cli_.Get("/with-range", Headers{
  5888. {"Range", "bytes=0-"},
  5889. {"Accept-Encoding", ""},
  5890. });
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5893. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5894. EXPECT_EQ(true, res->has_header("Content-Range"));
  5895. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5896. EXPECT_EQ(std::string("abcdefg"), res->body);
  5897. }
  5898. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5899. auto res = cli_.Get("/streamed-with-range",
  5900. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5903. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5904. EXPECT_EQ(false, res->has_header("Content-Range"));
  5905. EXPECT_EQ(267U, res->body.size());
  5906. // Check that both range contents are present
  5907. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5908. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5909. // Check that Content-Range headers are present for both ranges
  5910. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5911. std::string::npos);
  5912. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5913. std::string::npos);
  5914. }
  5915. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5916. Ranges ranges;
  5917. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5918. ranges.emplace_back(0, -1);
  5919. }
  5920. auto res = cli_.Get("/streamed-with-range?error",
  5921. Headers{{make_range_header(ranges)}});
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5924. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5925. EXPECT_EQ(false, res->has_header("Content-Range"));
  5926. EXPECT_EQ(0U, res->body.size());
  5927. }
  5928. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5929. auto res = cli_.Get("/streamed-with-range",
  5930. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5933. EXPECT_EQ(5U, res->body.size());
  5934. // Check that overlapping ranges are coalesced into a single range
  5935. EXPECT_EQ("bcdef", res->body);
  5936. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5937. // Should be single range, not multipart
  5938. EXPECT_TRUE(res->has_header("Content-Range"));
  5939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5940. }
  5941. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5942. auto res = cli_.Get("/streamed-with-range",
  5943. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5946. EXPECT_EQ(268U, res->body.size());
  5947. // Check that both range contents are present
  5948. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5949. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5950. // Check that Content-Range headers are present for both ranges
  5951. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5952. std::string::npos);
  5953. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5954. std::string::npos);
  5955. }
  5956. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5957. auto res = cli_.Get("/streamed-with-range",
  5958. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5961. EXPECT_EQ(269U, res->body.size());
  5962. // Check that both duplicate range contents are present
  5963. size_t first_abc = res->body.find("abc\r\n");
  5964. EXPECT_TRUE(first_abc != std::string::npos);
  5965. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5966. EXPECT_TRUE(second_abc != std::string::npos);
  5967. // Check that Content-Range headers are present for both ranges
  5968. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5969. EXPECT_TRUE(first_range != std::string::npos);
  5970. size_t second_range =
  5971. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5972. EXPECT_TRUE(second_range != std::string::npos);
  5973. }
  5974. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5975. auto res =
  5976. cli_.Get("/streamed-with-range?error",
  5977. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5979. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5980. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5981. EXPECT_EQ(false, res->has_header("Content-Range"));
  5982. EXPECT_EQ(0U, res->body.size());
  5983. }
  5984. TEST_F(ServerTest, GetStreamedEndless) {
  5985. uint64_t offset = 0;
  5986. auto res = cli_.Get("/streamed-cancel",
  5987. [&](const char * /*data*/, uint64_t data_length) {
  5988. if (offset < 100) {
  5989. offset += data_length;
  5990. return true;
  5991. }
  5992. return false;
  5993. });
  5994. ASSERT_TRUE(!res);
  5995. EXPECT_EQ(Error::Canceled, res.error());
  5996. }
  5997. TEST_F(ServerTest, ClientStop) {
  5998. std::atomic_size_t count{4};
  5999. std::vector<std::thread> threads;
  6000. for (auto i = count.load(); i != 0; --i) {
  6001. threads.emplace_back([&]() {
  6002. auto res = cli_.Get("/streamed-cancel",
  6003. [&](const char *, uint64_t) { return true; });
  6004. --count;
  6005. ASSERT_TRUE(!res);
  6006. EXPECT_TRUE(res.error() == Error::Canceled ||
  6007. res.error() == Error::Read || res.error() == Error::Write);
  6008. });
  6009. }
  6010. std::this_thread::sleep_for(std::chrono::seconds(2));
  6011. while (count != 0) {
  6012. cli_.stop();
  6013. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6014. }
  6015. for (auto &t : threads) {
  6016. t.join();
  6017. }
  6018. }
  6019. TEST_F(ServerTest, GetWithRange1) {
  6020. auto res = cli_.Get("/with-range", Headers{
  6021. make_range_header({{3, 5}}),
  6022. {"Accept-Encoding", ""},
  6023. });
  6024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6026. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6027. EXPECT_EQ(true, res->has_header("Content-Range"));
  6028. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6029. EXPECT_EQ(std::string("def"), res->body);
  6030. }
  6031. TEST_F(ServerTest, GetWithRange2) {
  6032. auto res = cli_.Get("/with-range", Headers{
  6033. make_range_header({{1, -1}}),
  6034. {"Accept-Encoding", ""},
  6035. });
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6039. EXPECT_EQ(true, res->has_header("Content-Range"));
  6040. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6041. EXPECT_EQ(std::string("bcdefg"), res->body);
  6042. }
  6043. TEST_F(ServerTest, GetWithRange3) {
  6044. auto res = cli_.Get("/with-range", Headers{
  6045. make_range_header({{0, 0}}),
  6046. {"Accept-Encoding", ""},
  6047. });
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6050. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6051. EXPECT_EQ(true, res->has_header("Content-Range"));
  6052. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6053. EXPECT_EQ(std::string("a"), res->body);
  6054. }
  6055. TEST_F(ServerTest, GetWithRange4) {
  6056. auto res = cli_.Get("/with-range", Headers{
  6057. make_range_header({{-1, 2}}),
  6058. {"Accept-Encoding", ""},
  6059. });
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6062. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6063. EXPECT_EQ(true, res->has_header("Content-Range"));
  6064. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6065. EXPECT_EQ(std::string("fg"), res->body);
  6066. }
  6067. TEST_F(ServerTest, GetWithRange5) {
  6068. auto res = cli_.Get("/with-range", Headers{
  6069. make_range_header({{0, 5}}),
  6070. {"Accept-Encoding", ""},
  6071. });
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6074. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6075. EXPECT_EQ(true, res->has_header("Content-Range"));
  6076. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6077. EXPECT_EQ(std::string("abcdef"), res->body);
  6078. }
  6079. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6080. auto res =
  6081. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6084. }
  6085. TEST_F(ServerTest, GetWithRangeMultipart) {
  6086. auto res =
  6087. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6090. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6091. EXPECT_EQ(false, res->has_header("Content-Range"));
  6092. EXPECT_EQ(267U, res->body.size());
  6093. }
  6094. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6095. auto res = cli_.Get("/with-range",
  6096. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6099. }
  6100. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6101. auto res = cli_.Get("/with-range-customized-response",
  6102. Headers{{make_range_header({{1, 2}})}});
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6105. EXPECT_EQ(true, res->has_header("Content-Length"));
  6106. EXPECT_EQ(false, res->has_header("Content-Range"));
  6107. EXPECT_EQ(JSON_DATA, res->body);
  6108. }
  6109. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6110. auto res = cli_.Get("/with-range-customized-response",
  6111. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6114. EXPECT_EQ(true, res->has_header("Content-Length"));
  6115. EXPECT_EQ(false, res->has_header("Content-Range"));
  6116. EXPECT_EQ(JSON_DATA, res->body);
  6117. }
  6118. TEST_F(ServerTest, Issue1772) {
  6119. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6122. }
  6123. TEST_F(ServerTest, Issue609) {
  6124. auto res = cli_.Delete("/issue609");
  6125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ(std::string("ok"), res->body);
  6128. }
  6129. TEST_F(ServerTest, GetStreamedChunked) {
  6130. auto res = cli_.Get("/streamed-chunked");
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. EXPECT_EQ(std::string("123456789"), res->body);
  6134. }
  6135. TEST_F(ServerTest, GetStreamedChunked2) {
  6136. auto res = cli_.Get("/streamed-chunked2");
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::OK_200, res->status);
  6139. EXPECT_EQ(std::string("123456789"), res->body);
  6140. }
  6141. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6142. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::OK_200, res->status);
  6145. EXPECT_EQ(std::string("123456789"), res->body);
  6146. EXPECT_TRUE(res->has_header("Trailer"));
  6147. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6148. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6149. // Trailers are now stored separately from headers (security fix)
  6150. EXPECT_EQ(2U, res->trailers.size());
  6151. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6152. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6153. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6154. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6155. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6156. // Verify trailers are NOT in headers (security verification)
  6157. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6158. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6159. }
  6160. TEST_F(ServerTest, LargeChunkedPost) {
  6161. Request req;
  6162. req.method = "POST";
  6163. req.path = "/large-chunked";
  6164. std::string host_and_port;
  6165. host_and_port += HOST;
  6166. host_and_port += ":";
  6167. host_and_port += std::to_string(PORT);
  6168. req.headers.emplace("Host", host_and_port.c_str());
  6169. req.headers.emplace("Accept", "*/*");
  6170. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6171. req.headers.emplace("Content-Type", "text/plain");
  6172. req.headers.emplace("Content-Length", "0");
  6173. req.headers.emplace("Transfer-Encoding", "chunked");
  6174. std::string long_string(30 * 1024u, 'a');
  6175. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6176. // Attempt to make a large enough post to exceed OS buffers, to test that
  6177. // the server handles short reads if the full chunk data isn't available.
  6178. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6179. auto res = std::make_shared<Response>();
  6180. auto error = Error::Success;
  6181. auto ret = cli_.send(req, *res, error);
  6182. ASSERT_TRUE(ret);
  6183. EXPECT_EQ(StatusCode::OK_200, res->status);
  6184. }
  6185. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6186. auto res = cli_.Get("/remote_addr");
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::OK_200, res->status);
  6189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6190. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6191. }
  6192. TEST_F(ServerTest, GetMethodLocalAddr) {
  6193. auto res = cli_.Get("/local_addr");
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. EXPECT_EQ(StatusCode::OK_200, res->status);
  6196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6197. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6198. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6199. }
  6200. TEST_F(ServerTest, HTTPResponseSplitting) {
  6201. auto res = cli_.Get("/http_response_splitting");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. EXPECT_EQ(StatusCode::OK_200, res->status);
  6204. }
  6205. TEST_F(ServerTest, SlowRequest) {
  6206. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6207. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6208. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6209. }
  6210. #if 0
  6211. TEST_F(ServerTest, SlowPost) {
  6212. char buffer[64 * 1024];
  6213. memset(buffer, 0x42, sizeof(buffer));
  6214. auto res = cli_.Post(
  6215. "/slowpost", 64 * 1024 * 1024,
  6216. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6217. auto ret = sink.write(buffer, sizeof(buffer));
  6218. EXPECT_TRUE(ret);
  6219. return true;
  6220. },
  6221. "text/plain");
  6222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6223. EXPECT_EQ(StatusCode::OK_200, res->status);
  6224. }
  6225. TEST_F(ServerTest, SlowPostFail) {
  6226. char buffer[64 * 1024];
  6227. memset(buffer, 0x42, sizeof(buffer));
  6228. cli_.set_write_timeout(std::chrono::seconds(0));
  6229. auto res = cli_.Post(
  6230. "/slowpost", 64 * 1024 * 1024,
  6231. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6232. sink.write(buffer, sizeof(buffer));
  6233. return true;
  6234. },
  6235. "text/plain");
  6236. ASSERT_TRUE(!res);
  6237. EXPECT_EQ(Error::Write, res.error());
  6238. }
  6239. #endif
  6240. TEST_F(ServerTest, Put) {
  6241. auto res = cli_.Put("/put", "PUT", "text/plain");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. EXPECT_EQ(StatusCode::OK_200, res->status);
  6244. EXPECT_EQ("PUT", res->body);
  6245. }
  6246. TEST_F(ServerTest, PutWithContentProvider) {
  6247. auto res = cli_.Put(
  6248. "/put", 3,
  6249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6250. sink.os << "PUT";
  6251. return true;
  6252. },
  6253. "text/plain");
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::OK_200, res->status);
  6256. EXPECT_EQ("PUT", res->body);
  6257. }
  6258. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6259. auto res = cli_.Post(
  6260. "/post", 42,
  6261. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6262. return false;
  6263. },
  6264. "text/plain");
  6265. ASSERT_TRUE(!res);
  6266. EXPECT_EQ(Error::Canceled, res.error());
  6267. }
  6268. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6269. auto res = cli_.Put(
  6270. "/put",
  6271. [](size_t /*offset*/, DataSink &sink) {
  6272. sink.os << "PUT";
  6273. sink.done();
  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, PostWithContentProviderWithoutLengthAbort) {
  6282. auto res = cli_.Post(
  6283. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6284. "text/plain");
  6285. ASSERT_TRUE(!res);
  6286. EXPECT_EQ(Error::Canceled, res.error());
  6287. }
  6288. TEST_F(ServerTest, PostLoopBack) {
  6289. std::string body;
  6290. auto res = cli_.Post(
  6291. "/post-loopback", 9,
  6292. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6293. EXPECT_EQ(9u, length);
  6294. sink.write("123", 3);
  6295. sink.write("456", 3);
  6296. sink.write("789", 3);
  6297. return true;
  6298. },
  6299. "text/plain",
  6300. [&body](const char *data, size_t data_length) {
  6301. body.append(data, data_length);
  6302. return true;
  6303. });
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. EXPECT_EQ(StatusCode::OK_200, res->status);
  6306. EXPECT_EQ("123456789", body);
  6307. }
  6308. TEST_F(ServerTest, PutLoopBack) {
  6309. std::string body;
  6310. auto res = cli_.Put(
  6311. "/put-loopback", 9,
  6312. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6313. EXPECT_EQ(9u, length);
  6314. sink.write("123", 3);
  6315. sink.write("456", 3);
  6316. sink.write("789", 3);
  6317. return true;
  6318. },
  6319. "text/plain",
  6320. [&body](const char *data, size_t data_length) {
  6321. body.append(data, data_length);
  6322. return true;
  6323. });
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::OK_200, res->status);
  6326. EXPECT_EQ("123456789", body);
  6327. }
  6328. TEST_F(ServerTest, PatchLoopBack) {
  6329. std::string body;
  6330. auto res = cli_.Patch(
  6331. "/patch-loopback", 9,
  6332. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6333. EXPECT_EQ(9u, length);
  6334. sink.write("123", 3);
  6335. sink.write("456", 3);
  6336. sink.write("789", 3);
  6337. return true;
  6338. },
  6339. "text/plain",
  6340. [&body](const char *data, size_t data_length) {
  6341. body.append(data, data_length);
  6342. return true;
  6343. });
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. EXPECT_EQ("123456789", body);
  6347. }
  6348. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6349. std::string body;
  6350. auto res = cli_.Post(
  6351. "/post-loopback",
  6352. [](size_t /*offset*/, DataSink &sink) {
  6353. sink.write("123", 3);
  6354. sink.write("456", 3);
  6355. sink.write("789", 3);
  6356. sink.done();
  6357. return true;
  6358. },
  6359. "text/plain",
  6360. [&body](const char *data, size_t data_length) {
  6361. body.append(data, data_length);
  6362. return true;
  6363. });
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::OK_200, res->status);
  6366. EXPECT_EQ("123456789", body);
  6367. }
  6368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6369. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6370. cli_.set_compress(true);
  6371. auto res = cli_.Put(
  6372. "/put", 3,
  6373. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6374. sink.os << "PUT";
  6375. return true;
  6376. },
  6377. "text/plain");
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. EXPECT_EQ("PUT", res->body);
  6381. }
  6382. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6383. cli_.set_compress(true);
  6384. auto res = cli_.Post(
  6385. "/post", 42,
  6386. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6387. return false;
  6388. },
  6389. "text/plain");
  6390. ASSERT_TRUE(!res);
  6391. EXPECT_EQ(Error::Canceled, res.error());
  6392. }
  6393. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6394. cli_.set_compress(true);
  6395. auto res = cli_.Put(
  6396. "/put",
  6397. [](size_t /*offset*/, DataSink &sink) {
  6398. sink.os << "PUT";
  6399. sink.done();
  6400. return true;
  6401. },
  6402. "text/plain");
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::OK_200, res->status);
  6405. EXPECT_EQ("PUT", res->body);
  6406. }
  6407. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6408. cli_.set_compress(true);
  6409. auto res = cli_.Post(
  6410. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6411. "text/plain");
  6412. ASSERT_TRUE(!res);
  6413. EXPECT_EQ(Error::Canceled, res.error());
  6414. }
  6415. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6416. cli_.set_compress(true);
  6417. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. EXPECT_EQ(LARGE_DATA, res->body);
  6421. }
  6422. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6423. #ifdef CPPHTTPLIB_SSL_ENABLED
  6424. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6425. Client cli(s.c_str());
  6426. cli.enable_server_certificate_verification(false);
  6427. #else
  6428. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6429. Client cli(s.c_str());
  6430. #endif
  6431. cli.set_compress(true);
  6432. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ(LARGE_DATA, res->body);
  6436. // The compressed size should be less than a 10th of the original. May vary
  6437. // depending on the zlib library.
  6438. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6439. static_cast<uint64_t>(10 * 1024 * 1024));
  6440. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6441. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6442. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6443. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6444. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6445. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6446. #endif
  6447. }
  6448. TEST_F(ServerTest, PutContentWithDeflate) {
  6449. cli_.set_compress(false);
  6450. Headers headers;
  6451. headers.emplace("Content-Encoding", "deflate");
  6452. // PUT in deflate format:
  6453. auto res = cli_.Put("/put", headers,
  6454. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. EXPECT_EQ("PUT", res->body);
  6458. }
  6459. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6460. Headers headers;
  6461. headers.emplace("Accept-Encoding", "gzip, deflate");
  6462. auto res = cli_.Get("/streamed-chunked", headers);
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ(StatusCode::OK_200, res->status);
  6465. EXPECT_EQ(std::string("123456789"), res->body);
  6466. }
  6467. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6468. Headers headers;
  6469. headers.emplace("Accept-Encoding", "gzip, deflate");
  6470. auto res = cli_.Get("/streamed-chunked2", headers);
  6471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6472. EXPECT_EQ(StatusCode::OK_200, res->status);
  6473. EXPECT_EQ(std::string("123456789"), res->body);
  6474. }
  6475. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6476. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. EXPECT_EQ(StatusCode::OK_200, res->status);
  6479. }
  6480. TEST(GzipDecompressor, ChunkedDecompression) {
  6481. std::string data;
  6482. for (size_t i = 0; i < 32 * 1024; ++i) {
  6483. data.push_back(static_cast<char>('a' + i % 26));
  6484. }
  6485. std::string compressed_data;
  6486. {
  6487. httplib::detail::gzip_compressor compressor;
  6488. bool result = compressor.compress(
  6489. data.data(), data.size(),
  6490. /*last=*/true,
  6491. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6492. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6493. compressed_data_size);
  6494. return true;
  6495. });
  6496. ASSERT_TRUE(result);
  6497. }
  6498. std::string decompressed_data;
  6499. {
  6500. httplib::detail::gzip_decompressor decompressor;
  6501. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6502. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6503. size_t chunk_size = 130;
  6504. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6505. chunk_begin += chunk_size) {
  6506. size_t current_chunk_size =
  6507. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6508. bool result = decompressor.decompress(
  6509. compressed_data.data() + chunk_begin, current_chunk_size,
  6510. [&](const char *decompressed_data_chunk,
  6511. size_t decompressed_data_chunk_size) {
  6512. decompressed_data.insert(decompressed_data.size(),
  6513. decompressed_data_chunk,
  6514. decompressed_data_chunk_size);
  6515. return true;
  6516. });
  6517. ASSERT_TRUE(result);
  6518. }
  6519. }
  6520. ASSERT_EQ(data, decompressed_data);
  6521. }
  6522. TEST(GzipDecompressor, DeflateDecompression) {
  6523. std::string original_text = "Raw deflate without gzip";
  6524. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6525. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6526. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6527. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6528. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6529. std::string decompressed_data;
  6530. {
  6531. httplib::detail::gzip_decompressor decompressor;
  6532. bool result = decompressor.decompress(
  6533. compressed_data.data(), compressed_data.size(),
  6534. [&](const char *decompressed_data_chunk,
  6535. size_t decompressed_data_chunk_size) {
  6536. decompressed_data.insert(decompressed_data.size(),
  6537. decompressed_data_chunk,
  6538. decompressed_data_chunk_size);
  6539. return true;
  6540. });
  6541. ASSERT_TRUE(result);
  6542. }
  6543. ASSERT_EQ(original_text, decompressed_data);
  6544. }
  6545. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6546. std::string original_text = "Raw deflate without gzip";
  6547. unsigned char data[40] = {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. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6552. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6553. std::string decompressed_data;
  6554. {
  6555. httplib::detail::gzip_decompressor decompressor;
  6556. bool result = decompressor.decompress(
  6557. compressed_data.data(), compressed_data.size(),
  6558. [&](const char *decompressed_data_chunk,
  6559. size_t decompressed_data_chunk_size) {
  6560. decompressed_data.insert(decompressed_data.size(),
  6561. decompressed_data_chunk,
  6562. decompressed_data_chunk_size);
  6563. return true;
  6564. });
  6565. ASSERT_TRUE(result);
  6566. }
  6567. ASSERT_EQ(original_text, decompressed_data);
  6568. }
  6569. #endif
  6570. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6571. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6572. Headers headers;
  6573. headers.emplace("Accept-Encoding", "br");
  6574. auto res = cli_.Get("/streamed-chunked", headers);
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. EXPECT_EQ(std::string("123456789"), res->body);
  6578. }
  6579. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6580. Headers headers;
  6581. headers.emplace("Accept-Encoding", "br");
  6582. auto res = cli_.Get("/streamed-chunked2", headers);
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::OK_200, res->status);
  6585. EXPECT_EQ(std::string("123456789"), res->body);
  6586. }
  6587. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6588. cli_.set_compress(true);
  6589. auto res = cli_.Put(
  6590. "/put", 3,
  6591. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6592. sink.os << "PUT";
  6593. return true;
  6594. },
  6595. "text/plain");
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. EXPECT_EQ(StatusCode::OK_200, res->status);
  6598. EXPECT_EQ("PUT", res->body);
  6599. }
  6600. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6601. cli_.set_compress(true);
  6602. auto res = cli_.Put(
  6603. "/put",
  6604. [](size_t /*offset*/, DataSink &sink) {
  6605. sink.os << "PUT";
  6606. sink.done();
  6607. return true;
  6608. },
  6609. "text/plain");
  6610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6611. EXPECT_EQ(StatusCode::OK_200, res->status);
  6612. EXPECT_EQ("PUT", res->body);
  6613. }
  6614. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6615. cli_.set_compress(true);
  6616. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ(LARGE_DATA, res->body);
  6620. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6621. }
  6622. #endif
  6623. TEST_F(ServerTest, Patch) {
  6624. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. EXPECT_EQ("PATCH", res->body);
  6628. }
  6629. TEST_F(ServerTest, Delete) {
  6630. auto res = cli_.Delete("/delete");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::OK_200, res->status);
  6633. EXPECT_EQ("DELETE", res->body);
  6634. }
  6635. TEST_F(ServerTest, DeleteContentReceiver) {
  6636. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("content", res->body);
  6640. }
  6641. TEST_F(ServerTest, Options) {
  6642. auto res = cli_.Options("*");
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6646. EXPECT_TRUE(res->body.empty());
  6647. }
  6648. TEST_F(ServerTest, URL) {
  6649. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. }
  6653. TEST_F(ServerTest, ArrayParam) {
  6654. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. }
  6658. TEST_F(ServerTest, ArrayParamValues) {
  6659. auto res =
  6660. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. }
  6664. TEST_F(ServerTest, NoMultipleHeaders) {
  6665. Headers headers = {{"Content-Length", "5"}};
  6666. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6667. "text/plain");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. }
  6671. TEST_F(ServerTest, PostContentReceiver) {
  6672. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. ASSERT_EQ(StatusCode::OK_200, res->status);
  6675. ASSERT_EQ("content", res->body);
  6676. }
  6677. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6678. UploadFormDataItems items = {
  6679. {"text1", "text default", "", ""},
  6680. {"text2", "aωb", "", ""},
  6681. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6682. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6683. {"file3", "", "", "application/octet-stream"},
  6684. };
  6685. auto res = cli_.Post("/content_receiver", items);
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. }
  6689. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6690. UploadFormDataItems items = {
  6691. {"text1", "text default", "", ""},
  6692. {"text2", "aωb", "", ""},
  6693. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6694. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6695. {"file3", "", "", "application/octet-stream"},
  6696. };
  6697. auto boundary = std::string("+++++");
  6698. std::string body;
  6699. for (const auto &item : items) {
  6700. body += "--" + boundary + "\r\n";
  6701. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6702. if (!item.filename.empty()) {
  6703. body += "; filename=\"" + item.filename + "\"";
  6704. }
  6705. body += "\r\n";
  6706. if (!item.content_type.empty()) {
  6707. body += "Content-Type: " + item.content_type + "\r\n";
  6708. }
  6709. body += "\r\n";
  6710. body += item.content + "\r\n";
  6711. }
  6712. body += "--" + boundary + "--\r\n";
  6713. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6714. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. }
  6718. TEST(MultipartFormDataTest, FieldEscaping) {
  6719. Server svr;
  6720. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6721. const ContentReader &content_reader) {
  6722. ASSERT_TRUE(req.is_multipart_form_data());
  6723. std::vector<FormData> received;
  6724. content_reader(
  6725. [&](const FormData &file) {
  6726. received.push_back(file);
  6727. return true;
  6728. },
  6729. [&](const char *data, size_t data_length) {
  6730. received.back().content.append(data, data_length);
  6731. return true;
  6732. });
  6733. // '"', CR and LF in names and filenames are escaped following the
  6734. // WHATWG HTML standard, so each part still parses as a single part
  6735. // with no injected headers. Content types get CR/LF escaped too,
  6736. // while '"' (legal there, e.g. quoted charset) is preserved.
  6737. ASSERT_EQ(4U, received.size());
  6738. EXPECT_EQ("na%22me", received[0].name);
  6739. EXPECT_EQ("quoted name", received[0].content);
  6740. EXPECT_EQ("file", received[1].name);
  6741. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6742. received[1].filename);
  6743. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6744. EXPECT_EQ("injected", received[1].content);
  6745. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6746. EXPECT_EQ("my%22file.txt", received[2].filename);
  6747. EXPECT_EQ("cr lf name", received[2].content);
  6748. EXPECT_EQ("typed", received[3].name);
  6749. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6750. received[3].content_type);
  6751. EXPECT_EQ("typed content", received[3].content);
  6752. });
  6753. auto port = svr.bind_to_any_port("localhost");
  6754. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6755. auto se = detail::scope_exit([&] {
  6756. svr.stop();
  6757. t.join();
  6758. ASSERT_FALSE(svr.is_running());
  6759. });
  6760. svr.wait_until_ready();
  6761. Client cli("localhost", port);
  6762. UploadFormDataItems items = {
  6763. {"na\"me", "quoted name", "", ""},
  6764. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6765. "application/octet-stream"},
  6766. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6767. {"typed", "typed content", "",
  6768. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6769. };
  6770. auto res = cli.Post("/post", items);
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. }
  6774. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6775. const UploadFormDataItems items = {
  6776. {"name1", "Content 1", "", ""},
  6777. {"name2", "Content 2", "file2.txt", "text/plain"},
  6778. };
  6779. Server svr;
  6780. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6781. const ContentReader &content_reader) {
  6782. ASSERT_TRUE(req.is_multipart_form_data());
  6783. std::vector<FormData> received;
  6784. content_reader(
  6785. [&](const FormData &file) {
  6786. received.push_back(file);
  6787. return true;
  6788. },
  6789. [&](const char *data, size_t data_length) {
  6790. received.back().content.append(data, data_length);
  6791. return true;
  6792. });
  6793. ASSERT_EQ(2U, received.size());
  6794. EXPECT_EQ("name1", received[0].name);
  6795. EXPECT_EQ("Content 1", received[0].content);
  6796. EXPECT_EQ("name2", received[1].name);
  6797. EXPECT_EQ("Content 2", received[1].content);
  6798. EXPECT_EQ("file2.txt", received[1].filename);
  6799. EXPECT_EQ("text/plain", received[1].content_type);
  6800. });
  6801. auto port = svr.bind_to_any_port("localhost");
  6802. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6803. auto se = detail::scope_exit([&] {
  6804. svr.stop();
  6805. t.join();
  6806. ASSERT_FALSE(svr.is_running());
  6807. });
  6808. svr.wait_until_ready();
  6809. Client cli("localhost", port);
  6810. // Whole-body serialization with a generated boundary
  6811. {
  6812. MultipartFormDataWriter writer;
  6813. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6814. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6815. writer.content_type());
  6816. auto body = writer.serialize(items);
  6817. EXPECT_EQ(body.size(), writer.content_length(items));
  6818. auto res = cli.Post("/post", body, writer.content_type());
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. }
  6822. // Per-part framing with a custom boundary via a content provider
  6823. {
  6824. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6825. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6826. MultipartFormDataWriter writer("custom-boundary_123");
  6827. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6828. std::string body;
  6829. for (const auto &item : items) {
  6830. body += writer.item_begin(item);
  6831. body += item.content;
  6832. body += MultipartFormDataWriter::item_end();
  6833. }
  6834. body += writer.finish();
  6835. EXPECT_EQ(body.size(), writer.content_length(items));
  6836. auto res = cli.Post(
  6837. "/post", body.size(),
  6838. [&](size_t offset, size_t length, DataSink &sink) {
  6839. sink.write(body.data() + offset, length);
  6840. return true;
  6841. },
  6842. writer.content_type());
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. }
  6846. }
  6847. TEST_F(ServerTest, PostContentReceiverGzip) {
  6848. cli_.set_compress(true);
  6849. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. ASSERT_EQ(StatusCode::OK_200, res->status);
  6852. ASSERT_EQ("content", res->body);
  6853. }
  6854. TEST_F(ServerTest, PutContentReceiver) {
  6855. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. ASSERT_EQ(StatusCode::OK_200, res->status);
  6858. ASSERT_EQ("content", res->body);
  6859. }
  6860. TEST_F(ServerTest, PatchContentReceiver) {
  6861. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. ASSERT_EQ(StatusCode::OK_200, res->status);
  6864. ASSERT_EQ("content", res->body);
  6865. }
  6866. template <typename ClientType>
  6867. void TestWithHeadersAndContentReceiver(
  6868. ClientType &cli,
  6869. std::function<Result(ClientType &, const std::string &, const Headers &,
  6870. const std::string &, const std::string &,
  6871. ContentReceiver, DownloadProgress)>
  6872. request_func) {
  6873. Headers headers;
  6874. headers.emplace("X-Custom-Header", "test-value");
  6875. std::string received_body;
  6876. auto res = request_func(
  6877. cli, "/content_receiver", headers, "content", "application/json",
  6878. [&](const char *data, size_t data_length) {
  6879. received_body.append(data, data_length);
  6880. return true;
  6881. },
  6882. nullptr);
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::OK_200, res->status);
  6885. EXPECT_EQ("content", received_body);
  6886. }
  6887. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6888. #ifdef CPPHTTPLIB_SSL_ENABLED
  6889. using ClientT = SSLClient;
  6890. #else
  6891. using ClientT = Client;
  6892. #endif
  6893. TestWithHeadersAndContentReceiver<ClientT>(
  6894. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6895. const std::string &body, const std::string &content_type,
  6896. ContentReceiver receiver, DownloadProgress progress) {
  6897. return cli.Post(path, headers, body, content_type, receiver, progress);
  6898. });
  6899. }
  6900. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6901. #ifdef CPPHTTPLIB_SSL_ENABLED
  6902. using ClientT = SSLClient;
  6903. #else
  6904. using ClientT = Client;
  6905. #endif
  6906. TestWithHeadersAndContentReceiver<ClientT>(
  6907. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6908. const std::string &body, const std::string &content_type,
  6909. ContentReceiver receiver, DownloadProgress progress) {
  6910. return cli.Put(path, headers, body, content_type, receiver, progress);
  6911. });
  6912. }
  6913. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6914. #ifdef CPPHTTPLIB_SSL_ENABLED
  6915. using ClientT = SSLClient;
  6916. #else
  6917. using ClientT = Client;
  6918. #endif
  6919. TestWithHeadersAndContentReceiver<ClientT>(
  6920. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6921. const std::string &body, const std::string &content_type,
  6922. ContentReceiver receiver, DownloadProgress progress) {
  6923. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6924. });
  6925. }
  6926. template <typename ClientType>
  6927. void TestWithHeadersAndContentReceiverWithProgress(
  6928. ClientType &cli,
  6929. std::function<Result(ClientType &, const std::string &, const Headers &,
  6930. const std::string &, const std::string &,
  6931. ContentReceiver, DownloadProgress)>
  6932. request_func) {
  6933. Headers headers;
  6934. headers.emplace("X-Test-Header", "progress-test");
  6935. std::string received_body;
  6936. auto progress_called = false;
  6937. auto res = request_func(
  6938. cli, "/content_receiver", headers, "content", "text/plain",
  6939. [&](const char *data, size_t data_length) {
  6940. received_body.append(data, data_length);
  6941. return true;
  6942. },
  6943. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6944. progress_called = true;
  6945. return true;
  6946. });
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. EXPECT_EQ("content", received_body);
  6950. EXPECT_TRUE(progress_called);
  6951. }
  6952. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6953. #ifdef CPPHTTPLIB_SSL_ENABLED
  6954. using ClientT = SSLClient;
  6955. #else
  6956. using ClientT = Client;
  6957. #endif
  6958. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6959. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6960. const std::string &body, const std::string &content_type,
  6961. ContentReceiver receiver, DownloadProgress progress) {
  6962. return cli.Post(path, headers, body, content_type, receiver, progress);
  6963. });
  6964. }
  6965. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6966. #ifdef CPPHTTPLIB_SSL_ENABLED
  6967. using ClientT = SSLClient;
  6968. #else
  6969. using ClientT = Client;
  6970. #endif
  6971. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6972. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6973. const std::string &body, const std::string &content_type,
  6974. ContentReceiver receiver, DownloadProgress progress) {
  6975. return cli.Put(path, headers, body, content_type, receiver, progress);
  6976. });
  6977. }
  6978. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6979. #ifdef CPPHTTPLIB_SSL_ENABLED
  6980. using ClientT = SSLClient;
  6981. #else
  6982. using ClientT = Client;
  6983. #endif
  6984. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6985. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6986. const std::string &body, const std::string &content_type,
  6987. ContentReceiver receiver, DownloadProgress progress) {
  6988. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6989. });
  6990. }
  6991. template <typename ClientType>
  6992. void TestWithHeadersAndContentReceiverError(
  6993. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6994. const Headers &, const std::string &,
  6995. const std::string &, ContentReceiver)>
  6996. request_func) {
  6997. Headers headers;
  6998. headers.emplace("X-Error-Test", "true");
  6999. std::string received_body;
  7000. auto receiver_failed = false;
  7001. auto res =
  7002. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7003. [&](const char *data, size_t data_length) {
  7004. received_body.append(data, data_length);
  7005. receiver_failed = true;
  7006. return false;
  7007. });
  7008. ASSERT_FALSE(res);
  7009. EXPECT_TRUE(receiver_failed);
  7010. }
  7011. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7012. #ifdef CPPHTTPLIB_SSL_ENABLED
  7013. using ClientT = SSLClient;
  7014. #else
  7015. using ClientT = Client;
  7016. #endif
  7017. TestWithHeadersAndContentReceiverError<ClientT>(
  7018. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7019. const std::string &body, const std::string &content_type,
  7020. ContentReceiver receiver) {
  7021. return cli.Post(path, headers, body, content_type, receiver);
  7022. });
  7023. }
  7024. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7025. #ifdef CPPHTTPLIB_SSL_ENABLED
  7026. using ClientT = SSLClient;
  7027. #else
  7028. using ClientT = Client;
  7029. #endif
  7030. TestWithHeadersAndContentReceiverError<ClientT>(
  7031. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7032. const std::string &body, const std::string &content_type,
  7033. ContentReceiver receiver) {
  7034. return cli.Put(path, headers, body, content_type, receiver);
  7035. });
  7036. }
  7037. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7038. #ifdef CPPHTTPLIB_SSL_ENABLED
  7039. using ClientT = SSLClient;
  7040. #else
  7041. using ClientT = Client;
  7042. #endif
  7043. TestWithHeadersAndContentReceiverError<ClientT>(
  7044. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7045. const std::string &body, const std::string &content_type,
  7046. ContentReceiver receiver) {
  7047. return cli.Patch(path, headers, body, content_type, receiver);
  7048. });
  7049. }
  7050. TEST_F(ServerTest, PostQueryStringAndBody) {
  7051. auto res =
  7052. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. ASSERT_EQ(StatusCode::OK_200, res->status);
  7055. }
  7056. TEST_F(ServerTest, HTTP2Magic) {
  7057. Request req;
  7058. req.method = "PRI";
  7059. req.path = "*";
  7060. req.body = "SM";
  7061. auto res = std::make_shared<Response>();
  7062. auto error = Error::Success;
  7063. auto ret = cli_.send(req, *res, error);
  7064. ASSERT_TRUE(ret);
  7065. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7066. }
  7067. TEST_F(ServerTest, KeepAlive) {
  7068. auto res = cli_.Get("/hi");
  7069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7070. EXPECT_EQ(StatusCode::OK_200, res->status);
  7071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7072. EXPECT_EQ("Hello World!", res->body);
  7073. res = cli_.Get("/hi");
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7077. EXPECT_EQ("Hello World!", res->body);
  7078. res = cli_.Get("/hi");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7082. EXPECT_EQ("Hello World!", res->body);
  7083. res = cli_.Get("/not-exist");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7086. res = cli_.Post("/empty", "", "text/plain");
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::OK_200, res->status);
  7089. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7090. EXPECT_EQ("empty", res->body);
  7091. EXPECT_EQ("close", res->get_header_value("Connection"));
  7092. res = cli_.Post(
  7093. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7094. "text/plain");
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7098. EXPECT_EQ("empty", res->body);
  7099. cli_.set_keep_alive(false);
  7100. res = cli_.Get("/last-request");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. EXPECT_EQ("close", res->get_header_value("Connection"));
  7104. }
  7105. TEST_F(ServerTest, TooManyRedirect) {
  7106. cli_.set_follow_location(true);
  7107. auto res = cli_.Get("/redirect/0");
  7108. ASSERT_TRUE(!res);
  7109. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7110. }
  7111. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7112. Request req;
  7113. req.method = "FOOBAR";
  7114. req.path = "/hi";
  7115. cli_.set_keep_alive(true);
  7116. auto res = cli_.send(req);
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7119. EXPECT_EQ("close", res->get_header_value("Connection"));
  7120. EXPECT_FALSE(cli_.is_socket_open());
  7121. }
  7122. TEST_F(ServerTest, CustomRouteReadsBody) {
  7123. const std::string xml =
  7124. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7125. Request req;
  7126. req.method = "PROPFIND";
  7127. req.path = "/dav/dir";
  7128. req.set_header("Depth", "1");
  7129. req.body = xml;
  7130. auto res = cli_.send(req);
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7133. EXPECT_EQ(xml, res->body);
  7134. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7135. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7136. }
  7137. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7138. Request req;
  7139. req.method = "PROPFIND";
  7140. req.path = "/dav/42";
  7141. auto res = cli_.send(req);
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7144. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7145. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7146. }
  7147. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7148. Request req;
  7149. req.method = "PROPFIND";
  7150. req.path = "/dav-re/123";
  7151. auto res = cli_.send(req);
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7154. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7155. }
  7156. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7157. Request req;
  7158. req.method = "MKCOL";
  7159. req.path = "/dav-mkcol";
  7160. auto res = cli_.send(req);
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::Created_201, res->status);
  7163. }
  7164. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7165. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7166. Request req;
  7167. req.method = "REPORT";
  7168. req.path = "/dav-report";
  7169. req.body = xml;
  7170. auto res = cli_.send(req);
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7173. EXPECT_EQ(xml, res->body);
  7174. }
  7175. // A content reader route must fire even when the request carries no body,
  7176. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7177. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7178. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7179. Request req;
  7180. req.method = "REPORT";
  7181. req.path = "/dav-report";
  7182. auto res = cli_.send(req);
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7185. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7186. }
  7187. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7188. Request req;
  7189. req.method = "PROPFIND";
  7190. req.path = "/not-dav";
  7191. auto res = cli_.send(req);
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7194. }
  7195. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7196. Request req;
  7197. req.method = "UNLOCK";
  7198. req.path = "/dav/dir";
  7199. cli_.set_keep_alive(true);
  7200. auto res = cli_.send(req);
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7203. EXPECT_EQ("close", res->get_header_value("Connection"));
  7204. EXPECT_FALSE(cli_.is_socket_open());
  7205. }
  7206. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7207. // The mount point serves this path, but only for GET and HEAD.
  7208. auto get_res = cli_.Get("/dir/index.html");
  7209. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7210. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7211. Request req;
  7212. req.method = "PROPFIND";
  7213. req.path = "/dir/index.html";
  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, CustomRouteKeepAlive) {
  7219. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7220. cli_.set_keep_alive(true);
  7221. for (auto i = 0; i < 2; i++) {
  7222. Request req;
  7223. req.method = "PROPFIND";
  7224. req.path = "/dav/dir";
  7225. req.body = xml;
  7226. auto res = cli_.send(req);
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7229. EXPECT_EQ(xml, res->body);
  7230. EXPECT_TRUE(cli_.is_socket_open());
  7231. }
  7232. // A built-in method must still be served on the same connection.
  7233. cli_.set_keep_alive(false);
  7234. auto res = cli_.Get("/hi");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::OK_200, res->status);
  7237. EXPECT_EQ("close", res->get_header_value("Connection"));
  7238. }
  7239. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7240. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7241. Request req;
  7242. req.method = "PROPFIND";
  7243. req.path = "/dav/dir";
  7244. req.set_header("Expect", "100-continue");
  7245. req.body = xml;
  7246. auto res = cli_.send(req);
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7249. EXPECT_EQ(xml, res->body);
  7250. }
  7251. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7252. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7253. TEST_F(ServerTest, Gzip) {
  7254. Headers headers;
  7255. headers.emplace("Accept-Encoding", "gzip, deflate");
  7256. auto res = cli_.Get("/compress", headers);
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7260. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7261. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7262. "7890123456789012345678901234567890",
  7263. res->body);
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. }
  7266. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7267. Headers headers;
  7268. headers.emplace("Accept-Encoding", "gzip, deflate");
  7269. auto res = cli_.Get("/compress-with-charset", headers);
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7272. EXPECT_EQ("application/json; charset=utf-8",
  7273. res->get_header_value("Content-Type"));
  7274. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7275. "7890123456789012345678901234567890",
  7276. res->body);
  7277. EXPECT_EQ(StatusCode::OK_200, res->status);
  7278. }
  7279. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7280. Headers headers;
  7281. headers.emplace("Accept-Encoding", "");
  7282. auto res = cli_.Get("/compress", headers);
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7285. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7286. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7287. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7288. "7890123456789012345678901234567890",
  7289. res->body);
  7290. EXPECT_EQ(StatusCode::OK_200, res->status);
  7291. }
  7292. TEST_F(ServerTest, GzipWithContentReceiver) {
  7293. Headers headers;
  7294. headers.emplace("Accept-Encoding", "gzip, deflate");
  7295. std::string body;
  7296. auto res = cli_.Get("/compress", headers,
  7297. [&](const char *data, uint64_t data_length) {
  7298. EXPECT_EQ(100U, data_length);
  7299. body.append(data, data_length);
  7300. return true;
  7301. });
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7305. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7306. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7307. "7890123456789012345678901234567890",
  7308. body);
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. }
  7311. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7312. Headers headers;
  7313. headers.emplace("Accept-Encoding", "gzip, deflate");
  7314. cli_.set_decompress(false);
  7315. auto res = cli_.Get("/compress", headers);
  7316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7317. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7319. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7320. EXPECT_EQ(33U, res->body.size());
  7321. EXPECT_EQ(StatusCode::OK_200, res->status);
  7322. }
  7323. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7324. Headers headers;
  7325. headers.emplace("Accept-Encoding", "");
  7326. std::string body;
  7327. auto res = cli_.Get("/compress", headers,
  7328. [&](const char *data, uint64_t data_length) {
  7329. EXPECT_EQ(100U, data_length);
  7330. body.append(data, data_length);
  7331. return true;
  7332. });
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7336. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7338. "7890123456789012345678901234567890",
  7339. body);
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST_F(ServerTest, NoGzip) {
  7343. Headers headers;
  7344. headers.emplace("Accept-Encoding", "gzip, deflate");
  7345. auto res = cli_.Get("/nocompress", headers);
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7348. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7349. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7350. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7351. "7890123456789012345678901234567890",
  7352. res->body);
  7353. EXPECT_EQ(StatusCode::OK_200, res->status);
  7354. }
  7355. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7356. Headers headers;
  7357. headers.emplace("Accept-Encoding", "gzip, deflate");
  7358. std::string body;
  7359. auto res = cli_.Get("/nocompress", headers,
  7360. [&](const char *data, uint64_t data_length) {
  7361. EXPECT_EQ(100U, data_length);
  7362. body.append(data, data_length);
  7363. return true;
  7364. });
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7367. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7368. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7369. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7370. "7890123456789012345678901234567890",
  7371. body);
  7372. EXPECT_EQ(StatusCode::OK_200, res->status);
  7373. }
  7374. TEST_F(ServerTest, MultipartFormDataGzip) {
  7375. UploadFormDataItems items = {
  7376. {"key1", "test", "", ""},
  7377. {"key2", "--abcdefg123", "", ""},
  7378. };
  7379. cli_.set_compress(true);
  7380. auto res = cli_.Post("/compress-multipart", items);
  7381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. #endif
  7385. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7386. TEST_F(ServerTest, Brotli) {
  7387. Headers headers;
  7388. headers.emplace("Accept-Encoding", "br");
  7389. auto res = cli_.Get("/compress", headers);
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7393. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7394. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7395. "7890123456789012345678901234567890",
  7396. res->body);
  7397. EXPECT_EQ(StatusCode::OK_200, res->status);
  7398. }
  7399. #endif
  7400. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7401. TEST_F(ServerTest, Zstd) {
  7402. Headers headers;
  7403. headers.emplace("Accept-Encoding", "zstd");
  7404. auto res = cli_.Get("/compress", headers);
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7408. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7410. "7890123456789012345678901234567890",
  7411. res->body);
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7415. Headers headers;
  7416. headers.emplace("Accept-Encoding", "");
  7417. auto res = cli_.Get("/compress", headers);
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7421. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7423. "7890123456789012345678901234567890",
  7424. res->body);
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7428. Headers headers;
  7429. headers.emplace("Accept-Encoding", "zstd");
  7430. std::string body;
  7431. auto res = cli_.Get("/compress", headers,
  7432. [&](const char *data, uint64_t data_length) {
  7433. EXPECT_EQ(100U, data_length);
  7434. body.append(data, data_length);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7439. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7440. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7441. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7442. "7890123456789012345678901234567890",
  7443. body);
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7447. Headers headers;
  7448. headers.emplace("Accept-Encoding", "zstd");
  7449. cli_.set_decompress(false);
  7450. auto res = cli_.Get("/compress", headers);
  7451. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7452. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7453. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7454. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7456. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7457. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7458. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. ASSERT_EQ(26U, res->body.size());
  7461. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7462. 0);
  7463. }
  7464. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7465. Headers headers;
  7466. headers.emplace("Accept-Encoding", "");
  7467. std::string body;
  7468. auto res = cli_.Get("/compress", headers,
  7469. [&](const char *data, uint64_t data_length) {
  7470. EXPECT_EQ(100U, data_length);
  7471. body.append(data, data_length);
  7472. return true;
  7473. });
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7477. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7478. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7479. "7890123456789012345678901234567890",
  7480. body);
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. }
  7483. TEST_F(ServerTest, NoZstd) {
  7484. Headers headers;
  7485. headers.emplace("Accept-Encoding", "zstd");
  7486. auto res = cli_.Get("/nocompress", headers);
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7490. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7491. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7492. "7890123456789012345678901234567890",
  7493. res->body);
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. }
  7496. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7497. Headers headers;
  7498. headers.emplace("Accept-Encoding", "zstd");
  7499. std::string body;
  7500. auto res = cli_.Get("/nocompress", headers,
  7501. [&](const char *data, uint64_t data_length) {
  7502. EXPECT_EQ(100U, data_length);
  7503. body.append(data, data_length);
  7504. return true;
  7505. });
  7506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7507. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7508. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7509. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7510. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7511. "7890123456789012345678901234567890",
  7512. body);
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. }
  7515. // TODO: How to enable zstd ??
  7516. TEST_F(ServerTest, MultipartFormDataZstd) {
  7517. UploadFormDataItems items = {
  7518. {"key1", "test", "", ""},
  7519. {"key2", "--abcdefg123", "", ""},
  7520. };
  7521. Headers headers;
  7522. headers.emplace("Accept-Encoding", "zstd");
  7523. cli_.set_compress(true);
  7524. auto res = cli_.Post("/compress-multipart", headers, items);
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. }
  7528. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7529. Headers headers;
  7530. headers.emplace("Accept-Encoding", "zstd");
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Put(
  7533. "/put", headers, 3,
  7534. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7535. sink.os << "PUT";
  7536. return true;
  7537. },
  7538. "text/plain");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. EXPECT_EQ("PUT", res->body);
  7542. }
  7543. // Pre-compression logging tests
  7544. TEST_F(ServerTest, PreCompressionLogging) {
  7545. // Test data for compression (matches the actual /compress endpoint content)
  7546. const std::string test_content =
  7547. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7548. "3456789012345678901234567890";
  7549. // Variables to capture logging data
  7550. std::string pre_compression_body;
  7551. std::string pre_compression_content_type;
  7552. std::string pre_compression_content_encoding;
  7553. std::string post_compression_body;
  7554. std::string post_compression_content_type;
  7555. std::string post_compression_content_encoding;
  7556. // Set up pre-compression logger
  7557. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7558. const Response &res) {
  7559. pre_compression_body = res.body;
  7560. pre_compression_content_type = res.get_header_value("Content-Type");
  7561. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7562. });
  7563. // Set up post-compression logger
  7564. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7565. post_compression_body = res.body;
  7566. post_compression_content_type = res.get_header_value("Content-Type");
  7567. post_compression_content_encoding =
  7568. res.get_header_value("Content-Encoding");
  7569. });
  7570. // Test with gzip compression
  7571. Headers headers;
  7572. headers.emplace("Accept-Encoding", "gzip");
  7573. auto res = cli_.Get("/compress", headers);
  7574. // Verify response was compressed
  7575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7576. EXPECT_EQ(StatusCode::OK_200, res->status);
  7577. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7578. // Verify pre-compression logger captured uncompressed content
  7579. EXPECT_EQ(test_content, pre_compression_body);
  7580. EXPECT_EQ("text/plain", pre_compression_content_type);
  7581. EXPECT_TRUE(pre_compression_content_encoding
  7582. .empty()); // No encoding header before compression
  7583. // Verify post-compression logger captured compressed content
  7584. EXPECT_NE(test_content,
  7585. post_compression_body); // Should be different after compression
  7586. EXPECT_EQ("text/plain", post_compression_content_type);
  7587. EXPECT_EQ("gzip", post_compression_content_encoding);
  7588. // Verify compressed content is smaller
  7589. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7590. }
  7591. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7592. const std::string test_content =
  7593. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7594. "3456789012345678901234567890";
  7595. std::string pre_compression_body;
  7596. std::string post_compression_body;
  7597. svr_.set_pre_compression_logger(
  7598. [&](const Request & /*req*/, const Response &res) {
  7599. pre_compression_body = res.body;
  7600. });
  7601. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7602. post_compression_body = res.body;
  7603. });
  7604. Headers headers;
  7605. headers.emplace("Accept-Encoding", "br");
  7606. auto res = cli_.Get("/compress", headers);
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::OK_200, res->status);
  7609. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7610. // Verify pre-compression content is uncompressed
  7611. EXPECT_EQ(test_content, pre_compression_body);
  7612. // Verify post-compression content is compressed
  7613. EXPECT_NE(test_content, post_compression_body);
  7614. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7615. }
  7616. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7617. const std::string test_content =
  7618. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7619. "3456789012345678901234567890";
  7620. std::string pre_compression_body;
  7621. std::string post_compression_body;
  7622. svr_.set_pre_compression_logger(
  7623. [&](const Request & /*req*/, const Response &res) {
  7624. pre_compression_body = res.body;
  7625. });
  7626. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7627. post_compression_body = res.body;
  7628. });
  7629. // Request without compression (use /nocompress endpoint)
  7630. Headers headers;
  7631. auto res = cli_.Get("/nocompress", headers);
  7632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7633. EXPECT_EQ(StatusCode::OK_200, res->status);
  7634. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7635. // Pre-compression logger should not be called when no compression is applied
  7636. EXPECT_TRUE(
  7637. pre_compression_body.empty()); // Pre-compression logger not called
  7638. EXPECT_EQ(
  7639. test_content,
  7640. post_compression_body); // Post-compression logger captures final content
  7641. }
  7642. TEST_F(ServerTest, LoggerSeesContentLength) {
  7643. size_t logged_content_length = 0;
  7644. std::string logged_content_length_header;
  7645. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7646. logged_content_length = res.content_length_;
  7647. logged_content_length_header = res.get_header_value("Content-Length");
  7648. });
  7649. auto res = cli_.Get("/nocompress");
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::OK_200, res->status);
  7652. EXPECT_EQ(res->body.size(), logged_content_length);
  7653. EXPECT_EQ(std::to_string(logged_content_length),
  7654. logged_content_length_header);
  7655. }
  7656. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7657. const std::string test_content =
  7658. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7659. "3456789012345678901234567890";
  7660. std::string pre_compression_body;
  7661. bool pre_logger_called = false;
  7662. // Set only pre-compression logger
  7663. svr_.set_pre_compression_logger(
  7664. [&](const Request & /*req*/, const Response &res) {
  7665. pre_compression_body = res.body;
  7666. pre_logger_called = true;
  7667. });
  7668. Headers headers;
  7669. headers.emplace("Accept-Encoding", "gzip");
  7670. auto res = cli_.Get("/compress", headers);
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ(StatusCode::OK_200, res->status);
  7673. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7674. // Verify pre-compression logger was called
  7675. EXPECT_TRUE(pre_logger_called);
  7676. EXPECT_EQ(test_content, pre_compression_body);
  7677. }
  7678. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7679. {
  7680. // Test with Expect: 100-continue header - success case
  7681. // Server returns 100 Continue, client sends body, server returns 200 OK
  7682. Request req;
  7683. req.method = "POST";
  7684. req.path = "/post-large";
  7685. req.set_header("Expect", "100-continue");
  7686. req.body = LARGE_DATA;
  7687. Response res;
  7688. auto error = Error::Success;
  7689. cli_.set_keep_alive(true);
  7690. auto ret = cli_.send(req, res, error);
  7691. EXPECT_TRUE(ret);
  7692. EXPECT_EQ(StatusCode::OK_200, res.status);
  7693. EXPECT_EQ(LARGE_DATA, res.body);
  7694. }
  7695. {
  7696. // Test with Expect: 100-continue header - error case
  7697. // Client should not send the body when server returns an error
  7698. Request req;
  7699. req.method = "POST";
  7700. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7701. req.set_header("Expect", "100-continue");
  7702. req.body = LARGE_DATA;
  7703. Response res;
  7704. auto error = Error::Success;
  7705. auto start = std::chrono::high_resolution_clock::now();
  7706. cli_.set_keep_alive(true);
  7707. auto ret = cli_.send(req, res, error);
  7708. auto end = std::chrono::high_resolution_clock::now();
  7709. auto elapsed =
  7710. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7711. .count();
  7712. // With Expect: 100-continue, request completes successfully but with error
  7713. EXPECT_TRUE(ret);
  7714. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7715. EXPECT_EQ("close", res.get_header_value("Connection"));
  7716. EXPECT_FALSE(cli_.is_socket_open());
  7717. EXPECT_LE(elapsed, 2000);
  7718. }
  7719. {
  7720. // Send an extra GET request to ensure error recovery without hanging
  7721. Request req;
  7722. req.method = "GET";
  7723. req.path = "/hi";
  7724. auto start = std::chrono::high_resolution_clock::now();
  7725. auto res = cli_.send(req);
  7726. auto end = std::chrono::high_resolution_clock::now();
  7727. auto elapsed =
  7728. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7729. .count();
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ("Hello World!", res->body);
  7733. EXPECT_LE(elapsed, 500);
  7734. }
  7735. }
  7736. TEST(ZstdDecompressor, ChunkedDecompression) {
  7737. std::string data;
  7738. for (size_t i = 0; i < 32 * 1024; ++i) {
  7739. data.push_back(static_cast<char>('a' + i % 26));
  7740. }
  7741. std::string compressed_data;
  7742. {
  7743. httplib::detail::zstd_compressor compressor;
  7744. bool result = compressor.compress(
  7745. data.data(), data.size(),
  7746. /*last=*/true,
  7747. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7748. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7749. compressed_data_size);
  7750. return true;
  7751. });
  7752. ASSERT_TRUE(result);
  7753. }
  7754. std::string decompressed_data;
  7755. {
  7756. httplib::detail::zstd_decompressor decompressor;
  7757. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7758. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7759. size_t chunk_size = 130;
  7760. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7761. chunk_begin += chunk_size) {
  7762. size_t current_chunk_size =
  7763. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7764. bool result = decompressor.decompress(
  7765. compressed_data.data() + chunk_begin, current_chunk_size,
  7766. [&](const char *decompressed_data_chunk,
  7767. size_t decompressed_data_chunk_size) {
  7768. decompressed_data.insert(decompressed_data.size(),
  7769. decompressed_data_chunk,
  7770. decompressed_data_chunk_size);
  7771. return true;
  7772. });
  7773. ASSERT_TRUE(result);
  7774. }
  7775. }
  7776. ASSERT_EQ(data, decompressed_data);
  7777. }
  7778. TEST(ZstdDecompressor, Decompress) {
  7779. std::string original_text = "Compressed with ZSTD";
  7780. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7781. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7782. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7783. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7784. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7785. std::string decompressed_data;
  7786. {
  7787. httplib::detail::zstd_decompressor decompressor;
  7788. bool result = decompressor.decompress(
  7789. compressed_data.data(), compressed_data.size(),
  7790. [&](const char *decompressed_data_chunk,
  7791. size_t decompressed_data_chunk_size) {
  7792. decompressed_data.insert(decompressed_data.size(),
  7793. decompressed_data_chunk,
  7794. decompressed_data_chunk_size);
  7795. return true;
  7796. });
  7797. ASSERT_TRUE(result);
  7798. }
  7799. ASSERT_EQ(original_text, decompressed_data);
  7800. }
  7801. #endif
  7802. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7803. // separate chunks so that the server sees each part in its own read(). Used to
  7804. // place a read boundary at a specific offset of a request body.
  7805. static bool send_request_in_parts(time_t read_timeout_sec,
  7806. const std::vector<std::string> &parts,
  7807. std::string *resp = nullptr,
  7808. int port = PORT) {
  7809. auto error = Error::Success;
  7810. auto client_sock = detail::create_client_socket(
  7811. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7812. /*connection_timeout_sec=*/5, 0,
  7813. /*read_timeout_sec=*/5, 0,
  7814. /*write_timeout_sec=*/5, 0, std::string(), error);
  7815. if (client_sock == INVALID_SOCKET) { return false; }
  7816. auto ret = detail::process_client_socket(
  7817. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7818. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7819. for (size_t i = 0; i < parts.size(); i++) {
  7820. const auto &part = parts[i];
  7821. if (part.size() !=
  7822. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7823. return false;
  7824. }
  7825. if (i + 1 < parts.size()) {
  7826. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7827. }
  7828. }
  7829. char buf[512];
  7830. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7831. while (line_reader.getline()) {
  7832. if (resp) { *resp += line_reader.ptr(); }
  7833. }
  7834. return true;
  7835. });
  7836. detail::close_socket(client_sock);
  7837. return ret;
  7838. }
  7839. // Sends a raw request to a server listening at HOST:PORT.
  7840. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7841. std::string *resp = nullptr, int port = PORT) {
  7842. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7843. }
  7844. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7845. Server svr;
  7846. std::string header_value;
  7847. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7848. header_value = req.get_header_value("foo");
  7849. res.set_content("ok", "text/plain");
  7850. });
  7851. thread t = thread([&] { svr.listen(HOST, PORT); });
  7852. auto se = detail::scope_exit([&] {
  7853. svr.stop();
  7854. t.join();
  7855. ASSERT_FALSE(svr.is_running());
  7856. });
  7857. svr.wait_until_ready();
  7858. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7859. // like characters are not treated the same - use vertical tab and escape.
  7860. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7861. "foo: \t \v bar \x1B\t \r\n"
  7862. "Connection: close\r\n"
  7863. "\r\n";
  7864. std::string res;
  7865. ASSERT_TRUE(send_request(5, req, &res));
  7866. EXPECT_EQ(header_value, "");
  7867. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7868. }
  7869. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7870. Server svr;
  7871. std::string received;
  7872. svr.Get("/order", [&](const Request &req, Response &res) {
  7873. received = entries_to_string(req.headers);
  7874. res.set_content("ok", "text/plain");
  7875. });
  7876. auto port = svr.bind_to_any_port(HOST);
  7877. thread t = thread([&] { svr.listen_after_bind(); });
  7878. auto se = detail::scope_exit([&] {
  7879. svr.stop();
  7880. t.join();
  7881. ASSERT_FALSE(svr.is_running());
  7882. });
  7883. svr.wait_until_ready();
  7884. const std::string req = "GET /order HTTP/1.1\r\n"
  7885. "X-First: 1\r\n"
  7886. "X-Dup: a\r\n"
  7887. "X-Second: 2\r\n"
  7888. "X-Dup: b\r\n"
  7889. "Connection: close\r\n"
  7890. "\r\n";
  7891. std::string res;
  7892. ASSERT_TRUE(send_request(5, req, &res, port));
  7893. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7894. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7895. }
  7896. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7897. Server svr;
  7898. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7899. res.set_header("Set-Cookie", "first=1");
  7900. res.set_header("X-Between", "y");
  7901. res.set_header("Set-Cookie", "second=2");
  7902. res.set_content("ok", "text/plain");
  7903. });
  7904. auto port = svr.bind_to_any_port(HOST);
  7905. thread t = thread([&] { svr.listen_after_bind(); });
  7906. auto se = detail::scope_exit([&] {
  7907. svr.stop();
  7908. t.join();
  7909. ASSERT_FALSE(svr.is_running());
  7910. });
  7911. svr.wait_until_ready();
  7912. Client cli(HOST, port);
  7913. auto res = cli.Get("/cookies");
  7914. ASSERT_TRUE(res);
  7915. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7916. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7917. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7918. }
  7919. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7920. Server svr;
  7921. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7922. auto i = new int(0);
  7923. res.set_header("Trailer", "X-Safe, X-Reflected");
  7924. res.set_chunked_content_provider(
  7925. "text/plain",
  7926. [i](size_t /*offset*/, DataSink &sink) {
  7927. if (*i == 0) {
  7928. sink.os << "body";
  7929. } else {
  7930. Headers trailer;
  7931. // A valid trailer that must survive.
  7932. trailer.emplace("X-Safe", "safe");
  7933. // Attacker-controlled value carrying CR/LF (response splitting).
  7934. trailer.emplace("X-Reflected",
  7935. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7936. // Attacker-controlled name carrying CR/LF.
  7937. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7938. sink.done_with_trailer(trailer);
  7939. }
  7940. (*i)++;
  7941. return true;
  7942. },
  7943. [i](bool /*success*/) { delete i; });
  7944. });
  7945. thread t = thread([&] { svr.listen(HOST, PORT); });
  7946. auto se = detail::scope_exit([&] {
  7947. svr.stop();
  7948. t.join();
  7949. ASSERT_FALSE(svr.is_running());
  7950. });
  7951. svr.wait_until_ready();
  7952. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7953. "Host: " + HOST +
  7954. "\r\n"
  7955. "Connection: close\r\n"
  7956. "\r\n";
  7957. std::string res;
  7958. ASSERT_TRUE(send_request(5, req, &res));
  7959. // The injected fields must not appear anywhere in the raw response.
  7960. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7961. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7962. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7963. // Invalid trailers are dropped entirely, matching set_header().
  7964. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7965. // The valid trailer still passes through.
  7966. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7967. }
  7968. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7969. Server svr;
  7970. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7971. // res.headers is a public field an application can populate directly,
  7972. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7973. // A valid header that must survive.
  7974. res.headers.emplace("X-Safe", "safe");
  7975. // Attacker-controlled value carrying CR/LF (response splitting).
  7976. res.headers.emplace("X-Reflected",
  7977. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7978. // Attacker-controlled name carrying CR/LF.
  7979. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7980. res.set_content("body", "text/plain");
  7981. });
  7982. thread t = thread([&] { svr.listen(HOST, PORT); });
  7983. auto se = detail::scope_exit([&] {
  7984. svr.stop();
  7985. t.join();
  7986. ASSERT_FALSE(svr.is_running());
  7987. });
  7988. svr.wait_until_ready();
  7989. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7990. "Host: " + HOST +
  7991. "\r\n"
  7992. "Connection: close\r\n"
  7993. "\r\n";
  7994. std::string res;
  7995. ASSERT_TRUE(send_request(5, req, &res));
  7996. // The injected fields must not appear anywhere in the raw response.
  7997. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7998. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7999. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8000. // Invalid headers are dropped entirely, matching set_header().
  8001. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8002. // The valid header still passes through.
  8003. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8004. }
  8005. // Forward declaration: in split builds split.py strips `inline` and moves the
  8006. // definition into httplib.cc, so detail::write_request_line is not visible from
  8007. // the public httplib.h. Re-declaring it here lets the tests link against the
  8008. // symbol in both header-only and split builds.
  8009. namespace httplib {
  8010. namespace detail {
  8011. ssize_t write_request_line(Stream &strm, const std::string &method,
  8012. const std::string &path);
  8013. } // namespace detail
  8014. } // namespace httplib
  8015. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8016. // A well-formed target is written verbatim.
  8017. {
  8018. detail::BufferStream strm;
  8019. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8020. EXPECT_GT(n, 0);
  8021. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8022. }
  8023. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8024. // otherwise it splits the request line and injects a header or a whole
  8025. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8026. // when path encoding is disabled.
  8027. const std::string evil_targets[] = {
  8028. "/a\r\nInjected: pwned",
  8029. "/a\rInjected",
  8030. "/a\nInjected",
  8031. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8032. };
  8033. for (const auto &evil : evil_targets) {
  8034. detail::BufferStream strm;
  8035. auto n = detail::write_request_line(strm, "GET", evil);
  8036. EXPECT_LT(n, 0);
  8037. EXPECT_TRUE(strm.get_buffer().empty());
  8038. }
  8039. }
  8040. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8041. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8042. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8043. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8044. // client must fail cleanly with Error::Write instead of putting a
  8045. // request-line-less, header-injecting request on the wire.
  8046. Server svr;
  8047. svr.Get("/a", [](const Request &, Response &res) {
  8048. res.set_content("ok", "text/plain");
  8049. });
  8050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8051. auto se = detail::scope_exit([&] {
  8052. svr.stop();
  8053. thread.join();
  8054. ASSERT_FALSE(svr.is_running());
  8055. });
  8056. svr.wait_until_ready();
  8057. {
  8058. Client cli(HOST, PORT);
  8059. cli.set_path_encode(false);
  8060. // The request is rejected before anything is written, so the connection
  8061. // stays silent and the subsequent response read would otherwise block for
  8062. // the full default read timeout. Shorten it -- the assertion is on the
  8063. // error, not the timeout.
  8064. cli.set_read_timeout(1, 0);
  8065. auto res = cli.Get("/a\r\nInjected: pwned");
  8066. EXPECT_FALSE(res);
  8067. EXPECT_EQ(Error::Write, res.error());
  8068. }
  8069. }
  8070. // Sends a raw request and verifies that there isn't a crash or exception.
  8071. static void test_raw_request(const std::string &req,
  8072. std::string *out = nullptr) {
  8073. Server svr;
  8074. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8075. res.set_content("ok", "text/plain");
  8076. });
  8077. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8078. res.set_content("ok", "text/plain");
  8079. });
  8080. svr.Get("/header_field_value_check",
  8081. [&](const Request & /*req*/, Response &res) {
  8082. res.set_content("ok", "text/plain");
  8083. });
  8084. svr.CustomRoute("PROPFIND", "/dav",
  8085. [&](const Request & /*req*/, Response &res) {
  8086. res.status = StatusCode::MultiStatus_207;
  8087. });
  8088. // Server read timeout must be longer than the client read timeout for the
  8089. // bug to reproduce, probably to force the server to process a request
  8090. // without a trailing blank line.
  8091. const time_t client_read_timeout_sec = 1;
  8092. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8093. bool listen_thread_ok = false;
  8094. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8095. auto se = detail::scope_exit([&] {
  8096. svr.stop();
  8097. t.join();
  8098. ASSERT_FALSE(svr.is_running());
  8099. EXPECT_TRUE(listen_thread_ok);
  8100. });
  8101. svr.wait_until_ready();
  8102. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8103. }
  8104. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8105. // A certain header line causes an exception if the header property is parsed
  8106. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8107. test_raw_request(
  8108. "GET /hi HTTP/1.1\r\n"
  8109. " : "
  8110. " "
  8111. " ");
  8112. }
  8113. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8114. // A certain header line causes an exception if the header property *name* is
  8115. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8116. // greedy matcher and requires backtracking when there are a lot of ":"
  8117. // characters.
  8118. // This occurs with libc++ but not libstdc++.
  8119. test_raw_request(
  8120. "GET /hi HTTP/1.1\r\n"
  8121. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8122. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8123. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8124. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8125. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8126. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8127. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8128. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8129. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8130. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8131. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8132. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8133. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8134. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8135. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8136. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8137. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8138. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8139. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8140. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8141. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8142. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8143. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8144. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8145. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8146. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8147. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8148. "&&&%%%");
  8149. }
  8150. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8151. // Make sure this doesn't crash the server.
  8152. // In a previous version of the header line regex, the "\r" rendered the line
  8153. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8154. // a new position where the leading white space ended and the field value
  8155. // began.
  8156. // The crash occurs with libc++ but not libstdc++.
  8157. test_raw_request("GET /hi HTTP/1.1\r\n"
  8158. "a:" +
  8159. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8160. "\r\n"
  8161. "\r\n");
  8162. }
  8163. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8164. std::string out;
  8165. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8166. "Content-Type: text/plain\r\n"
  8167. "Transfer-Encoding: chunked\r\n"
  8168. "\r\n"
  8169. "nothex\r\n",
  8170. &out);
  8171. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8172. }
  8173. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8174. std::string out;
  8175. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8176. "Content-Type: text/plain\r\n"
  8177. "Transfer-Encoding: chunked\r\n"
  8178. "\r\n"
  8179. "3\r\n"
  8180. "xyz\r\n"
  8181. "NaN\r\n",
  8182. &out);
  8183. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8184. }
  8185. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8186. std::string out;
  8187. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8188. "Content-Type: text/plain\r\n"
  8189. "Transfer-Encoding: chunked\r\n"
  8190. "\r\n"
  8191. // Length is too large for 64 bits.
  8192. "1ffffffffffffffff\r\n"
  8193. "xyz\r\n",
  8194. &out);
  8195. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8196. }
  8197. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8198. test_raw_request("GET /hi HTTP/1.1\r\n"
  8199. "Content-Type: text/plain\r\n\r");
  8200. }
  8201. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8202. std::string out;
  8203. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8204. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8205. }
  8206. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8207. Server svr;
  8208. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8209. EXPECT_TRUE(!req.remote_addr.empty());
  8210. });
  8211. thread t = thread([&] { svr.listen(HOST, PORT); });
  8212. auto se = detail::scope_exit([&] {
  8213. svr.stop();
  8214. t.join();
  8215. ASSERT_FALSE(svr.is_running());
  8216. });
  8217. svr.wait_until_ready();
  8218. // Send an invalid request line to trigger Bad Request
  8219. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8220. std::string out;
  8221. ASSERT_TRUE(send_request(5, bad_req, &out));
  8222. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8223. }
  8224. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8225. // answered right away rather than blocking on a read that waits for EOF.
  8226. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8227. std::string out;
  8228. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8229. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8230. }
  8231. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8232. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8233. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8234. for (const auto *method : methods) {
  8235. Server svr;
  8236. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8237. EXPECT_FALSE(svr.is_valid()) << method;
  8238. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8239. }
  8240. }
  8241. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8242. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8243. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8244. for (const auto *method : methods) {
  8245. Server svr;
  8246. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8247. EXPECT_FALSE(svr.is_valid()) << method;
  8248. }
  8249. }
  8250. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8251. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8252. "COPY", "MOVE", "LOCK",
  8253. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8254. Server svr;
  8255. for (const auto *method : methods) {
  8256. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8257. }
  8258. EXPECT_TRUE(svr.is_valid());
  8259. }
  8260. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8261. Server svr;
  8262. svr.CustomRoute("POST", "/x",
  8263. [](const Request &, Response &, const ContentReader &) {});
  8264. EXPECT_FALSE(svr.is_valid());
  8265. }
  8266. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8267. Server svr;
  8268. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8269. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8270. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8271. EXPECT_FALSE(svr.is_valid());
  8272. }
  8273. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8274. Server svr;
  8275. auto captured = Error::Success;
  8276. svr.set_error_logger(
  8277. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8278. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8279. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8280. }
  8281. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8282. std::string out;
  8283. std::string request(
  8284. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8285. test_raw_request(request, &out);
  8286. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8287. }
  8288. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8289. std::string out;
  8290. std::string request(
  8291. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8292. test_raw_request(request, &out);
  8293. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8294. }
  8295. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8296. std::string out;
  8297. std::string request(
  8298. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8299. test_raw_request(request, &out);
  8300. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8301. }
  8302. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8303. std::string out;
  8304. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8305. "Test: \r\n\r\n",
  8306. &out);
  8307. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8308. }
  8309. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8310. Server svr;
  8311. std::string x_custom;
  8312. std::string cookie;
  8313. std::string xff;
  8314. std::string x_unicode;
  8315. std::string x_iis;
  8316. svr.Get("/check", [&](const Request &req, Response &res) {
  8317. x_custom = req.get_header_value("X-Custom");
  8318. cookie = req.get_header_value("Cookie");
  8319. xff = req.get_header_value("X-Forwarded-For");
  8320. x_unicode = req.get_header_value("X-Unicode");
  8321. x_iis = req.get_header_value("X-IIS");
  8322. res.set_content("ok", "text/plain");
  8323. });
  8324. thread t = thread([&] { svr.listen(HOST, PORT); });
  8325. auto se = detail::scope_exit([&] {
  8326. svr.stop();
  8327. t.join();
  8328. ASSERT_FALSE(svr.is_running());
  8329. });
  8330. svr.wait_until_ready();
  8331. const std::string req = "GET /check HTTP/1.1\r\n"
  8332. "Host: localhost\r\n"
  8333. "X-Custom: a%0D%0AInjected: b\r\n"
  8334. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8335. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8336. "X-Unicode: %E3%81%82\r\n"
  8337. "X-IIS: %u00E9\r\n"
  8338. "Connection: close\r\n"
  8339. "\r\n";
  8340. std::string res;
  8341. ASSERT_TRUE(send_request(5, req, &res));
  8342. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8343. // Every value must be returned verbatim (wire form), with no decoding.
  8344. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8345. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8346. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8347. EXPECT_EQ("%E3%81%82", x_unicode);
  8348. EXPECT_EQ("%u00E9", x_iis);
  8349. }
  8350. // Applications that previously relied on automatic percent-decoding can
  8351. // reproduce the old behavior by explicitly calling decode_path_component()
  8352. // or, for RFC 3986 conformance, decode_uri_component().
  8353. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8354. Server svr;
  8355. std::string decoded;
  8356. svr.Get("/check", [&](const Request &req, Response &res) {
  8357. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8358. res.set_content("ok", "text/plain");
  8359. });
  8360. thread t = thread([&] { svr.listen(HOST, PORT); });
  8361. auto se = detail::scope_exit([&] {
  8362. svr.stop();
  8363. t.join();
  8364. ASSERT_FALSE(svr.is_running());
  8365. });
  8366. svr.wait_until_ready();
  8367. const std::string req = "GET /check HTTP/1.1\r\n"
  8368. "Host: localhost\r\n"
  8369. "X-Custom: hello%20world\r\n"
  8370. "Connection: close\r\n"
  8371. "\r\n";
  8372. std::string res;
  8373. ASSERT_TRUE(send_request(5, req, &res));
  8374. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8375. EXPECT_EQ("hello world", decoded);
  8376. }
  8377. // Regression test for #2033. Browsers send Referer values that include
  8378. // percent-encoded characters such as %0A inside the URL. Decoding the
  8379. // header value would either trip the post-decode CR/LF/NUL guard (the
  8380. // original bug, returning 400) or, after that guard was relaxed, silently
  8381. // store a literal LF — both unacceptable. The wire form must round-trip.
  8382. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8383. Server svr;
  8384. std::string referer;
  8385. svr.Get("/check", [&](const Request &req, Response &res) {
  8386. referer = req.get_header_value("Referer");
  8387. res.set_content("ok", "text/plain");
  8388. });
  8389. thread t = thread([&] { svr.listen(HOST, PORT); });
  8390. auto se = detail::scope_exit([&] {
  8391. svr.stop();
  8392. t.join();
  8393. ASSERT_FALSE(svr.is_running());
  8394. });
  8395. svr.wait_until_ready();
  8396. const std::string req = "GET /check HTTP/1.1\r\n"
  8397. "Host: localhost\r\n"
  8398. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8399. "Connection: close\r\n"
  8400. "\r\n";
  8401. std::string res;
  8402. ASSERT_TRUE(send_request(5, req, &res));
  8403. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8404. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8405. }
  8406. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8407. Server svr;
  8408. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8409. res.set_header("Cache-Control", "no-cache");
  8410. res.set_chunked_content_provider(
  8411. "text/event-stream", [](size_t offset, DataSink &sink) {
  8412. std::string s = "data:";
  8413. s += std::to_string(offset);
  8414. s += "\n\n";
  8415. auto ret = sink.write(s.data(), s.size());
  8416. EXPECT_TRUE(ret);
  8417. std::this_thread::sleep_for(std::chrono::seconds(1));
  8418. return true;
  8419. });
  8420. });
  8421. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8422. svr.wait_until_ready();
  8423. Client client(HOST, PORT);
  8424. const Headers headers = {{"Accept", "text/event-stream"}};
  8425. auto get_thread = std::thread([&client, &headers]() {
  8426. auto res = client.Get(
  8427. "/events", headers,
  8428. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8429. });
  8430. auto se = detail::scope_exit([&] {
  8431. svr.stop();
  8432. get_thread.join();
  8433. listen_thread.join();
  8434. ASSERT_FALSE(svr.is_running());
  8435. });
  8436. // Give GET time to get a few messages.
  8437. std::this_thread::sleep_for(std::chrono::seconds(2));
  8438. }
  8439. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8440. httplib::Server svr;
  8441. svr.Post("/hi",
  8442. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8443. res.status = StatusCode::OK_200;
  8444. });
  8445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8446. svr.wait_until_ready();
  8447. Client cli(HOST, PORT);
  8448. auto res = cli.Post("/hi", "data", "text/plain");
  8449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8450. EXPECT_EQ(StatusCode::OK_200, res->status);
  8451. svr.stop();
  8452. thread.join();
  8453. ASSERT_FALSE(svr.is_running());
  8454. res = cli.Post("/hi", "data", "text/plain");
  8455. ASSERT_FALSE(res);
  8456. }
  8457. TEST(ServerStopTest, ListenFailure) {
  8458. Server svr;
  8459. auto t = thread([&]() {
  8460. auto ret = svr.listen("????", PORT);
  8461. EXPECT_FALSE(ret);
  8462. });
  8463. svr.wait_until_ready();
  8464. svr.stop();
  8465. t.join();
  8466. }
  8467. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8468. TEST(ServerStopTest, Decommision) {
  8469. Server svr;
  8470. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8471. for (int i = 0; i < 4; i++) {
  8472. auto is_even = !(i % 2);
  8473. std::thread t{[&] {
  8474. try {
  8475. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8476. if (is_even) {
  8477. throw std::runtime_error("Some thing that happens to go wrong.");
  8478. }
  8479. svr.listen(HOST, PORT);
  8480. } catch (...) { svr.decommission(); }
  8481. }};
  8482. svr.wait_until_ready();
  8483. // Server is up
  8484. {
  8485. Client cli(HOST, PORT);
  8486. auto res = cli.Get("/hi");
  8487. if (is_even) {
  8488. EXPECT_FALSE(res);
  8489. } else {
  8490. EXPECT_TRUE(res);
  8491. EXPECT_EQ("hi...", res->body);
  8492. }
  8493. }
  8494. svr.stop();
  8495. t.join();
  8496. // Server is down...
  8497. {
  8498. Client cli(HOST, PORT);
  8499. auto res = cli.Get("/hi");
  8500. EXPECT_FALSE(res);
  8501. }
  8502. }
  8503. }
  8504. #endif
  8505. // Helper function for string body upload progress tests
  8506. template <typename SetupHandler, typename ClientCall>
  8507. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8508. ClientCall &&client_call,
  8509. const string &body) {
  8510. Server svr;
  8511. setup_handler(svr);
  8512. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8513. auto se = detail::scope_exit([&] {
  8514. svr.stop();
  8515. t.join();
  8516. });
  8517. svr.wait_until_ready();
  8518. Client cli(HOST, PORT);
  8519. vector<uint64_t> progress_values;
  8520. bool progress_called = false;
  8521. auto res =
  8522. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8523. progress_values.push_back(current);
  8524. progress_called = true;
  8525. return true;
  8526. });
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(200, res->status);
  8529. EXPECT_TRUE(progress_called);
  8530. }
  8531. TEST(UploadProgressTest, PostStringBodyBasic) {
  8532. TestStringBodyUploadProgress(
  8533. [](Server &svr) {
  8534. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8535. res.set_content("received", "text/plain");
  8536. });
  8537. },
  8538. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8539. return cli.Post("/test", body, "text/plain", progress_callback);
  8540. },
  8541. "test data for upload progress");
  8542. }
  8543. TEST(UploadProgressTest, PutStringBodyBasic) {
  8544. TestStringBodyUploadProgress(
  8545. [](Server &svr) {
  8546. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8547. res.set_content("put received", "text/plain");
  8548. });
  8549. },
  8550. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8551. return cli.Put("/test", body, "text/plain", progress_callback);
  8552. },
  8553. "put test data for upload progress");
  8554. }
  8555. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8556. TestStringBodyUploadProgress(
  8557. [](Server &svr) {
  8558. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8559. res.set_content("patch received", "text/plain");
  8560. });
  8561. },
  8562. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8563. return cli.Patch("/test", body, "text/plain", progress_callback);
  8564. },
  8565. "patch test data for upload progress");
  8566. }
  8567. // Helper function for content provider upload progress tests
  8568. template <typename SetupHandler, typename ClientCall>
  8569. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8570. ClientCall &&client_call) {
  8571. Server svr;
  8572. setup_handler(svr);
  8573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8574. auto se = detail::scope_exit([&] {
  8575. svr.stop();
  8576. t.join();
  8577. });
  8578. svr.wait_until_ready();
  8579. Client cli(HOST, PORT);
  8580. vector<uint64_t> progress_values;
  8581. auto res =
  8582. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8583. progress_values.push_back(current);
  8584. return true;
  8585. });
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ(200, res->status);
  8588. EXPECT_FALSE(progress_values.empty());
  8589. }
  8590. TEST(UploadProgressTest, PostContentProviderProgress) {
  8591. TestContentProviderUploadProgress(
  8592. [](Server &svr) {
  8593. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8594. res.set_content("provider received", "text/plain");
  8595. });
  8596. },
  8597. [](Client &cli, UploadProgress progress_callback) {
  8598. return cli.Post(
  8599. "/test", 10,
  8600. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8601. sink.os << "test data";
  8602. return true;
  8603. },
  8604. "text/plain", progress_callback);
  8605. });
  8606. }
  8607. // Helper function for multipart upload progress tests
  8608. template <typename SetupHandler, typename ClientCall>
  8609. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8610. ClientCall &&client_call,
  8611. const string &endpoint) {
  8612. Server svr;
  8613. setup_handler(svr);
  8614. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8615. auto se = detail::scope_exit([&] {
  8616. svr.stop();
  8617. t.join();
  8618. });
  8619. svr.wait_until_ready();
  8620. Client cli(HOST, PORT);
  8621. vector<uint64_t> progress_values;
  8622. UploadFormDataItems items = {
  8623. {"field1", "value1", "", ""},
  8624. {"field2", "longer value for progress tracking test", "", ""},
  8625. {"file1", "file content data for upload progress", "test.txt",
  8626. "text/plain"}};
  8627. auto res = client_call(cli, endpoint, items,
  8628. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8629. progress_values.push_back(current);
  8630. return true;
  8631. });
  8632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8633. EXPECT_EQ(200, res->status);
  8634. EXPECT_FALSE(progress_values.empty());
  8635. }
  8636. TEST(UploadProgressTest, PostMultipartProgress) {
  8637. TestMultipartUploadProgress(
  8638. [](Server &svr) {
  8639. svr.Post("/multipart", [](const Request &req, Response &res) {
  8640. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8641. res.set_content("multipart received", "text/plain");
  8642. });
  8643. },
  8644. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8645. UploadProgress progress_callback) {
  8646. return cli.Post(endpoint, items, progress_callback);
  8647. },
  8648. "/multipart");
  8649. }
  8650. // Helper function for basic download progress tests
  8651. template <typename SetupHandler, typename ClientCall>
  8652. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8653. ClientCall &&client_call, const string &endpoint,
  8654. size_t expected_content_size) {
  8655. Server svr;
  8656. setup_handler(svr);
  8657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8658. auto se = detail::scope_exit([&] {
  8659. svr.stop();
  8660. t.join();
  8661. });
  8662. svr.wait_until_ready();
  8663. Client cli(HOST, PORT);
  8664. vector<uint64_t> progress_values;
  8665. auto res = client_call(cli, endpoint,
  8666. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8667. progress_values.push_back(current);
  8668. return true;
  8669. });
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ(200, res->status);
  8672. EXPECT_FALSE(progress_values.empty());
  8673. EXPECT_EQ(expected_content_size, res->body.size());
  8674. }
  8675. TEST(DownloadProgressTest, GetBasic) {
  8676. TestBasicDownloadProgress(
  8677. [](Server &svr) {
  8678. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8679. string content(1000, 'D');
  8680. res.set_content(content, "text/plain");
  8681. });
  8682. },
  8683. [](Client &cli, const string &endpoint,
  8684. DownloadProgress progress_callback) {
  8685. return cli.Get(endpoint, progress_callback);
  8686. },
  8687. "/download", 1000u);
  8688. }
  8689. // Helper function for content receiver download progress tests
  8690. template <typename SetupHandler, typename ClientCall>
  8691. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8692. ClientCall &&client_call,
  8693. const string &endpoint,
  8694. size_t expected_content_size) {
  8695. Server svr;
  8696. setup_handler(svr);
  8697. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8698. auto se = detail::scope_exit([&] {
  8699. svr.stop();
  8700. t.join();
  8701. });
  8702. svr.wait_until_ready();
  8703. Client cli(HOST, PORT);
  8704. vector<uint64_t> progress_values;
  8705. string received_body;
  8706. auto res = client_call(
  8707. cli, endpoint,
  8708. [&](const char *data, size_t data_length) -> bool {
  8709. received_body.append(data, data_length);
  8710. return true;
  8711. },
  8712. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8713. progress_values.push_back(current);
  8714. return true;
  8715. });
  8716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8717. EXPECT_EQ(200, res->status);
  8718. EXPECT_FALSE(progress_values.empty());
  8719. EXPECT_EQ(expected_content_size, received_body.size());
  8720. EXPECT_TRUE(res->body.empty());
  8721. }
  8722. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8723. TestContentReceiverDownloadProgress(
  8724. [](Server &svr) {
  8725. svr.Get("/download-receiver",
  8726. [](const Request & /*req*/, Response &res) {
  8727. string content(2000, 'R');
  8728. res.set_content(content, "text/plain");
  8729. });
  8730. },
  8731. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8732. DownloadProgress progress_callback) {
  8733. return cli.Get(endpoint, content_receiver, progress_callback);
  8734. },
  8735. "/download-receiver", 2000u);
  8736. }
  8737. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  8738. // A provider reaching a pass with nothing to hand over - an empty buffer
  8739. // popped off a queue, say - must not be taken to mean the body is finished.
  8740. // It used to end the loop with the terminating chunk unwritten while the
  8741. // server still considered the response complete, so the peer waited for an
  8742. // end that never arrived.
  8743. Server svr;
  8744. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8745. auto step = std::make_shared<int>(0);
  8746. res.set_chunked_content_provider("text/plain",
  8747. [step](size_t /*offset*/, DataSink &sink) {
  8748. switch ((*step)++) {
  8749. case 0: sink.write("", 0); break;
  8750. case 1: sink.write("hello", 5); break;
  8751. default: sink.done(); break;
  8752. }
  8753. return true;
  8754. });
  8755. });
  8756. auto port = svr.bind_to_any_port(HOST);
  8757. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8758. auto listen_se = detail::scope_exit([&] {
  8759. svr.stop();
  8760. listen_thread.join();
  8761. ASSERT_FALSE(svr.is_running());
  8762. });
  8763. svr.wait_until_ready();
  8764. Client cli(HOST, port);
  8765. // Without the fix the body is never terminated, so bound the wait rather
  8766. // than letting the test hang on the default read timeout.
  8767. cli.set_read_timeout(5, 0);
  8768. auto res = cli.Get("/stream");
  8769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8770. EXPECT_EQ(StatusCode::OK_200, res->status);
  8771. EXPECT_EQ("hello", res->body);
  8772. }
  8773. TEST(StreamingTest, NoContentLengthStreaming) {
  8774. Server svr;
  8775. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8776. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8777. if (offset < 6) {
  8778. sink.os << (offset < 3 ? "a" : "b");
  8779. } else {
  8780. sink.done();
  8781. }
  8782. return true;
  8783. });
  8784. });
  8785. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8786. auto listen_se = detail::scope_exit([&] {
  8787. svr.stop();
  8788. listen_thread.join();
  8789. ASSERT_FALSE(svr.is_running());
  8790. });
  8791. svr.wait_until_ready();
  8792. Client client(HOST, PORT);
  8793. auto get_thread = std::thread([&client]() {
  8794. std::string s;
  8795. auto res =
  8796. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8797. s += std::string(data, len);
  8798. return true;
  8799. });
  8800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8801. EXPECT_EQ(StatusCode::OK_200, res->status);
  8802. EXPECT_EQ("aaabbb", s);
  8803. });
  8804. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8805. // Give GET time to get a few messages.
  8806. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8807. }
  8808. TEST(MountTest, Unmount) {
  8809. Server svr;
  8810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8811. auto se = detail::scope_exit([&] {
  8812. svr.stop();
  8813. listen_thread.join();
  8814. ASSERT_FALSE(svr.is_running());
  8815. });
  8816. svr.wait_until_ready();
  8817. Client cli("localhost", PORT);
  8818. svr.set_mount_point("/mount2", "./www2");
  8819. auto res = cli.Get("/");
  8820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8822. res = cli.Get("/mount2/dir/test.html");
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ(StatusCode::OK_200, res->status);
  8825. svr.set_mount_point("/", "./www");
  8826. res = cli.Get("/dir/");
  8827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8828. EXPECT_EQ(StatusCode::OK_200, res->status);
  8829. svr.remove_mount_point("/");
  8830. res = cli.Get("/dir/");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8833. svr.remove_mount_point("/mount2");
  8834. res = cli.Get("/mount2/dir/test.html");
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8837. }
  8838. TEST(MountTest, PathSegmentBoundary) {
  8839. Server svr;
  8840. svr.set_mount_point("/mount2", "./www2");
  8841. svr.set_mount_point("/", "./www");
  8842. auto port = svr.bind_to_any_port(HOST);
  8843. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8844. auto se = detail::scope_exit([&] {
  8845. svr.stop();
  8846. listen_thread.join();
  8847. ASSERT_FALSE(svr.is_running());
  8848. });
  8849. svr.wait_until_ready();
  8850. Client cli(HOST, port);
  8851. auto res = cli.Get("/mount2/dir/test.html");
  8852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8853. EXPECT_EQ(StatusCode::OK_200, res->status);
  8854. // "/mount2" must not match part-way through a path segment.
  8855. res = cli.Get("/mount2dir/test.html");
  8856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8857. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8858. // A mount point ending in '/' keeps matching every path below it.
  8859. res = cli.Get("/dir/test.html");
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. }
  8863. TEST(MountTest, Redicect) {
  8864. Server svr;
  8865. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8866. auto se = detail::scope_exit([&] {
  8867. svr.stop();
  8868. listen_thread.join();
  8869. ASSERT_FALSE(svr.is_running());
  8870. });
  8871. svr.set_mount_point("/", "./www");
  8872. svr.wait_until_ready();
  8873. Client cli("localhost", PORT);
  8874. auto res = cli.Get("/dir/");
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. res = cli.Get("/dir");
  8878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8879. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8880. res = cli.Get("/file");
  8881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. res = cli.Get("/file/");
  8884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8885. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8886. cli.set_follow_location(true);
  8887. res = cli.Get("/dir");
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_EQ(StatusCode::OK_200, res->status);
  8890. }
  8891. TEST(MountTest, MultibytesPathName) {
  8892. Server svr;
  8893. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8894. auto se = detail::scope_exit([&] {
  8895. svr.stop();
  8896. listen_thread.join();
  8897. ASSERT_FALSE(svr.is_running());
  8898. });
  8899. svr.set_mount_point("/", "./www");
  8900. svr.wait_until_ready();
  8901. Client cli("localhost", PORT);
  8902. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8904. EXPECT_EQ(StatusCode::OK_200, res->status);
  8905. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8906. }
  8907. #ifdef _WIN32
  8908. // Issue #2435: mmap::open() must succeed even when another handle holds
  8909. // the file open for writing (e.g. an active log file).
  8910. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8911. const char *path = "mmap_concurrent_writer_test.txt";
  8912. const char *content = "hello";
  8913. {
  8914. std::ofstream f(path, std::ios::binary);
  8915. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8916. }
  8917. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8918. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8919. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8920. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8921. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8922. detail::mmap m(path);
  8923. ASSERT_TRUE(m.is_open());
  8924. EXPECT_EQ(strlen(content), m.size());
  8925. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8926. }
  8927. #endif
  8928. #ifndef _WIN32
  8929. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8930. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8931. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8932. TEST(MmapTest, FailedMappingIsNotOpen) {
  8933. const char *path = "./mmap_failed_mapping_test_dir";
  8934. ASSERT_EQ(0, ::mkdir(path, 0755));
  8935. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8936. detail::mmap m(path);
  8937. EXPECT_FALSE(m.is_open());
  8938. EXPECT_EQ(0U, m.size());
  8939. EXPECT_NE(static_cast<const void *>(m.data()),
  8940. static_cast<const void *>(MAP_FAILED));
  8941. }
  8942. #endif
  8943. TEST(KeepAliveTest, ReadTimeout) {
  8944. Server svr;
  8945. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8946. std::this_thread::sleep_for(std::chrono::seconds(2));
  8947. res.set_content("a", "text/plain");
  8948. });
  8949. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8950. res.set_content("b", "text/plain");
  8951. });
  8952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8953. auto se = detail::scope_exit([&] {
  8954. svr.stop();
  8955. listen_thread.join();
  8956. ASSERT_FALSE(svr.is_running());
  8957. });
  8958. svr.wait_until_ready();
  8959. Client cli("localhost", PORT);
  8960. cli.set_keep_alive(true);
  8961. cli.set_read_timeout(std::chrono::seconds(1));
  8962. auto resa = cli.Get("/a");
  8963. ASSERT_FALSE(resa);
  8964. EXPECT_EQ(Error::Read, resa.error());
  8965. auto resb = cli.Get("/b");
  8966. ASSERT_TRUE(resb);
  8967. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8968. EXPECT_EQ("b", resb->body);
  8969. }
  8970. TEST(KeepAliveTest, MaxCount) {
  8971. size_t keep_alive_max_count = 3;
  8972. Server svr;
  8973. svr.set_keep_alive_max_count(keep_alive_max_count);
  8974. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8975. res.set_content("Hello World!", "text/plain");
  8976. });
  8977. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8978. auto se = detail::scope_exit([&] {
  8979. svr.stop();
  8980. listen_thread.join();
  8981. ASSERT_FALSE(svr.is_running());
  8982. });
  8983. svr.wait_until_ready();
  8984. Client cli(HOST, PORT);
  8985. cli.set_keep_alive(true);
  8986. for (size_t i = 0; i < 5; i++) {
  8987. auto result = cli.Get("/hi");
  8988. ASSERT_TRUE(result);
  8989. EXPECT_EQ(StatusCode::OK_200, result->status);
  8990. if (i == keep_alive_max_count - 1) {
  8991. EXPECT_EQ("close", result->get_header_value("Connection"));
  8992. } else {
  8993. EXPECT_FALSE(result->has_header("Connection"));
  8994. }
  8995. }
  8996. }
  8997. TEST(KeepAliveTest, Issue1041) {
  8998. Server svr;
  8999. svr.set_keep_alive_timeout(3);
  9000. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9001. res.set_content("Hello World!", "text/plain");
  9002. });
  9003. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9004. auto se = detail::scope_exit([&] {
  9005. svr.stop();
  9006. listen_thread.join();
  9007. ASSERT_FALSE(svr.is_running());
  9008. });
  9009. svr.wait_until_ready();
  9010. Client cli(HOST, PORT);
  9011. cli.set_keep_alive(true);
  9012. auto result = cli.Get("/hi");
  9013. ASSERT_TRUE(result);
  9014. EXPECT_EQ(StatusCode::OK_200, result->status);
  9015. std::this_thread::sleep_for(std::chrono::seconds(5));
  9016. result = cli.Get("/hi");
  9017. ASSERT_TRUE(result);
  9018. EXPECT_EQ(StatusCode::OK_200, result->status);
  9019. }
  9020. TEST(KeepAliveTest, Issue1959) {
  9021. Server svr;
  9022. svr.set_keep_alive_timeout(5);
  9023. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9024. res.set_content("a", "text/plain");
  9025. });
  9026. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. if (!svr.is_running()) return;
  9029. svr.stop();
  9030. listen_thread.join();
  9031. ASSERT_FALSE(svr.is_running());
  9032. });
  9033. svr.wait_until_ready();
  9034. Client cli("localhost", PORT);
  9035. cli.set_keep_alive(true);
  9036. using namespace std::chrono;
  9037. auto start = steady_clock::now();
  9038. cli.Get("/a");
  9039. svr.stop();
  9040. listen_thread.join();
  9041. auto end = steady_clock::now();
  9042. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9043. EXPECT_LT(elapsed, 5000);
  9044. }
  9045. #ifdef CPPHTTPLIB_SSL_ENABLED
  9046. TEST(KeepAliveTest, SSLClientReconnection) {
  9047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9048. ASSERT_TRUE(svr.is_valid());
  9049. svr.set_keep_alive_timeout(1);
  9050. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9051. res.set_content("Hello World!", "text/plain");
  9052. });
  9053. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9054. auto se = detail::scope_exit([&] {
  9055. svr.stop();
  9056. listen_thread.join();
  9057. ASSERT_FALSE(svr.is_running());
  9058. });
  9059. svr.wait_until_ready();
  9060. SSLClient cli(HOST, PORT);
  9061. cli.enable_server_certificate_verification(false);
  9062. cli.set_keep_alive(true);
  9063. auto result = cli.Get("/hi");
  9064. ASSERT_TRUE(result);
  9065. EXPECT_EQ(StatusCode::OK_200, result->status);
  9066. result = cli.Get("/hi");
  9067. ASSERT_TRUE(result);
  9068. EXPECT_EQ(StatusCode::OK_200, result->status);
  9069. std::this_thread::sleep_for(std::chrono::seconds(2));
  9070. // Recoonect
  9071. result = cli.Get("/hi");
  9072. ASSERT_TRUE(result);
  9073. EXPECT_EQ(StatusCode::OK_200, result->status);
  9074. result = cli.Get("/hi");
  9075. ASSERT_TRUE(result);
  9076. EXPECT_EQ(StatusCode::OK_200, result->status);
  9077. }
  9078. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9079. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9080. ASSERT_TRUE(svr.is_valid());
  9081. svr.set_keep_alive_timeout(1);
  9082. std::string content = "reconnect";
  9083. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9084. res.set_content("Hello World!", "text/plain");
  9085. });
  9086. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9087. auto se = detail::scope_exit([&] {
  9088. svr.stop();
  9089. listen_thread.join();
  9090. ASSERT_FALSE(svr.is_running());
  9091. });
  9092. svr.wait_until_ready();
  9093. SSLClient cli(HOST, PORT);
  9094. cli.enable_server_certificate_verification(false);
  9095. cli.set_keep_alive(true);
  9096. auto result = cli.Post(
  9097. "/hi", content.size(),
  9098. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9099. sink.write(content.c_str(), content.size());
  9100. return true;
  9101. },
  9102. "text/plain");
  9103. ASSERT_TRUE(result);
  9104. EXPECT_EQ(200, result->status);
  9105. std::this_thread::sleep_for(std::chrono::seconds(2));
  9106. // Recoonect
  9107. result = cli.Post(
  9108. "/hi", content.size(),
  9109. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9110. sink.write(content.c_str(), content.size());
  9111. return true;
  9112. },
  9113. "text/plain");
  9114. ASSERT_TRUE(result);
  9115. EXPECT_EQ(200, result->status);
  9116. result = cli.Post(
  9117. "/hi", content.size(),
  9118. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9119. sink.write(content.c_str(), content.size());
  9120. return true;
  9121. },
  9122. "text/plain");
  9123. ASSERT_TRUE(result);
  9124. EXPECT_EQ(200, result->status);
  9125. }
  9126. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9127. using namespace httplib::tls;
  9128. {
  9129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9130. ASSERT_TRUE(svr.is_valid());
  9131. svr.Get("/sni", [&](const Request &req, Response &res) {
  9132. std::string expected = req.sni();
  9133. EXPECT_EQ(expected, req.get_param_value("expected"));
  9134. res.set_content("ok", "text/plain");
  9135. });
  9136. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9137. auto se = detail::scope_exit([&] {
  9138. svr.stop();
  9139. listen_thread.join();
  9140. ASSERT_FALSE(svr.is_running());
  9141. });
  9142. svr.wait_until_ready();
  9143. {
  9144. SSLClient cli("localhost", PORT);
  9145. cli.enable_server_certificate_verification(false);
  9146. auto res = cli.Get("/sni?expected=localhost");
  9147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9148. }
  9149. {
  9150. SSLClient cli("::1", PORT);
  9151. cli.enable_server_certificate_verification(false);
  9152. auto res = cli.Get("/sni?expected=");
  9153. // NOTE: This may fail if the server is listening on IPv4 only
  9154. // (e.g., when localhost resolves to 127.0.0.1 only)
  9155. if (res) {
  9156. EXPECT_EQ(StatusCode::OK_200, res->status);
  9157. } else {
  9158. EXPECT_EQ(Error::Connection, res.error());
  9159. }
  9160. }
  9161. }
  9162. }
  9163. #endif
  9164. TEST(ClientProblemDetectionTest, ContentProvider) {
  9165. Server svr;
  9166. size_t content_length = 1024 * 1024;
  9167. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9168. res.set_content_provider(
  9169. content_length, "text/plain",
  9170. [&](size_t offset, size_t length, DataSink &sink) {
  9171. auto out_len = std::min(length, static_cast<size_t>(1024));
  9172. std::string out(out_len, '@');
  9173. sink.write(out.data(), out_len);
  9174. return offset < 4096;
  9175. },
  9176. [](bool success) { ASSERT_FALSE(success); });
  9177. });
  9178. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9179. res.set_content_provider(
  9180. 0, "text/plain",
  9181. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9182. EXPECT_TRUE(false);
  9183. return true;
  9184. },
  9185. [](bool success) { ASSERT_FALSE(success); });
  9186. });
  9187. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9188. auto se = detail::scope_exit([&] {
  9189. svr.stop();
  9190. listen_thread.join();
  9191. ASSERT_FALSE(svr.is_running());
  9192. });
  9193. svr.wait_until_ready();
  9194. Client cli("localhost", PORT);
  9195. {
  9196. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9197. size_t /*data_length*/) { return false; });
  9198. ASSERT_FALSE(res);
  9199. }
  9200. {
  9201. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9202. size_t /*data_length*/) { return false; });
  9203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9204. }
  9205. }
  9206. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9207. // A writer only has to assign `write`. The other three used to be left as
  9208. // empty std::functions, so a provider calling one threw
  9209. // std::bad_function_call out of the thread running it and took the whole
  9210. // process down.
  9211. DataSink sink;
  9212. std::string written;
  9213. sink.write = [&](const char *data, size_t data_len) {
  9214. written.append(data, data_len);
  9215. return true;
  9216. };
  9217. EXPECT_TRUE(sink.is_writable());
  9218. sink.done();
  9219. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9220. EXPECT_TRUE(written.empty());
  9221. }
  9222. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9223. // A sink that cannot carry trailers still has to finish.
  9224. DataSink sink;
  9225. auto done_count = 0;
  9226. sink.done = [&]() { done_count++; };
  9227. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9228. EXPECT_EQ(1, done_count);
  9229. }
  9230. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9231. Server svr;
  9232. const std::string body(4096, 'x');
  9233. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9234. res.set_content_provider(body.size(), "text/plain",
  9235. [&](size_t offset, size_t length, DataSink &sink) {
  9236. sink.write(body.data() + offset, length);
  9237. sink.done();
  9238. return true;
  9239. });
  9240. });
  9241. auto port = svr.bind_to_any_port(HOST);
  9242. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9243. auto se = detail::scope_exit([&] {
  9244. svr.stop();
  9245. listen_thread.join();
  9246. ASSERT_FALSE(svr.is_running());
  9247. });
  9248. svr.wait_until_ready();
  9249. Client cli(HOST, port);
  9250. auto res = cli.Get("/");
  9251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. EXPECT_EQ(body, res->body);
  9254. }
  9255. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9256. Server svr;
  9257. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9258. res.set_content_provider(
  9259. 1024, "text/plain",
  9260. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9261. sink.write("hello", 5);
  9262. sink.done(); // short of the 1024 bytes the response promised
  9263. return true;
  9264. });
  9265. });
  9266. auto port = svr.bind_to_any_port(HOST);
  9267. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. listen_thread.join();
  9271. ASSERT_FALSE(svr.is_running());
  9272. });
  9273. svr.wait_until_ready();
  9274. Client cli(HOST, port);
  9275. cli.set_read_timeout(5, 0);
  9276. // The response is short of its Content-Length, so the client cannot read a
  9277. // complete body. What matters is that this returns at all: a no-op done()
  9278. // would leave the writer looping over a provider that never makes progress.
  9279. auto res = cli.Get("/");
  9280. EXPECT_FALSE(res);
  9281. }
  9282. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9283. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9284. // The compressed path builds the whole body before connecting, so this
  9285. // fails client-side and never reaches a server.
  9286. Client cli(HOST, PORT);
  9287. cli.set_compress(true);
  9288. auto res = cli.Post(
  9289. "/", 1024,
  9290. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9291. sink.write("hello", 5);
  9292. sink.done(); // short of the 1024 bytes the request announced
  9293. return true;
  9294. },
  9295. "text/plain");
  9296. ASSERT_FALSE(res);
  9297. EXPECT_EQ(Error::Write, res.error());
  9298. }
  9299. #endif
  9300. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9301. Server svr;
  9302. svr.set_error_handler([](Request const &, Response &res) -> void {
  9303. res.set_chunked_content_provider(
  9304. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9305. sink.os << "hello";
  9306. sink.os << "world";
  9307. sink.done();
  9308. return true;
  9309. });
  9310. });
  9311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9312. auto se = detail::scope_exit([&] {
  9313. svr.stop();
  9314. listen_thread.join();
  9315. ASSERT_FALSE(svr.is_running());
  9316. });
  9317. svr.wait_until_ready();
  9318. Client cli("localhost", PORT);
  9319. auto res = cli.Get("/");
  9320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9322. EXPECT_EQ("helloworld", res->body);
  9323. }
  9324. TEST(LongPollingTest, ClientCloseDetection) {
  9325. Server svr;
  9326. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9327. res.set_chunked_content_provider(
  9328. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9329. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9330. sink.os << "hello";
  9331. auto count = 10;
  9332. while (count > 0 && sink.is_writable()) {
  9333. this_thread::sleep_for(chrono::milliseconds(10));
  9334. count--;
  9335. }
  9336. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9337. return true;
  9338. });
  9339. });
  9340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9341. auto se = detail::scope_exit([&] {
  9342. svr.stop();
  9343. listen_thread.join();
  9344. ASSERT_FALSE(svr.is_running());
  9345. });
  9346. svr.wait_until_ready();
  9347. Client cli("localhost", PORT);
  9348. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9349. EXPECT_EQ("hello", string(data, data_length));
  9350. return false; // close the socket immediately.
  9351. });
  9352. ASSERT_FALSE(res);
  9353. }
  9354. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9355. Server svr;
  9356. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9357. res.set_chunked_content_provider(
  9358. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9359. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9360. sink.os << "hello";
  9361. EXPECT_TRUE(sink.os.good());
  9362. // Wait for the client to close the connection
  9363. auto count = 10;
  9364. while (count > 0 && sink.is_writable()) {
  9365. this_thread::sleep_for(chrono::milliseconds(10));
  9366. count--;
  9367. }
  9368. // After client disconnect, write repeatedly until the socket
  9369. // write actually fails (small writes may be absorbed by the
  9370. // kernel buffer)
  9371. std::string chunk(1024, 'x');
  9372. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9373. sink.os << chunk;
  9374. }
  9375. EXPECT_TRUE(sink.os.fail());
  9376. return true;
  9377. });
  9378. });
  9379. auto port = svr.bind_to_any_port("localhost");
  9380. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. listen_thread.join();
  9384. ASSERT_FALSE(svr.is_running());
  9385. });
  9386. svr.wait_until_ready();
  9387. Client cli("localhost", port);
  9388. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9389. EXPECT_EQ("hello", string(data, data_length));
  9390. return false; // close the socket immediately.
  9391. });
  9392. ASSERT_FALSE(res);
  9393. }
  9394. TEST(GetWithParametersTest, GetWithParameters) {
  9395. Server svr;
  9396. svr.Get("/", [&](const Request &req, Response &) {
  9397. EXPECT_EQ("world", req.get_param_value("hello"));
  9398. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9399. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9400. });
  9401. svr.Get("/params", [&](const Request &req, Response &) {
  9402. EXPECT_EQ("world", req.get_param_value("hello"));
  9403. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9404. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9405. });
  9406. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9407. EXPECT_EQ("resource-id", req.matches[1]);
  9408. EXPECT_EQ("foo", req.get_param_value("param1"));
  9409. EXPECT_EQ("bar", req.get_param_value("param2"));
  9410. });
  9411. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9412. EXPECT_EQ("user-id", req.path_params.at("id"));
  9413. EXPECT_EQ("foo", req.get_param_value("param1"));
  9414. EXPECT_EQ("bar", req.get_param_value("param2"));
  9415. });
  9416. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9417. auto se = detail::scope_exit([&] {
  9418. svr.stop();
  9419. listen_thread.join();
  9420. ASSERT_FALSE(svr.is_running());
  9421. });
  9422. svr.wait_until_ready();
  9423. {
  9424. Client cli(HOST, PORT);
  9425. Params params;
  9426. params.emplace("hello", "world");
  9427. params.emplace("hello2", "world2");
  9428. params.emplace("hello3", "world3");
  9429. auto res = cli.Get("/", params, Headers{});
  9430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9431. EXPECT_EQ(StatusCode::OK_200, res->status);
  9432. }
  9433. {
  9434. Client cli(HOST, PORT);
  9435. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9437. EXPECT_EQ(StatusCode::OK_200, res->status);
  9438. }
  9439. {
  9440. Client cli(HOST, PORT);
  9441. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9443. EXPECT_EQ(StatusCode::OK_200, res->status);
  9444. }
  9445. {
  9446. Client cli(HOST, PORT);
  9447. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9449. EXPECT_EQ(StatusCode::OK_200, res->status);
  9450. }
  9451. }
  9452. TEST(GetWithParametersTest, GetWithParameters2) {
  9453. Server svr;
  9454. svr.Get("/", [&](const Request &req, Response &res) {
  9455. auto text = req.get_param_value("hello");
  9456. res.set_content(text, "text/plain");
  9457. });
  9458. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. listen_thread.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. Client cli("localhost", PORT);
  9466. Params params;
  9467. params.emplace("hello", "world");
  9468. std::string body;
  9469. auto res = cli.Get("/", params, Headers{},
  9470. [&](const char *data, size_t data_length) {
  9471. body.append(data, data_length);
  9472. return true;
  9473. });
  9474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9475. EXPECT_EQ(StatusCode::OK_200, res->status);
  9476. EXPECT_EQ("world", body);
  9477. }
  9478. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9479. Server svr;
  9480. svr.Get("/search", [&](const Request &req, Response &res) {
  9481. auto q = req.get_param_value("q");
  9482. res.set_content(q, "text/plain");
  9483. });
  9484. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9485. auto se = detail::scope_exit([&] {
  9486. svr.stop();
  9487. listen_thread.join();
  9488. ASSERT_FALSE(svr.is_running());
  9489. });
  9490. svr.wait_until_ready();
  9491. Client cli("localhost", PORT);
  9492. // Verify that Get(path, params) works without requiring Headers argument
  9493. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9495. EXPECT_EQ(StatusCode::OK_200, res->status);
  9496. EXPECT_EQ("cpp-httplib", res->body);
  9497. }
  9498. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9499. auto host = "httpbingo.org";
  9500. auto path = std::string{"/range/32"};
  9501. #ifdef CPPHTTPLIB_SSL_ENABLED
  9502. SSLClient cli(host);
  9503. #else
  9504. Client cli(host);
  9505. #endif
  9506. cli.set_default_headers({make_range_header({{1, 10}})});
  9507. cli.set_connection_timeout(5);
  9508. {
  9509. auto res = cli.Get(path);
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ("bcdefghijk", res->body);
  9512. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9513. }
  9514. {
  9515. auto res = cli.Get(path);
  9516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9517. EXPECT_EQ("bcdefghijk", res->body);
  9518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9519. }
  9520. }
  9521. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9522. Server svr;
  9523. svr.set_default_headers({{"Hello", "World"}});
  9524. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9525. res.set_content("ok", "text/plain");
  9526. });
  9527. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9528. auto se = detail::scope_exit([&] {
  9529. svr.stop();
  9530. listen_thread.join();
  9531. ASSERT_FALSE(svr.is_running());
  9532. });
  9533. svr.wait_until_ready();
  9534. Client cli("localhost", PORT);
  9535. auto res = cli.Get("/");
  9536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9537. EXPECT_EQ(StatusCode::OK_200, res->status);
  9538. EXPECT_EQ("ok", res->body);
  9539. EXPECT_EQ("World", res->get_header_value("Hello"));
  9540. }
  9541. #ifdef CPPHTTPLIB_SSL_ENABLED
  9542. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9544. ASSERT_TRUE(svr.is_valid());
  9545. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9546. std::this_thread::sleep_for(std::chrono::seconds(2));
  9547. res.set_content("a", "text/plain");
  9548. });
  9549. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9550. res.set_content("b", "text/plain");
  9551. });
  9552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. listen_thread.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. SSLClient cli("localhost", PORT);
  9560. cli.enable_server_certificate_verification(false);
  9561. cli.set_keep_alive(true);
  9562. cli.set_read_timeout(std::chrono::seconds(1));
  9563. auto resa = cli.Get("/a");
  9564. ASSERT_TRUE(!resa);
  9565. EXPECT_EQ(Error::Read, resa.error());
  9566. auto resb = cli.Get("/b");
  9567. ASSERT_TRUE(resb);
  9568. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9569. EXPECT_EQ("b", resb->body);
  9570. }
  9571. #endif
  9572. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9573. protected:
  9574. ServerTestWithAI_PASSIVE()
  9575. : cli_(HOST, PORT)
  9576. #ifdef CPPHTTPLIB_SSL_ENABLED
  9577. ,
  9578. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9579. #endif
  9580. {
  9581. #ifdef CPPHTTPLIB_SSL_ENABLED
  9582. cli_.enable_server_certificate_verification(false);
  9583. #endif
  9584. }
  9585. virtual void SetUp() {
  9586. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9587. res.set_content("Hello World!", "text/plain");
  9588. });
  9589. t_ = thread(
  9590. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9591. svr_.wait_until_ready();
  9592. }
  9593. virtual void TearDown() {
  9594. svr_.stop();
  9595. t_.join();
  9596. }
  9597. #ifdef CPPHTTPLIB_SSL_ENABLED
  9598. SSLClient cli_;
  9599. SSLServer svr_;
  9600. #else
  9601. Client cli_;
  9602. Server svr_;
  9603. #endif
  9604. thread t_;
  9605. };
  9606. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9607. auto res = cli_.Get("/hi");
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9611. EXPECT_EQ("Hello World!", res->body);
  9612. }
  9613. class ServerUpDownTest : public ::testing::Test {
  9614. protected:
  9615. ServerUpDownTest() : cli_(HOST, PORT) {}
  9616. virtual void SetUp() {
  9617. t_ = thread([&]() {
  9618. svr_.bind_to_any_port(HOST);
  9619. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9620. ASSERT_TRUE(svr_.listen_after_bind());
  9621. });
  9622. svr_.wait_until_ready();
  9623. }
  9624. virtual void TearDown() {
  9625. svr_.stop();
  9626. t_.join();
  9627. }
  9628. Client cli_;
  9629. Server svr_;
  9630. thread t_;
  9631. };
  9632. TEST_F(ServerUpDownTest, QuickStartStop) {
  9633. // Should not crash, especially when run with
  9634. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9635. }
  9636. class PayloadMaxLengthTest : public ::testing::Test {
  9637. protected:
  9638. PayloadMaxLengthTest()
  9639. : cli_(HOST, PORT)
  9640. #ifdef CPPHTTPLIB_SSL_ENABLED
  9641. ,
  9642. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9643. #endif
  9644. {
  9645. #ifdef CPPHTTPLIB_SSL_ENABLED
  9646. cli_.enable_server_certificate_verification(false);
  9647. #endif
  9648. }
  9649. virtual void SetUp() {
  9650. svr_.set_payload_max_length(8);
  9651. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9652. res.set_content("test", "text/plain");
  9653. });
  9654. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9655. svr_.wait_until_ready();
  9656. }
  9657. virtual void TearDown() {
  9658. svr_.stop();
  9659. t_.join();
  9660. }
  9661. #ifdef CPPHTTPLIB_SSL_ENABLED
  9662. SSLClient cli_;
  9663. SSLServer svr_;
  9664. #else
  9665. Client cli_;
  9666. Server svr_;
  9667. #endif
  9668. thread t_;
  9669. };
  9670. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9671. auto res = cli_.Post("/test", "123456789", "text/plain");
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9674. res = cli_.Post("/test", "12345678", "text/plain");
  9675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9676. EXPECT_EQ(StatusCode::OK_200, res->status);
  9677. }
  9678. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9679. // Test chunked encoding with payload exceeding the 8-byte limit
  9680. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9681. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9683. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9684. }
  9685. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9686. // Test chunked encoding with payload within the 8-byte limit
  9687. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9688. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9690. EXPECT_EQ(StatusCode::OK_200, res->status);
  9691. }
  9692. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9693. // Test using send_request to send chunked data exceeding payload limit
  9694. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9695. "Host: " +
  9696. std::string(HOST) + ":" + std::to_string(PORT) +
  9697. "\r\n"
  9698. "Transfer-Encoding: chunked\r\n"
  9699. "Connection: close\r\n"
  9700. "\r\n"
  9701. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9702. "0123456789\r\n"
  9703. "0\r\n" // End chunk
  9704. "\r\n";
  9705. std::string response;
  9706. bool result = send_request(1, chunked_request, &response);
  9707. if (!result) {
  9708. // If send_request fails, it might be because the server closed the
  9709. // connection due to payload limit enforcement, which is acceptable
  9710. SUCCEED()
  9711. << "Server rejected oversized chunked request (connection closed)";
  9712. } else {
  9713. // If we got a response, check if it's an error response or connection was
  9714. // closed early Short response length indicates connection was closed due to
  9715. // payload limit
  9716. if (response.length() <= 10) {
  9717. SUCCEED() << "Server closed connection for oversized chunked request";
  9718. } else {
  9719. // Check for error status codes
  9720. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9721. response.find("Payload Too Large") != std::string::npos ||
  9722. response.find("400") != std::string::npos);
  9723. }
  9724. }
  9725. }
  9726. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9727. // Test request without Content-Length header exceeding payload limit
  9728. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9729. "Host: " +
  9730. std::string(HOST) + ":" +
  9731. std::to_string(PORT) +
  9732. "\r\n"
  9733. "Connection: close\r\n"
  9734. "\r\n";
  9735. // Add payload exceeding the 8-byte limit
  9736. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9737. request_without_content_length += large_payload;
  9738. std::string response;
  9739. bool result = send_request(1, request_without_content_length, &response);
  9740. if (!result) {
  9741. // If send_request fails, server likely closed connection due to payload
  9742. // limit
  9743. SUCCEED() << "Server rejected oversized request without Content-Length "
  9744. "(connection closed)";
  9745. } else {
  9746. // Check if server responded with error or closed connection early
  9747. if (response.length() <= 10) {
  9748. SUCCEED() << "Server closed connection for oversized request without "
  9749. "Content-Length";
  9750. } else {
  9751. // Check for error status codes
  9752. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9753. response.find("Payload Too Large") != std::string::npos ||
  9754. response.find("400") != std::string::npos);
  9755. }
  9756. }
  9757. }
  9758. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9759. // Test request without Content-Length header within payload limit
  9760. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9761. "Host: " +
  9762. std::string(HOST) + ":" +
  9763. std::to_string(PORT) +
  9764. "\r\n"
  9765. "Connection: close\r\n"
  9766. "\r\n";
  9767. // Add payload within the 8-byte limit
  9768. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9769. request_without_content_length += small_payload;
  9770. std::string response;
  9771. bool result = send_request(1, request_without_content_length, &response);
  9772. // For requests without Content-Length, the server may have different behavior
  9773. // The key is that it should not reject due to payload limit for small
  9774. // payloads
  9775. if (result) {
  9776. // Check for any HTTP response (success or error, but not connection closed)
  9777. if (response.length() > 10) {
  9778. SUCCEED()
  9779. << "Server processed request without Content-Length within limit";
  9780. } else {
  9781. // Short response might indicate connection closed, which is acceptable
  9782. SUCCEED() << "Server closed connection for request without "
  9783. "Content-Length (acceptable behavior)";
  9784. }
  9785. } else {
  9786. // Connection failure might be due to protocol requirements
  9787. SUCCEED() << "Connection issue with request without Content-Length "
  9788. "(environment-specific)";
  9789. }
  9790. }
  9791. class LargePayloadMaxLengthTest : public ::testing::Test {
  9792. protected:
  9793. LargePayloadMaxLengthTest()
  9794. : cli_(HOST, PORT)
  9795. #ifdef CPPHTTPLIB_SSL_ENABLED
  9796. ,
  9797. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9798. #endif
  9799. {
  9800. #ifdef CPPHTTPLIB_SSL_ENABLED
  9801. cli_.enable_server_certificate_verification(false);
  9802. #endif
  9803. }
  9804. virtual void SetUp() {
  9805. // Set 10MB payload limit
  9806. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9807. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9808. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9809. res.set_content("Large payload test", "text/plain");
  9810. });
  9811. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9812. svr_.wait_until_ready();
  9813. }
  9814. virtual void TearDown() {
  9815. svr_.stop();
  9816. t_.join();
  9817. }
  9818. #ifdef CPPHTTPLIB_SSL_ENABLED
  9819. SSLClient cli_;
  9820. SSLServer svr_;
  9821. #else
  9822. Client cli_;
  9823. Server svr_;
  9824. #endif
  9825. thread t_;
  9826. };
  9827. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9828. // Test chunked encoding with payload within 10MB limit
  9829. std::string medium_payload(5 * 1024 * 1024,
  9830. 'A'); // 5MB payload, within 10MB limit
  9831. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. }
  9835. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9836. // Test chunked encoding with payload exceeding 10MB limit
  9837. std::string large_payload(12 * 1024 * 1024,
  9838. 'B'); // 12MB payload, exceeds 10MB limit
  9839. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9840. // Server may either return 413 or close the connection
  9841. if (res) {
  9842. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9843. } else {
  9844. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9845. }
  9846. }
  9847. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9848. // Test request without Content-Length header within 10MB limit
  9849. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9850. "Host: " +
  9851. std::string(HOST) + ":" +
  9852. std::to_string(PORT) +
  9853. "\r\n"
  9854. "Connection: close\r\n"
  9855. "\r\n";
  9856. // Add 1MB payload (within 10MB limit)
  9857. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9858. request_without_content_length += medium_payload;
  9859. std::string response;
  9860. bool result = send_request(5, request_without_content_length, &response);
  9861. if (result) {
  9862. // Should get a proper HTTP response for payloads within limit
  9863. if (response.length() > 10) {
  9864. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9865. "10MB limit";
  9866. } else {
  9867. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9868. "Content-Length)";
  9869. }
  9870. } else {
  9871. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9872. }
  9873. }
  9874. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9875. // Test request without Content-Length header exceeding 10MB limit
  9876. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9877. "Host: " +
  9878. std::string(HOST) + ":" +
  9879. std::to_string(PORT) +
  9880. "\r\n"
  9881. "Connection: close\r\n"
  9882. "\r\n";
  9883. // Add 12MB payload (exceeds 10MB limit)
  9884. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9885. request_without_content_length += large_payload;
  9886. std::string response;
  9887. bool result = send_request(10, request_without_content_length, &response);
  9888. if (!result) {
  9889. // Server should close connection due to payload limit
  9890. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9891. "(connection closed)";
  9892. } else {
  9893. // Check for error response
  9894. if (response.length() <= 10) {
  9895. SUCCEED()
  9896. << "Server closed connection for 12MB request exceeding 10MB limit";
  9897. } else {
  9898. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9899. response.find("Payload Too Large") != std::string::npos ||
  9900. response.find("400") != std::string::npos);
  9901. }
  9902. }
  9903. }
  9904. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9905. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9906. // path.
  9907. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9908. Server svr;
  9909. const size_t LIMIT = 64 * 1024; // 64KB
  9910. svr.set_payload_max_length(LIMIT);
  9911. size_t total = 0;
  9912. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9913. const ContentReader &content_reader) {
  9914. content_reader([&](const char * /*data*/, size_t len) {
  9915. total += len;
  9916. return true;
  9917. });
  9918. res.status = 200;
  9919. res.set_content("stream_ok", "text/plain");
  9920. });
  9921. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9922. auto se = detail::scope_exit([&] {
  9923. svr.stop();
  9924. thread.join();
  9925. ASSERT_FALSE(svr.is_running());
  9926. });
  9927. svr.wait_until_ready();
  9928. // Prepare 256KB raw data and gzip-compress it
  9929. std::string raw(256 * 1024, 'A');
  9930. std::string gz;
  9931. {
  9932. z_stream zs{};
  9933. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9934. Z_DEFAULT_STRATEGY);
  9935. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9936. zs.avail_in = static_cast<uInt>(raw.size());
  9937. char outbuf[4096];
  9938. int ret;
  9939. do {
  9940. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9941. zs.avail_out = sizeof(outbuf);
  9942. ret = deflate(&zs, Z_FINISH);
  9943. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9944. } while (ret != Z_STREAM_END);
  9945. deflateEnd(&zs);
  9946. }
  9947. Client cli(HOST, PORT);
  9948. cli.set_connection_timeout(std::chrono::seconds(5));
  9949. Headers headers = {{"Content-Encoding", "gzip"}};
  9950. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9951. "application/octet-stream");
  9952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9953. // Server must reject oversized decompressed payloads with 413.
  9954. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9955. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9956. EXPECT_LE(total, LIMIT);
  9957. }
  9958. #ifndef CPPHTTPLIB_SSL_ENABLED
  9959. // For a request with neither Content-Length nor Transfer-Encoding, the
  9960. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9961. // compressed wire bytes straight to the ContentReader without ever routing
  9962. // them through the decompressor, so payload_max_length_ only bounded the
  9963. // compressed size on the wire, not the decompressed size.
  9964. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9965. Server svr;
  9966. const size_t LIMIT = 64 * 1024; // 64KB
  9967. svr.set_payload_max_length(LIMIT);
  9968. size_t total = 0;
  9969. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9970. const ContentReader &content_reader) {
  9971. content_reader([&](const char * /*data*/, size_t len) {
  9972. total += len;
  9973. return true;
  9974. });
  9975. res.status = 200;
  9976. res.set_content("stream_ok", "text/plain");
  9977. });
  9978. auto port = svr.bind_to_any_port(HOST);
  9979. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. thread.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. });
  9985. svr.wait_until_ready();
  9986. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9987. // StreamingGzipDecompression test above.
  9988. std::string raw(256 * 1024, 'A');
  9989. std::string gz;
  9990. {
  9991. httplib::detail::gzip_compressor compressor;
  9992. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9993. [&](const char *chunk, size_t len) {
  9994. gz.append(chunk, len);
  9995. return true;
  9996. });
  9997. ASSERT_TRUE(result);
  9998. }
  9999. // Send the gzip body over raw TCP with neither Content-Length nor
  10000. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10001. // kicks in.
  10002. std::string req = "POST /stream HTTP/1.1\r\n"
  10003. "Host: " +
  10004. std::string(HOST) + ":" + std::to_string(port) +
  10005. "\r\n"
  10006. "Content-Encoding: gzip\r\n"
  10007. "Connection: close\r\n"
  10008. "\r\n" +
  10009. gz;
  10010. std::string response;
  10011. ASSERT_TRUE(send_request(5, req, &response, port));
  10012. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10013. EXPECT_LE(total, LIMIT);
  10014. }
  10015. #endif
  10016. #endif
  10017. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10018. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10019. // the payload must be passed through untouched instead of being rejected.
  10020. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10021. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10022. Server svr;
  10023. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10024. res.set_content(body, "image/jpeg");
  10025. res.set_header("Content-Encoding", "UTF-8");
  10026. });
  10027. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10028. res.set_content(body, "image/jpeg");
  10029. res.set_header("Content-Encoding", "identity");
  10030. });
  10031. svr.Post("/echo", [](const Request &req, Response &res) {
  10032. res.set_content(req.body, "image/jpeg");
  10033. });
  10034. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. t.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. Client cli(HOST, PORT);
  10042. {
  10043. auto res = cli.Get("/image");
  10044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10045. EXPECT_EQ(StatusCode::OK_200, res->status);
  10046. EXPECT_EQ(body, res->body);
  10047. }
  10048. {
  10049. auto res = cli.Get("/identity");
  10050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10051. EXPECT_EQ(StatusCode::OK_200, res->status);
  10052. EXPECT_EQ(body, res->body);
  10053. }
  10054. {
  10055. // The same applies to a request body reaching the server.
  10056. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10057. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10059. EXPECT_EQ(StatusCode::OK_200, res->status);
  10060. EXPECT_EQ(body, res->body);
  10061. }
  10062. }
  10063. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10064. // gzip-encoded response even when the build has no zlib support.
  10065. static const char GZIPPED_HELLO_WORLD[] = {
  10066. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10067. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10068. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10069. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10070. // A content coding is a whole token, not something the field value merely
  10071. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10072. // as "fibre" look like Brotli, and turned a multi-coding value like
  10073. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10074. // it was never meant to see.
  10075. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10076. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10077. Server svr;
  10078. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10079. res.set_content(body, "image/jpeg");
  10080. res.set_header("Content-Encoding", "fibre");
  10081. });
  10082. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10083. res.set_content(body, "image/jpeg");
  10084. res.set_header("Content-Encoding", "gzip, br");
  10085. });
  10086. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10087. res.set_content(body, "image/jpeg");
  10088. res.set_header("Content-Encoding", "x-zstd-ish");
  10089. });
  10090. auto port = svr.bind_to_any_port(HOST);
  10091. thread t = thread([&]() { svr.listen_after_bind(); });
  10092. auto se = detail::scope_exit([&] {
  10093. svr.stop();
  10094. t.join();
  10095. ASSERT_FALSE(svr.is_running());
  10096. });
  10097. svr.wait_until_ready();
  10098. Client cli(HOST, port);
  10099. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10100. auto res = cli.Get(path);
  10101. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10102. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10103. // Not a coding we recognize, so the payload comes back untouched
  10104. EXPECT_EQ(body, res->body) << path;
  10105. }
  10106. }
  10107. // A content coding cpp-httplib recognizes but was not built with must be
  10108. // reported as such. Handing the still-compressed payload back to the caller
  10109. // would silently corrupt it.
  10110. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10111. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10112. Server svr;
  10113. // "image/jpeg" keeps the server from applying a content coding of its own,
  10114. // so the hand-crafted Content-Encoding below survives.
  10115. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10116. res.set_content(gzipped, "image/jpeg");
  10117. res.set_header("Content-Encoding", "gzip");
  10118. });
  10119. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10120. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10121. res.set_content(gzipped, "image/jpeg");
  10122. res.set_header("Content-Encoding", "GZIP");
  10123. });
  10124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10125. auto se = detail::scope_exit([&] {
  10126. svr.stop();
  10127. t.join();
  10128. ASSERT_FALSE(svr.is_running());
  10129. });
  10130. svr.wait_until_ready();
  10131. Client cli(HOST, PORT);
  10132. {
  10133. auto res = cli.Get("/gzipped");
  10134. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10136. EXPECT_EQ("Hello World!", res->body);
  10137. #else
  10138. ASSERT_FALSE(res);
  10139. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10140. #endif
  10141. }
  10142. {
  10143. // open_stream() must behave the same way.
  10144. auto handle = cli.open_stream("GET", "/gzipped");
  10145. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10146. ASSERT_TRUE(handle.is_valid());
  10147. std::string received;
  10148. char buf[256];
  10149. ssize_t n;
  10150. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10151. received.append(buf, static_cast<size_t>(n));
  10152. }
  10153. EXPECT_EQ("Hello World!", received);
  10154. #else
  10155. EXPECT_FALSE(handle.is_valid());
  10156. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10157. #endif
  10158. }
  10159. {
  10160. // A differently-cased coding must not be mistaken for an unknown one, or
  10161. // the body would be handed back still compressed.
  10162. auto res = cli.Get("/gzipped-uppercase");
  10163. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10165. EXPECT_EQ("Hello World!", res->body);
  10166. #else
  10167. ASSERT_FALSE(res);
  10168. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10169. #endif
  10170. }
  10171. }
  10172. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10173. // the same message as the comma-joined one, so both have to be read the same
  10174. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10175. // single gzip coding, and a body the sender says was encoded twice was handed
  10176. // back after one pass, still compressed but presented as decoded.
  10177. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10178. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10179. Server svr;
  10180. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10181. res.set_content(body, "image/jpeg");
  10182. res.headers.emplace("Content-Encoding", "gzip");
  10183. res.headers.emplace("Content-Encoding", "gzip");
  10184. });
  10185. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10186. res.set_content(body, "image/jpeg");
  10187. res.set_header("Content-Encoding", "gzip, gzip");
  10188. });
  10189. auto port = svr.bind_to_any_port(HOST);
  10190. thread t = thread([&]() { svr.listen_after_bind(); });
  10191. auto se = detail::scope_exit([&] {
  10192. svr.stop();
  10193. t.join();
  10194. ASSERT_FALSE(svr.is_running());
  10195. });
  10196. svr.wait_until_ready();
  10197. Client cli(HOST, port);
  10198. // Two codings is not something cpp-httplib decodes, so both representations
  10199. // take the pass-through path rather than one of them being gunzipped once.
  10200. for (const char *path : {"/split", "/joined"}) {
  10201. auto res = cli.Get(path);
  10202. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10203. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10204. EXPECT_EQ(body, res->body) << path;
  10205. }
  10206. }
  10207. // Regression test for DoS vulnerability: a malicious server sending a response
  10208. // without Content-Length header must not cause unbounded memory consumption on
  10209. // the client side. The client should stop reading after a reasonable limit,
  10210. // similar to the server-side set_payload_max_length protection.
  10211. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10212. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10213. #ifndef _WIN32
  10214. signal(SIGPIPE, SIG_IGN);
  10215. #endif
  10216. auto server_thread = std::thread([] {
  10217. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10218. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10219. default_socket_options(srv);
  10220. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10221. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10222. sockaddr_in addr{};
  10223. addr.sin_family = AF_INET;
  10224. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10225. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10226. int opt = 1;
  10227. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10228. #ifdef _WIN32
  10229. reinterpret_cast<const char *>(&opt),
  10230. #else
  10231. &opt,
  10232. #endif
  10233. sizeof(opt));
  10234. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10235. ::listen(srv, 1);
  10236. sockaddr_in cli_addr{};
  10237. socklen_t cli_len = sizeof(cli_addr);
  10238. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10239. if (cli != INVALID_SOCKET) {
  10240. char buf[4096];
  10241. ::recv(cli, buf, sizeof(buf), 0);
  10242. // Malicious response: no Content-Length, no chunked encoding
  10243. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10244. "Connection: close\r\n"
  10245. "\r\n";
  10246. ::send(cli,
  10247. #ifdef _WIN32
  10248. static_cast<const char *>(response_header.c_str()),
  10249. static_cast<int>(response_header.size()),
  10250. #else
  10251. response_header.c_str(), response_header.size(),
  10252. #endif
  10253. 0);
  10254. // Send 10MB of data
  10255. std::string chunk(64 * 1024, 'A');
  10256. size_t total_sent = 0;
  10257. while (total_sent < MALICIOUS_DATA_SIZE) {
  10258. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10259. auto sent = ::send(cli,
  10260. #ifdef _WIN32
  10261. static_cast<const char *>(chunk.c_str()),
  10262. static_cast<int>(to_send),
  10263. #else
  10264. chunk.c_str(), to_send,
  10265. #endif
  10266. 0);
  10267. if (sent <= 0) break;
  10268. total_sent += static_cast<size_t>(sent);
  10269. }
  10270. detail::close_socket(cli);
  10271. }
  10272. detail::close_socket(srv);
  10273. });
  10274. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10275. size_t total_read = 0;
  10276. {
  10277. Client cli("127.0.0.1", PORT + 2);
  10278. cli.set_read_timeout(5, 0);
  10279. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10280. auto stream = cli.open_stream("GET", "/malicious");
  10281. ASSERT_TRUE(stream.is_valid());
  10282. char buffer[64 * 1024];
  10283. ssize_t n;
  10284. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10285. total_read += static_cast<size_t>(n);
  10286. }
  10287. } // StreamHandle and Client destroyed here, closing the socket
  10288. server_thread.join();
  10289. // With set_payload_max_length, the client must stop reading before consuming
  10290. // all 10MB. The read loop should be cut off at or near the configured limit.
  10291. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10292. << "Client read " << total_read << " bytes, exceeding the configured "
  10293. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10294. }
  10295. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10296. // the entire response body without truncation.
  10297. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10298. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10299. #ifndef _WIN32
  10300. signal(SIGPIPE, SIG_IGN);
  10301. #endif
  10302. auto server_thread = std::thread([] {
  10303. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10304. default_socket_options(srv);
  10305. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10306. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10307. sockaddr_in addr{};
  10308. addr.sin_family = AF_INET;
  10309. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10310. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10311. int opt = 1;
  10312. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10313. #ifdef _WIN32
  10314. reinterpret_cast<const char *>(&opt),
  10315. #else
  10316. &opt,
  10317. #endif
  10318. sizeof(opt));
  10319. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10320. ::listen(srv, 1);
  10321. sockaddr_in cli_addr{};
  10322. socklen_t cli_len = sizeof(cli_addr);
  10323. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10324. if (cli != INVALID_SOCKET) {
  10325. char buf[4096];
  10326. ::recv(cli, buf, sizeof(buf), 0);
  10327. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10328. "Connection: close\r\n"
  10329. "\r\n";
  10330. ::send(cli,
  10331. #ifdef _WIN32
  10332. static_cast<const char *>(response_header.c_str()),
  10333. static_cast<int>(response_header.size()),
  10334. #else
  10335. response_header.c_str(), response_header.size(),
  10336. #endif
  10337. 0);
  10338. std::string chunk(64 * 1024, 'A');
  10339. size_t total_sent = 0;
  10340. while (total_sent < DATA_SIZE) {
  10341. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10342. auto sent = ::send(cli,
  10343. #ifdef _WIN32
  10344. static_cast<const char *>(chunk.c_str()),
  10345. static_cast<int>(to_send),
  10346. #else
  10347. chunk.c_str(), to_send,
  10348. #endif
  10349. 0);
  10350. if (sent <= 0) break;
  10351. total_sent += static_cast<size_t>(sent);
  10352. }
  10353. #ifdef _WIN32
  10354. ::shutdown(cli, SD_SEND);
  10355. #else
  10356. ::shutdown(cli, SHUT_WR);
  10357. #endif
  10358. // Drain until the client closes its end, ensuring all data is delivered
  10359. char drain[1024];
  10360. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10361. detail::close_socket(cli);
  10362. }
  10363. detail::close_socket(srv);
  10364. });
  10365. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10366. size_t total_read = 0;
  10367. {
  10368. Client cli("127.0.0.1", PORT + 2);
  10369. cli.set_read_timeout(5, 0);
  10370. cli.set_payload_max_length(0); // 0 means no limit
  10371. auto stream = cli.open_stream("GET", "/data");
  10372. ASSERT_TRUE(stream.is_valid());
  10373. char buffer[64 * 1024];
  10374. ssize_t n;
  10375. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10376. total_read += static_cast<size_t>(n);
  10377. }
  10378. }
  10379. server_thread.join();
  10380. EXPECT_EQ(total_read, DATA_SIZE)
  10381. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10382. << " bytes without truncation, but only read " << total_read << " bytes.";
  10383. }
  10384. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10385. // enormous Content-Length must not cause the client to pre-allocate a huge
  10386. // response body buffer. The reservation is capped at payload_max_length_, and
  10387. // the read itself fails when the body exceeds the limit.
  10388. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10389. #ifndef _WIN32
  10390. signal(SIGPIPE, SIG_IGN);
  10391. #endif
  10392. auto server_thread = std::thread([] {
  10393. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10394. default_socket_options(srv);
  10395. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10396. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10397. sockaddr_in addr{};
  10398. addr.sin_family = AF_INET;
  10399. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10400. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10401. int opt = 1;
  10402. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10403. #ifdef _WIN32
  10404. reinterpret_cast<const char *>(&opt),
  10405. #else
  10406. &opt,
  10407. #endif
  10408. sizeof(opt));
  10409. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10410. ::listen(srv, 1);
  10411. sockaddr_in cli_addr{};
  10412. socklen_t cli_len = sizeof(cli_addr);
  10413. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10414. if (cli != INVALID_SOCKET) {
  10415. char buf[4096];
  10416. ::recv(cli, buf, sizeof(buf), 0);
  10417. // Malicious response: claim a 20GB body but send only a tiny payload.
  10418. std::string response = "HTTP/1.1 200 OK\r\n"
  10419. "Content-Length: 20000000000\r\n"
  10420. "\r\n"
  10421. "abc";
  10422. ::send(cli,
  10423. #ifdef _WIN32
  10424. static_cast<const char *>(response.c_str()),
  10425. static_cast<int>(response.size()),
  10426. #else
  10427. response.c_str(), response.size(),
  10428. #endif
  10429. 0);
  10430. detail::close_socket(cli);
  10431. }
  10432. detail::close_socket(srv);
  10433. });
  10434. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10435. {
  10436. Client cli("127.0.0.1", PORT + 2);
  10437. cli.set_read_timeout(5, 0);
  10438. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10439. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10440. // (server claims more bytes than payload_max_length permits), but it must
  10441. // not exhaust memory before getting there.
  10442. auto res = cli.Get("/malicious");
  10443. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10444. }
  10445. server_thread.join();
  10446. }
  10447. // Verify that content_receiver bypasses the default payload_max_length,
  10448. // allowing streaming downloads larger than 100MB without requiring an explicit
  10449. // set_payload_max_length call.
  10450. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10451. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10452. #ifndef _WIN32
  10453. signal(SIGPIPE, SIG_IGN);
  10454. #endif
  10455. auto server_thread = std::thread([] {
  10456. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10457. default_socket_options(srv);
  10458. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10460. sockaddr_in addr{};
  10461. addr.sin_family = AF_INET;
  10462. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10463. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10464. int opt = 1;
  10465. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10466. #ifdef _WIN32
  10467. reinterpret_cast<const char *>(&opt),
  10468. #else
  10469. &opt,
  10470. #endif
  10471. sizeof(opt));
  10472. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10473. ::listen(srv, 1);
  10474. sockaddr_in cli_addr{};
  10475. socklen_t cli_len = sizeof(cli_addr);
  10476. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10477. if (cli != INVALID_SOCKET) {
  10478. char buf[4096];
  10479. ::recv(cli, buf, sizeof(buf), 0);
  10480. // Response with Content-Length larger than default 100MB limit
  10481. auto content_length = std::to_string(DATA_SIZE);
  10482. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10483. "Content-Length: " +
  10484. content_length +
  10485. "\r\n"
  10486. "Connection: close\r\n"
  10487. "\r\n";
  10488. ::send(cli,
  10489. #ifdef _WIN32
  10490. static_cast<const char *>(response_header.c_str()),
  10491. static_cast<int>(response_header.size()),
  10492. #else
  10493. response_header.c_str(), response_header.size(),
  10494. #endif
  10495. 0);
  10496. std::string chunk(64 * 1024, 'A');
  10497. size_t total_sent = 0;
  10498. while (total_sent < DATA_SIZE) {
  10499. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10500. auto sent = ::send(cli,
  10501. #ifdef _WIN32
  10502. static_cast<const char *>(chunk.c_str()),
  10503. static_cast<int>(to_send),
  10504. #else
  10505. chunk.c_str(), to_send,
  10506. #endif
  10507. 0);
  10508. if (sent <= 0) break;
  10509. total_sent += static_cast<size_t>(sent);
  10510. }
  10511. detail::close_socket(cli);
  10512. }
  10513. detail::close_socket(srv);
  10514. });
  10515. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10516. size_t total_received = 0;
  10517. {
  10518. Client cli("127.0.0.1", PORT + 2);
  10519. cli.set_read_timeout(10, 0);
  10520. // Do NOT call set_payload_max_length — use the default 100MB limit
  10521. auto res =
  10522. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10523. total_received += data_length;
  10524. return true;
  10525. });
  10526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10527. EXPECT_EQ(StatusCode::OK_200, res->status);
  10528. }
  10529. server_thread.join();
  10530. EXPECT_EQ(total_received, DATA_SIZE)
  10531. << "With content_receiver, the client should read all " << DATA_SIZE
  10532. << " bytes despite the default 100MB payload_max_length, but only read "
  10533. << total_received << " bytes.";
  10534. }
  10535. // Verify that an explicit set_payload_max_length smaller than the response is
  10536. // enforced even when a content_receiver is used.
  10537. TEST(ClientVulnerabilityTest,
  10538. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10539. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10540. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10541. #ifndef _WIN32
  10542. signal(SIGPIPE, SIG_IGN);
  10543. #endif
  10544. auto server_thread = std::thread([] {
  10545. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10546. default_socket_options(srv);
  10547. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10548. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10549. sockaddr_in addr{};
  10550. addr.sin_family = AF_INET;
  10551. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10552. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10553. int opt = 1;
  10554. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10555. #ifdef _WIN32
  10556. reinterpret_cast<const char *>(&opt),
  10557. #else
  10558. &opt,
  10559. #endif
  10560. sizeof(opt));
  10561. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10562. ::listen(srv, 1);
  10563. sockaddr_in cli_addr{};
  10564. socklen_t cli_len = sizeof(cli_addr);
  10565. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10566. if (cli != INVALID_SOCKET) {
  10567. char buf[4096];
  10568. ::recv(cli, buf, sizeof(buf), 0);
  10569. auto content_length = std::to_string(DATA_SIZE);
  10570. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10571. "Content-Length: " +
  10572. content_length +
  10573. "\r\n"
  10574. "Connection: close\r\n"
  10575. "\r\n";
  10576. ::send(cli,
  10577. #ifdef _WIN32
  10578. static_cast<const char *>(response_header.c_str()),
  10579. static_cast<int>(response_header.size()),
  10580. #else
  10581. response_header.c_str(), response_header.size(),
  10582. #endif
  10583. 0);
  10584. std::string chunk(64 * 1024, 'A');
  10585. size_t total_sent = 0;
  10586. while (total_sent < DATA_SIZE) {
  10587. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10588. auto sent = ::send(cli,
  10589. #ifdef _WIN32
  10590. static_cast<const char *>(chunk.c_str()),
  10591. static_cast<int>(to_send),
  10592. #else
  10593. chunk.c_str(), to_send,
  10594. #endif
  10595. 0);
  10596. if (sent <= 0) break;
  10597. total_sent += static_cast<size_t>(sent);
  10598. }
  10599. detail::close_socket(cli);
  10600. }
  10601. detail::close_socket(srv);
  10602. });
  10603. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10604. size_t total_received = 0;
  10605. {
  10606. Client cli("127.0.0.1", PORT + 2);
  10607. cli.set_read_timeout(10, 0);
  10608. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10609. auto res =
  10610. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10611. total_received += data_length;
  10612. return true;
  10613. });
  10614. // Should fail because 200MB exceeds the explicit 150MB limit
  10615. EXPECT_FALSE(res);
  10616. }
  10617. server_thread.join();
  10618. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10619. << "Client with content_receiver should respect the explicit "
  10620. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10621. << total_received << " bytes.";
  10622. }
  10623. // Verify that an explicit set_payload_max_length larger than the response
  10624. // allows the content_receiver to read all data successfully.
  10625. TEST(ClientVulnerabilityTest,
  10626. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10627. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10628. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10629. #ifndef _WIN32
  10630. signal(SIGPIPE, SIG_IGN);
  10631. #endif
  10632. auto server_thread = std::thread([] {
  10633. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10634. default_socket_options(srv);
  10635. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10636. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10637. sockaddr_in addr{};
  10638. addr.sin_family = AF_INET;
  10639. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10640. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10641. int opt = 1;
  10642. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10643. #ifdef _WIN32
  10644. reinterpret_cast<const char *>(&opt),
  10645. #else
  10646. &opt,
  10647. #endif
  10648. sizeof(opt));
  10649. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10650. ::listen(srv, 1);
  10651. sockaddr_in cli_addr{};
  10652. socklen_t cli_len = sizeof(cli_addr);
  10653. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10654. if (cli != INVALID_SOCKET) {
  10655. char buf[4096];
  10656. ::recv(cli, buf, sizeof(buf), 0);
  10657. auto content_length = std::to_string(DATA_SIZE);
  10658. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10659. "Content-Length: " +
  10660. content_length +
  10661. "\r\n"
  10662. "Connection: close\r\n"
  10663. "\r\n";
  10664. ::send(cli,
  10665. #ifdef _WIN32
  10666. static_cast<const char *>(response_header.c_str()),
  10667. static_cast<int>(response_header.size()),
  10668. #else
  10669. response_header.c_str(), response_header.size(),
  10670. #endif
  10671. 0);
  10672. std::string chunk(64 * 1024, 'A');
  10673. size_t total_sent = 0;
  10674. while (total_sent < DATA_SIZE) {
  10675. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10676. auto sent = ::send(cli,
  10677. #ifdef _WIN32
  10678. static_cast<const char *>(chunk.c_str()),
  10679. static_cast<int>(to_send),
  10680. #else
  10681. chunk.c_str(), to_send,
  10682. #endif
  10683. 0);
  10684. if (sent <= 0) break;
  10685. total_sent += static_cast<size_t>(sent);
  10686. }
  10687. #ifdef _WIN32
  10688. ::shutdown(cli, SD_SEND);
  10689. #else
  10690. ::shutdown(cli, SHUT_WR);
  10691. #endif
  10692. char drain[1024];
  10693. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10694. detail::close_socket(cli);
  10695. }
  10696. detail::close_socket(srv);
  10697. });
  10698. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10699. size_t total_received = 0;
  10700. {
  10701. Client cli("127.0.0.1", PORT + 2);
  10702. cli.set_read_timeout(10, 0);
  10703. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10704. auto res =
  10705. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10706. total_received += data_length;
  10707. return true;
  10708. });
  10709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10710. EXPECT_EQ(StatusCode::OK_200, res->status);
  10711. }
  10712. server_thread.join();
  10713. EXPECT_EQ(total_received, DATA_SIZE)
  10714. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10715. << " bytes (larger than " << DATA_SIZE
  10716. << " bytes response), content_receiver should read all data, but only "
  10717. "read "
  10718. << total_received << " bytes.";
  10719. }
  10720. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10721. // Regression test for "zip bomb" attack on the client side: a malicious server
  10722. // sends a small gzip-compressed response that decompresses to a huge payload.
  10723. // The client must enforce payload_max_length on the decompressed size.
  10724. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10725. constexpr size_t DECOMPRESSED_SIZE =
  10726. 10 * 1024 * 1024; // 10MB after decompression
  10727. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10728. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10729. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10730. std::string compressed;
  10731. {
  10732. httplib::detail::gzip_compressor compressor;
  10733. bool ok =
  10734. compressor.compress(uncompressed.data(), uncompressed.size(),
  10735. /*last=*/true, [&](const char *buf, size_t len) {
  10736. compressed.append(buf, len);
  10737. return true;
  10738. });
  10739. ASSERT_TRUE(ok);
  10740. }
  10741. // Sanity: compressed data should be much smaller than the decompressed size
  10742. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10743. #ifndef _WIN32
  10744. signal(SIGPIPE, SIG_IGN);
  10745. #endif
  10746. // Set up the listening socket in the main thread so the server is guaranteed
  10747. // to be ready before the client connects (eliminates race condition).
  10748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10749. default_socket_options(srv);
  10750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10752. sockaddr_in addr{};
  10753. addr.sin_family = AF_INET;
  10754. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10756. int opt = 1;
  10757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10758. #ifdef _WIN32
  10759. reinterpret_cast<const char *>(&opt),
  10760. #else
  10761. &opt,
  10762. #endif
  10763. sizeof(opt));
  10764. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10765. ASSERT_EQ(0, ::listen(srv, 1));
  10766. auto server_thread = std::thread([&compressed, srv] {
  10767. sockaddr_in cli_addr{};
  10768. socklen_t cli_len = sizeof(cli_addr);
  10769. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10770. if (cli != INVALID_SOCKET) {
  10771. // Read the full HTTP request (until \r\n\r\n)
  10772. char buf[4096];
  10773. size_t total = 0;
  10774. while (total < sizeof(buf)) {
  10775. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10776. if (n <= 0) break;
  10777. total += static_cast<size_t>(n);
  10778. // Check for end of headers
  10779. if (total >= 4) {
  10780. std::string req(buf, total);
  10781. if (req.find("\r\n\r\n") != std::string::npos) break;
  10782. }
  10783. }
  10784. // Malicious response: gzip-compressed body, no Content-Length
  10785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10786. "Content-Encoding: gzip\r\n"
  10787. "Connection: close\r\n"
  10788. "\r\n";
  10789. ::send(cli,
  10790. #ifdef _WIN32
  10791. static_cast<const char *>(response_header.c_str()),
  10792. static_cast<int>(response_header.size()),
  10793. #else
  10794. response_header.c_str(), response_header.size(),
  10795. #endif
  10796. 0);
  10797. // Send the compressed payload (small on the wire, huge when decompressed)
  10798. size_t total_sent = 0;
  10799. while (total_sent < compressed.size()) {
  10800. auto to_send = std::min(compressed.size() - total_sent,
  10801. static_cast<size_t>(64 * 1024));
  10802. auto sent =
  10803. ::send(cli,
  10804. #ifdef _WIN32
  10805. static_cast<const char *>(compressed.c_str() + total_sent),
  10806. static_cast<int>(to_send),
  10807. #else
  10808. compressed.c_str() + total_sent, to_send,
  10809. #endif
  10810. 0);
  10811. if (sent <= 0) break;
  10812. total_sent += static_cast<size_t>(sent);
  10813. }
  10814. detail::close_socket(cli);
  10815. }
  10816. });
  10817. auto se = detail::scope_exit([&] {
  10818. detail::close_socket(srv);
  10819. server_thread.join();
  10820. });
  10821. size_t total_decompressed = 0;
  10822. {
  10823. Client cli("127.0.0.1", PORT + 3);
  10824. cli.set_read_timeout(5, 0);
  10825. cli.set_decompress(true);
  10826. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10827. auto stream = cli.open_stream("GET", "/zipbomb");
  10828. ASSERT_TRUE(stream.is_valid());
  10829. char buffer[64 * 1024];
  10830. ssize_t n;
  10831. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10832. total_decompressed += static_cast<size_t>(n);
  10833. }
  10834. }
  10835. // The decompressed size must be capped by payload_max_length. Without
  10836. // protection, the client would decompress the full 10MB from a tiny
  10837. // compressed payload, enabling a zip bomb DoS attack.
  10838. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10839. << "Client decompressed " << total_decompressed
  10840. << " bytes from a gzip response. The decompressed size should be "
  10841. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10842. }
  10843. #endif
  10844. TEST(HostAndPortPropertiesTest, NoSSL) {
  10845. httplib::Client cli("www.google.com", 1234);
  10846. ASSERT_EQ("www.google.com", cli.host());
  10847. ASSERT_EQ(1234, cli.port());
  10848. }
  10849. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10850. httplib::Client cli("www.google.com:1234");
  10851. ASSERT_EQ("www.google.com", cli.host());
  10852. ASSERT_EQ(1234, cli.port());
  10853. }
  10854. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10855. // Port number that overflows int — should not crash, client becomes invalid
  10856. httplib::Client cli("http://www.google.com:99999999999999999999");
  10857. ASSERT_FALSE(cli.is_valid());
  10858. }
  10859. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10860. // Port 99999 exceeds valid range (1-65535) — should not crash
  10861. httplib::Client cli("http://www.google.com:99999");
  10862. ASSERT_FALSE(cli.is_valid());
  10863. }
  10864. #ifdef CPPHTTPLIB_SSL_ENABLED
  10865. TEST(HostAndPortPropertiesTest, SSL) {
  10866. httplib::SSLClient cli("www.google.com");
  10867. ASSERT_EQ("www.google.com", cli.host());
  10868. ASSERT_EQ(443, cli.port());
  10869. }
  10870. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10871. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10872. std::string cert;
  10873. read_file(CA_CERT_FILE, cert);
  10874. httplib::SSLClient httplib_client("www.google.com");
  10875. // Load CA store first time
  10876. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10877. // Load CA store second time (update)
  10878. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10879. // Verify client is still valid and can make connections
  10880. httplib_client.enable_server_certificate_verification(true);
  10881. auto res = httplib_client.Get("/");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. // Google may return 200 or 301 depending on various factors
  10884. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10885. res->status == StatusCode::MovedPermanently_301);
  10886. }
  10887. TEST(SSLClientTest, ServerNameIndication_Online) {
  10888. auto host = "httpbingo.org";
  10889. auto path = std::string{"/get"};
  10890. SSLClient cli(host, 443);
  10891. auto res = cli.Get(path);
  10892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10893. ASSERT_EQ(StatusCode::OK_200, res->status);
  10894. }
  10895. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10896. // Use a site that will cause SSL verification failure due to self-signed cert
  10897. SSLClient cli("self-signed.badssl.com", 443);
  10898. cli.enable_server_certificate_verification(true);
  10899. auto res = cli.Get("/");
  10900. ASSERT_TRUE(!res);
  10901. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10902. // Verify backend error is captured for SSLServerVerification
  10903. // This occurs when certificate verification fails
  10904. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10905. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10906. EXPECT_NE(0UL, res.ssl_backend_error());
  10907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10908. // For OpenSSL, ssl_error is 0 for verification errors
  10909. EXPECT_EQ(0, res.ssl_error());
  10910. #if !defined(_WIN32) || \
  10911. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10912. // On non-Windows or when Windows Schannel is disabled, the error comes
  10913. // from OpenSSL's verification
  10914. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10915. res.ssl_backend_error());
  10916. #endif
  10917. #endif
  10918. }
  10919. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10920. // Use a site where hostname doesn't match the certificate
  10921. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10922. SSLClient cli("wrong.host.badssl.com", 443);
  10923. cli.enable_server_certificate_verification(true);
  10924. cli.enable_server_hostname_verification(true);
  10925. auto res = cli.Get("/");
  10926. ASSERT_TRUE(!res);
  10927. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10928. // Verify backend error is captured for hostname verification failure
  10929. EXPECT_NE(0UL, res.ssl_backend_error());
  10930. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10931. // For OpenSSL, ssl_error is 0 for verification errors
  10932. EXPECT_EQ(0, res.ssl_error());
  10933. #if !defined(_WIN32) || \
  10934. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10935. // On non-Windows or when Windows Schannel is disabled, the error comes
  10936. // from OpenSSL's hostname verification
  10937. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10938. res.ssl_backend_error());
  10939. #endif
  10940. #endif
  10941. }
  10942. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10943. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10944. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10945. SSLClient cli("www.google.com", 443);
  10946. cli.enable_server_certificate_verification(true);
  10947. auto res = cli.Get("/");
  10948. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10949. }
  10950. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10951. SSLClient cli("www.google.com", 443);
  10952. cli.enable_server_certificate_verification(true);
  10953. cli.enable_windows_certificate_verification(false);
  10954. auto res = cli.Get("/");
  10955. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10956. }
  10957. #endif
  10958. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10959. Client cli("https://google.com");
  10960. auto res = cli.Get("/");
  10961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10962. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10963. }
  10964. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10965. SSLClient cli("google.com");
  10966. cli.set_ca_cert_path(CA_CERT_FILE);
  10967. auto res = cli.Get("/");
  10968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10969. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10970. }
  10971. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10972. SSLClient cli("google.com");
  10973. cli.enable_server_certificate_verification(true);
  10974. cli.set_ca_cert_path("hello");
  10975. auto res = cli.Get("/");
  10976. ASSERT_TRUE(!res);
  10977. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10978. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10979. // should be set
  10980. EXPECT_EQ(0, res.ssl_error());
  10981. // Verify backend error is captured for SSLLoadingCerts
  10982. // This error occurs when loading CA certificates fails
  10983. EXPECT_NE(0UL, res.ssl_backend_error());
  10984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10985. // OpenSSL specific error codes:
  10986. // > openssl errstr 0x80000002
  10987. // error:80000002:system library::No such file or directory
  10988. // > openssl errstr 0xA000126
  10989. // error:0A000126:SSL routines::unexpected eof while reading
  10990. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10991. res.ssl_backend_error() == 0xA000126);
  10992. #endif
  10993. }
  10994. TEST(SSLClientTest, ServerCertificateVerification4) {
  10995. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10996. ASSERT_TRUE(svr.is_valid());
  10997. svr.Get("/test", [&](const Request &, Response &res) {
  10998. res.set_content("test", "text/plain");
  10999. svr.stop();
  11000. ASSERT_TRUE(true);
  11001. });
  11002. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11003. auto se = detail::scope_exit([&] {
  11004. t.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. });
  11007. svr.wait_until_ready();
  11008. SSLClient cli("127.0.0.1", PORT);
  11009. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11010. cli.enable_server_certificate_verification(true);
  11011. cli.set_connection_timeout(30);
  11012. auto res = cli.Get("/test");
  11013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11014. ASSERT_EQ(StatusCode::OK_200, res->status);
  11015. }
  11016. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11017. std::string cert;
  11018. read_file(CA_CERT_FILE, cert);
  11019. SSLClient cli("google.com");
  11020. cli.load_ca_cert_store(cert.data(), cert.size());
  11021. const auto res = cli.Get("/");
  11022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11023. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11024. }
  11025. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11026. // clang-format off
  11027. static constexpr char cert[] =
  11028. "GlobalSign Root CA\n"
  11029. "==================\n"
  11030. "-----BEGIN CERTIFICATE-----\n"
  11031. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11032. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11033. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11034. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11035. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11036. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11037. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11038. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11039. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11040. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11041. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11042. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11043. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11044. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11045. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11046. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11047. "-----END CERTIFICATE-----\n";
  11048. // clang-format on
  11049. SSLClient cli("google.com");
  11050. cli.load_ca_cert_store(cert, sizeof(cert));
  11051. const auto res = cli.Get("/");
  11052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11053. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11054. }
  11055. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11056. SSLClient cli("www.youtube.com");
  11057. cli.set_ca_cert_path(CA_CERT_FILE);
  11058. cli.enable_server_certificate_verification(true);
  11059. cli.set_follow_location(true);
  11060. auto res = cli.Get("/");
  11061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11062. ASSERT_EQ(StatusCode::OK_200, res->status);
  11063. }
  11064. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11065. SSLClient cli("wWw.YouTube.Com");
  11066. cli.set_ca_cert_path(CA_CERT_FILE);
  11067. cli.enable_server_certificate_verification(true);
  11068. cli.enable_server_hostname_verification(true);
  11069. cli.set_follow_location(true);
  11070. auto res = cli.Get("/");
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. ASSERT_EQ(StatusCode::OK_200, res->status);
  11073. }
  11074. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11075. SSLClient cli("gOoGlE.COm");
  11076. cli.enable_server_certificate_verification(true);
  11077. cli.enable_server_hostname_verification(true);
  11078. cli.set_follow_location(true);
  11079. auto res = cli.Get("/");
  11080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11081. ASSERT_EQ(StatusCode::OK_200, res->status);
  11082. }
  11083. TEST(SSLClientTest, Issue2004_Online) {
  11084. Client client("https://google.com");
  11085. client.set_follow_location(true);
  11086. auto res = client.Get("/");
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. ASSERT_EQ(StatusCode::OK_200, res->status);
  11089. auto body = res->body;
  11090. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11091. }
  11092. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11093. // Create SSLClient with invalid cert/key to make is_valid() return false
  11094. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11095. "nonexistent_key.pem");
  11096. // is_valid() should be false due to cert loading failure
  11097. ASSERT_FALSE(cli.is_valid());
  11098. auto res = cli.Get("/");
  11099. ASSERT_FALSE(res);
  11100. EXPECT_EQ(Error::SSLConnection, res.error());
  11101. }
  11102. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11103. // Test for Issue #2251: SSL error not properly reported when client cert
  11104. // and key paths are swapped or mismatched
  11105. // This simulates the scenario where user accidentally swaps the cert and key
  11106. // files
  11107. // Using client cert file as private key and vice versa (completely wrong)
  11108. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11109. // Should fail validation due to cert/key mismatch
  11110. ASSERT_FALSE(cli.is_valid());
  11111. // Attempt to make a request should fail with proper error
  11112. auto res = cli.Get("/");
  11113. ASSERT_FALSE(res);
  11114. EXPECT_EQ(Error::SSLConnection, res.error());
  11115. // SSL error should be recorded in the Result object (this is the key fix for
  11116. // Issue #2251)
  11117. auto backend_error = res.ssl_backend_error();
  11118. EXPECT_NE(0u, backend_error);
  11119. }
  11120. // Tests cert/key mismatch detection at the TLS context level
  11121. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11122. // Test that using mismatched cert/key causes connection failure.
  11123. // We verify this at the SSLClient level rather than through internal
  11124. // TLS API functions.
  11125. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11126. cli.enable_server_certificate_verification(false);
  11127. cli.set_connection_timeout(2);
  11128. // The mismatch should cause a connection or handshake error
  11129. auto res = cli.Get("/test");
  11130. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11131. // Either way, the request should fail
  11132. EXPECT_FALSE(res);
  11133. }
  11134. #endif
  11135. #if 0
  11136. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11137. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11138. ASSERT_TRUE(cli != nullptr);
  11139. cli->set_address_family(AF_INET6);
  11140. cli->set_interface("en0");
  11141. auto res = cli->Get("/get");
  11142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11143. ASSERT_EQ(StatusCode::OK_200, res->status);
  11144. }
  11145. #endif
  11146. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11147. #ifdef CPPHTTPLIB_SSL_ENABLED
  11148. void ClientCertPresent(
  11149. const std::string &client_cert_file,
  11150. const std::string &client_private_key_file,
  11151. const std::string &client_encrypted_private_key_pass = std::string()) {
  11152. using namespace httplib::tls;
  11153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11154. CLIENT_CA_CERT_DIR);
  11155. ASSERT_TRUE(svr.is_valid());
  11156. svr.Get("/test", [&](const Request &req, Response &res) {
  11157. res.set_content("test", "text/plain");
  11158. auto cert = req.peer_cert();
  11159. ASSERT_TRUE(static_cast<bool>(cert));
  11160. std::string common_name = cert.subject_cn();
  11161. EXPECT_EQ("Common Name", common_name);
  11162. });
  11163. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11164. auto se = detail::scope_exit([&] {
  11165. svr.stop();
  11166. t.join();
  11167. ASSERT_FALSE(svr.is_running());
  11168. });
  11169. svr.wait_until_ready();
  11170. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11171. client_encrypted_private_key_pass);
  11172. cli.enable_server_certificate_verification(false);
  11173. cli.set_connection_timeout(30);
  11174. auto res = cli.Get("/test");
  11175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11176. ASSERT_EQ(StatusCode::OK_200, res->status);
  11177. }
  11178. TEST(SSLClientServerTest, ClientCertPresent) {
  11179. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11180. }
  11181. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11182. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11183. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11184. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11185. }
  11186. // PEM memory-based constructor tests (works with all TLS backends)
  11187. void PemMemoryClientCertPresent(
  11188. const std::string &client_cert_file,
  11189. const std::string &client_private_key_file,
  11190. const std::string &client_encrypted_private_key_pass = std::string()) {
  11191. // Read PEM files into memory
  11192. std::string server_cert_pem, server_key_pem;
  11193. std::string client_ca_pem;
  11194. std::string client_cert_pem, client_key_pem;
  11195. read_file(SERVER_CERT_FILE, server_cert_pem);
  11196. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11197. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11198. read_file(client_cert_file, client_cert_pem);
  11199. read_file(client_private_key_file, client_key_pem);
  11200. // Create server with PEM memory
  11201. SSLServer::PemMemory server_pem = {
  11202. server_cert_pem.c_str(),
  11203. server_cert_pem.size(),
  11204. server_key_pem.c_str(),
  11205. server_key_pem.size(),
  11206. client_ca_pem.c_str(),
  11207. client_ca_pem.size(),
  11208. nullptr // no password for server key
  11209. };
  11210. SSLServer svr(server_pem);
  11211. ASSERT_TRUE(svr.is_valid());
  11212. svr.Get("/test", [&](const Request &, Response &res) {
  11213. res.set_content("test", "text/plain");
  11214. });
  11215. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11216. auto se = detail::scope_exit([&] {
  11217. svr.stop();
  11218. t.join();
  11219. ASSERT_FALSE(svr.is_running());
  11220. });
  11221. svr.wait_until_ready();
  11222. // Create client with PEM memory
  11223. const char *password = client_encrypted_private_key_pass.empty()
  11224. ? nullptr
  11225. : client_encrypted_private_key_pass.c_str();
  11226. SSLClient::PemMemory client_pem = {
  11227. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11228. client_key_pem.size(), password};
  11229. SSLClient cli(HOST, PORT, client_pem);
  11230. cli.enable_server_certificate_verification(false);
  11231. cli.set_connection_timeout(30);
  11232. auto res = cli.Get("/test");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. ASSERT_EQ(StatusCode::OK_200, res->status);
  11235. }
  11236. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11237. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11238. }
  11239. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11240. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11241. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11242. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11243. }
  11244. TEST(SSLClientServerTest, ClientCertMissing) {
  11245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11246. CLIENT_CA_CERT_DIR);
  11247. ASSERT_TRUE(svr.is_valid());
  11248. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11250. auto se = detail::scope_exit([&] {
  11251. svr.stop();
  11252. t.join();
  11253. ASSERT_FALSE(svr.is_running());
  11254. });
  11255. svr.wait_until_ready();
  11256. SSLClient cli(HOST, PORT);
  11257. cli.set_connection_timeout(30);
  11258. auto res = cli.Get("/test");
  11259. ASSERT_TRUE(!res);
  11260. // When client cert is missing and server requires it, connection fails
  11261. // Error type depends on backend implementation
  11262. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11263. res.error() == Error::SSLConnection);
  11264. // Verify backend error is captured
  11265. // Note: This test may have different error codes depending on the exact
  11266. // verification failure
  11267. EXPECT_NE(0UL, res.ssl_backend_error());
  11268. }
  11269. TEST(SSLClientServerTest, TrustDirOptional) {
  11270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11271. ASSERT_TRUE(svr.is_valid());
  11272. svr.Get("/test", [&](const Request &, Response &res) {
  11273. res.set_content("test", "text/plain");
  11274. });
  11275. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11276. auto se = detail::scope_exit([&] {
  11277. svr.stop();
  11278. t.join();
  11279. ASSERT_FALSE(svr.is_running());
  11280. });
  11281. svr.wait_until_ready();
  11282. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  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, SSLConnectTimeout) {
  11290. class NoListenSSLServer : public SSLServer {
  11291. public:
  11292. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11293. const char *client_ca_cert_file_path,
  11294. const char *client_ca_cert_dir_path = nullptr)
  11295. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11296. client_ca_cert_dir_path),
  11297. stop_(false) {}
  11298. std::atomic_bool stop_;
  11299. private:
  11300. bool process_and_close_socket(socket_t /*sock*/) override {
  11301. // Don't create SSL context
  11302. while (!stop_.load()) {
  11303. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11304. }
  11305. return true;
  11306. }
  11307. };
  11308. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11309. CLIENT_CA_CERT_FILE);
  11310. ASSERT_TRUE(svr.is_valid());
  11311. svr.Get("/test", [&](const Request &, Response &res) {
  11312. res.set_content("test", "text/plain");
  11313. });
  11314. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11315. auto se = detail::scope_exit([&] {
  11316. svr.stop_ = true;
  11317. svr.stop();
  11318. t.join();
  11319. ASSERT_FALSE(svr.is_running());
  11320. });
  11321. svr.wait_until_ready();
  11322. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11323. cli.enable_server_certificate_verification(false);
  11324. cli.set_connection_timeout(1);
  11325. auto res = cli.Get("/test");
  11326. ASSERT_TRUE(!res);
  11327. EXPECT_EQ(Error::SSLConnection, res.error());
  11328. // Timeout results in WantRead error code (maps to backend-specific value)
  11329. EXPECT_NE(0, res.ssl_error());
  11330. }
  11331. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11332. // Test SSLServer with client certificate verification using the standard
  11333. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11335. CLIENT_CA_CERT_DIR);
  11336. ASSERT_TRUE(svr.is_valid());
  11337. svr.Get("/test", [&](const Request &req, Response &res) {
  11338. res.set_content("test", "text/plain");
  11339. auto cert = req.peer_cert();
  11340. ASSERT_TRUE(static_cast<bool>(cert));
  11341. auto common_name = cert.subject_cn();
  11342. EXPECT_EQ("Common Name", common_name);
  11343. });
  11344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. });
  11350. svr.wait_until_ready();
  11351. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11352. cli.enable_server_certificate_verification(false);
  11353. cli.set_connection_timeout(30);
  11354. auto res = cli.Get("/test");
  11355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11356. ASSERT_EQ(StatusCode::OK_200, res->status);
  11357. }
  11358. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11359. // Verifies that wildcard matching and exact matching work consistently
  11360. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11361. using namespace httplib::tls;
  11362. // We need a running server to test against
  11363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11364. ASSERT_TRUE(svr.is_valid());
  11365. svr.Get("/test", [](const Request &, Response &res) {
  11366. res.set_content("ok", "text/plain");
  11367. });
  11368. thread t([&]() { svr.listen(HOST, PORT); });
  11369. auto se = detail::scope_exit([&] {
  11370. svr.stop();
  11371. t.join();
  11372. });
  11373. svr.wait_until_ready();
  11374. bool verify_callback_called = false;
  11375. bool verify_result_wrong = false;
  11376. SSLClient cli(HOST, PORT);
  11377. cli.enable_server_certificate_verification(true);
  11378. cli.set_ca_cert_path(CA_CERT_FILE);
  11379. cli.set_connection_timeout(5);
  11380. // Note: Test certificate has CN="Common Name", not "localhost"
  11381. bool verify_result_cn = false;
  11382. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11383. verify_callback_called = true;
  11384. if (!ctx.cert) return false;
  11385. // Test 1: "Common Name" should match (our test server cert CN)
  11386. verify_result_cn = ctx.check_hostname("Common Name");
  11387. // Test 2: wrong hostname should not match
  11388. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11389. return true; // Accept for the purpose of this test
  11390. });
  11391. auto res = cli.Get("/test");
  11392. // The request may succeed or fail depending on cert configuration
  11393. // but the callback should have been called
  11394. ASSERT_TRUE(verify_callback_called)
  11395. << "Verify callback should have been called";
  11396. // CN="Common Name" should match our test certificate
  11397. //
  11398. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11399. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11400. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11401. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11402. // <openssl/base.h>, which is included transitively when
  11403. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11404. #if defined(OPENSSL_IS_BORINGSSL)
  11405. EXPECT_FALSE(verify_result_cn)
  11406. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11407. #else
  11408. EXPECT_TRUE(verify_result_cn)
  11409. << "verify_hostname should match 'Common Name' (certificate CN)";
  11410. #endif
  11411. // Wrong hostname should not match
  11412. EXPECT_FALSE(verify_result_wrong)
  11413. << "verify_hostname should not match 'wronghost.example.com'";
  11414. }
  11415. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11416. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11417. // X509_check_ip behavior and must hold for every backend.
  11418. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11419. using namespace httplib::tls;
  11420. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11421. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11422. ASSERT_TRUE(svr.is_valid());
  11423. svr.Get("/test", [](const Request &, Response &res) {
  11424. res.set_content("ok", "text/plain");
  11425. });
  11426. thread t([&]() { svr.listen(HOST, PORT); });
  11427. auto se = detail::scope_exit([&] {
  11428. svr.stop();
  11429. t.join();
  11430. });
  11431. svr.wait_until_ready();
  11432. bool verify_callback_called = false;
  11433. bool ip_matched_via_cn = true;
  11434. SSLClient cli(HOST, PORT);
  11435. cli.enable_server_certificate_verification(true);
  11436. cli.set_ca_cert_path(CA_CERT_FILE);
  11437. cli.set_connection_timeout(5);
  11438. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11439. verify_callback_called = true;
  11440. if (!ctx.cert) return false;
  11441. // The IP appears only in the CN, so it must NOT be accepted.
  11442. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11443. return true; // Accept for the purpose of this test
  11444. });
  11445. cli.Get("/test");
  11446. ASSERT_TRUE(verify_callback_called)
  11447. << "Verify callback should have been called";
  11448. EXPECT_FALSE(ip_matched_via_cn)
  11449. << "An IP host must not be authenticated via the certificate CN";
  11450. }
  11451. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11452. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11453. using namespace httplib::tls;
  11454. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11455. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11456. ASSERT_TRUE(svr.is_valid());
  11457. svr.Get("/test", [](const Request &, Response &res) {
  11458. res.set_content("ok", "text/plain");
  11459. });
  11460. thread t([&]() { svr.listen(HOST, PORT); });
  11461. auto se = detail::scope_exit([&] {
  11462. svr.stop();
  11463. t.join();
  11464. });
  11465. svr.wait_until_ready();
  11466. bool verify_callback_called = false;
  11467. bool san_matched = false;
  11468. bool wrong_ipv6_matched = true;
  11469. bool cn_ipv6_matched = true;
  11470. SSLClient cli(HOST, PORT);
  11471. cli.enable_server_certificate_verification(true);
  11472. cli.set_ca_cert_path(CA_CERT_FILE);
  11473. cli.set_connection_timeout(5);
  11474. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11475. verify_callback_called = true;
  11476. if (!ctx.cert) return false;
  11477. // Matches the IPv6 iPAddress SAN.
  11478. san_matched = ctx.check_hostname("2001:db8::1");
  11479. // A different IPv6 address must not match.
  11480. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11481. // "::1" lives only in the CN, so it must not be accepted.
  11482. cn_ipv6_matched = ctx.check_hostname("::1");
  11483. return true; // Accept for the purpose of this test
  11484. });
  11485. cli.Get("/test");
  11486. ASSERT_TRUE(verify_callback_called)
  11487. << "Verify callback should have been called";
  11488. EXPECT_TRUE(san_matched)
  11489. << "verify_hostname should match an IPv6 iPAddress SAN";
  11490. EXPECT_FALSE(wrong_ipv6_matched)
  11491. << "verify_hostname should not match a non-matching IPv6 address";
  11492. EXPECT_FALSE(cn_ipv6_matched)
  11493. << "An IPv6 host must not be authenticated via the certificate CN";
  11494. }
  11495. #endif
  11496. // mbedTLS-specific callback constructor test
  11497. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11498. #ifdef CPPHTTPLIB_SSL_ENABLED
  11499. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11501. ASSERT_TRUE(svr.is_valid());
  11502. // Set up a handler to verify client certificate is present
  11503. bool client_cert_verified = false;
  11504. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11505. // Verify that client certificate was provided
  11506. client_cert_verified = true;
  11507. res.set_content("success", "text/plain");
  11508. });
  11509. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11510. auto se = detail::scope_exit([&] {
  11511. svr.stop();
  11512. t.join();
  11513. ASSERT_FALSE(svr.is_running());
  11514. });
  11515. svr.wait_until_ready();
  11516. // Client with certificate
  11517. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11518. cli.enable_server_certificate_verification(false);
  11519. cli.set_connection_timeout(30);
  11520. auto res = cli.Get("/test");
  11521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11522. ASSERT_EQ(StatusCode::OK_200, res->status);
  11523. ASSERT_TRUE(client_cert_verified);
  11524. EXPECT_EQ("success", res->body);
  11525. }
  11526. #endif
  11527. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11528. // backends
  11529. #ifdef CPPHTTPLIB_SSL_ENABLED
  11530. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11531. using namespace httplib::tls;
  11532. // Test that when client CA cert file is provided,
  11533. // the server properly requests and validates client certificates
  11534. // Create a server with client authentication
  11535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11536. ASSERT_TRUE(svr.is_valid());
  11537. bool handler_called = false;
  11538. svr.Get("/test", [&](const Request &req, Response &res) {
  11539. handler_called = true;
  11540. // Verify that a client certificate was provided
  11541. auto cert = req.peer_cert();
  11542. ASSERT_TRUE(static_cast<bool>(cert));
  11543. // Get the issuer name
  11544. std::string issuer_str = cert.issuer_name();
  11545. ASSERT_FALSE(issuer_str.empty());
  11546. // The client certificate should be issued by our test CA
  11547. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11548. res.set_content("authenticated", "text/plain");
  11549. });
  11550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11551. auto se = detail::scope_exit([&] {
  11552. svr.stop();
  11553. t.join();
  11554. ASSERT_FALSE(svr.is_running());
  11555. });
  11556. svr.wait_until_ready();
  11557. // Connect with a client certificate issued by the CA
  11558. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11559. cli.enable_server_certificate_verification(false);
  11560. cli.set_connection_timeout(30);
  11561. auto res = cli.Get("/test");
  11562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11563. ASSERT_EQ(StatusCode::OK_200, res->status);
  11564. ASSERT_TRUE(handler_called);
  11565. EXPECT_EQ("authenticated", res->body);
  11566. }
  11567. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11568. using namespace httplib::tls;
  11569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11570. ASSERT_TRUE(svr.is_valid());
  11571. svr.Get("/test", [](const Request &, Response &res) {
  11572. res.set_content("ok", "text/plain");
  11573. });
  11574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11575. auto se = detail::scope_exit([&] {
  11576. svr.stop();
  11577. t.join();
  11578. });
  11579. svr.wait_until_ready();
  11580. SSLClient cli(HOST, PORT);
  11581. cli.enable_server_certificate_verification(false);
  11582. cli.set_connection_timeout(30);
  11583. bool cert_checked = false;
  11584. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11585. if (ctx.cert) {
  11586. auto sans = ctx.sans();
  11587. // Test certificate may or may not have SANs - just verify the API
  11588. // works If SANs exist, verify the types are valid
  11589. for (const auto &san : sans) {
  11590. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11591. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11592. san.type == SanType::OTHER);
  11593. EXPECT_FALSE(san.value.empty());
  11594. }
  11595. cert_checked = true;
  11596. }
  11597. return true;
  11598. });
  11599. auto res = cli.Get("/test");
  11600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11601. EXPECT_TRUE(cert_checked);
  11602. }
  11603. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11604. using namespace httplib::tls;
  11605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11606. ASSERT_TRUE(svr.is_valid());
  11607. svr.Get("/test", [](const Request &, Response &res) {
  11608. res.set_content("ok", "text/plain");
  11609. });
  11610. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11611. auto se = detail::scope_exit([&] {
  11612. svr.stop();
  11613. t.join();
  11614. });
  11615. svr.wait_until_ready();
  11616. SSLClient cli(HOST, PORT);
  11617. cli.enable_server_certificate_verification(false);
  11618. cli.set_connection_timeout(30);
  11619. bool validity_checked = false;
  11620. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11621. if (ctx.cert) {
  11622. time_t not_before = 0, not_after = 0;
  11623. bool result = ctx.validity(not_before, not_after);
  11624. EXPECT_TRUE(result);
  11625. // Verify that not_before < now < not_after for a valid cert
  11626. time_t now = time(nullptr);
  11627. EXPECT_LT(not_before, now);
  11628. EXPECT_GT(not_after, now);
  11629. validity_checked = true;
  11630. }
  11631. return true;
  11632. });
  11633. auto res = cli.Get("/test");
  11634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11635. EXPECT_TRUE(validity_checked);
  11636. }
  11637. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11638. using namespace httplib::tls;
  11639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11640. ASSERT_TRUE(svr.is_valid());
  11641. svr.Get("/test", [](const Request &, Response &res) {
  11642. res.set_content("ok", "text/plain");
  11643. });
  11644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11645. auto se = detail::scope_exit([&] {
  11646. svr.stop();
  11647. t.join();
  11648. });
  11649. svr.wait_until_ready();
  11650. SSLClient cli(HOST, PORT);
  11651. cli.enable_server_certificate_verification(false);
  11652. cli.set_connection_timeout(30);
  11653. bool serial_checked = false;
  11654. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11655. if (ctx.cert) {
  11656. std::string serial = ctx.serial();
  11657. EXPECT_FALSE(serial.empty());
  11658. // Serial should be a hex string
  11659. for (char c : serial) {
  11660. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11661. (c >= 'a' && c <= 'f'));
  11662. }
  11663. serial_checked = true;
  11664. }
  11665. return true;
  11666. });
  11667. auto res = cli.Get("/test");
  11668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11669. EXPECT_TRUE(serial_checked);
  11670. }
  11671. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11672. // Test 1: Valid CA file - no error should be recorded
  11673. {
  11674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11675. CLIENT_CA_CERT_FILE);
  11676. ASSERT_TRUE(svr.is_valid());
  11677. // With valid setup, last_ssl_error should be 0
  11678. EXPECT_EQ(0, svr.ssl_last_error());
  11679. }
  11680. // Test 2: Invalid CA file content
  11681. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11682. {
  11683. // Create a temporary file with completely invalid content
  11684. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11685. {
  11686. std::ofstream ofs(temp_invalid_ca);
  11687. ofs << "This is not a certificate file at all\n";
  11688. ofs << "Just plain text content\n";
  11689. }
  11690. // Create server with invalid CA file
  11691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11692. // Clean up temporary file
  11693. std::remove(temp_invalid_ca);
  11694. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11695. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11696. // Note: SSL_CTX_load_verify_locations typically fails first,
  11697. // but our error handling code path is still exercised
  11698. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11699. }
  11700. }
  11701. TEST(VerifyCallbackTest, VerifyContextFields) {
  11702. using namespace httplib::tls;
  11703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11704. ASSERT_TRUE(svr.is_valid());
  11705. svr.Get("/test", [](const Request &, Response &res) {
  11706. res.set_content("ok", "text/plain");
  11707. });
  11708. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. });
  11713. svr.wait_until_ready();
  11714. SSLClient cli(HOST, PORT);
  11715. cli.enable_server_certificate_verification(false);
  11716. cli.set_connection_timeout(30);
  11717. int callback_count = 0;
  11718. bool saw_leaf_cert = false;
  11719. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11720. if (ctx.cert) {
  11721. callback_count++;
  11722. // We should see at least one certificate (the leaf)
  11723. std::string cn = ctx.subject_cn();
  11724. if (!cn.empty()) { saw_leaf_cert = true; }
  11725. // Verify context fields are populated
  11726. EXPECT_NE(ctx.session, nullptr);
  11727. EXPECT_GE(ctx.depth, 0);
  11728. }
  11729. return true;
  11730. });
  11731. auto res = cli.Get("/test");
  11732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11733. EXPECT_GT(callback_count, 0);
  11734. EXPECT_TRUE(saw_leaf_cert);
  11735. }
  11736. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11737. using httplib::tls::TlsError;
  11738. // Test that verify_error_to_string returns empty for success
  11739. std::string success_str = TlsError::verify_error_to_string(0);
  11740. EXPECT_TRUE(success_str.empty());
  11741. // Test that verify_error_to_string returns non-empty for error codes
  11742. // Using a common error code (certificate expired)
  11743. std::string error_str =
  11744. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11745. EXPECT_FALSE(error_str.empty());
  11746. }
  11747. TEST(SessionVerifierTest, CertificateAccepted) {
  11748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11749. ASSERT_TRUE(svr.is_valid());
  11750. svr.Get("/test", [](const Request &, Response &res) {
  11751. res.set_content("ok", "text/plain");
  11752. });
  11753. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11754. auto se = detail::scope_exit([&] {
  11755. svr.stop();
  11756. t.join();
  11757. });
  11758. svr.wait_until_ready();
  11759. SSLClient cli(HOST, PORT);
  11760. cli.enable_server_certificate_verification(false);
  11761. cli.set_connection_timeout(30);
  11762. bool callback_called = false;
  11763. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11764. EXPECT_NE(session, nullptr);
  11765. callback_called = true;
  11766. return SSLVerifierResponse::CertificateAccepted;
  11767. });
  11768. auto res = cli.Get("/test");
  11769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11770. EXPECT_EQ(200, res->status);
  11771. EXPECT_TRUE(callback_called);
  11772. }
  11773. TEST(SessionVerifierTest, CertificateRejected) {
  11774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11775. ASSERT_TRUE(svr.is_valid());
  11776. svr.Get("/test", [](const Request &, Response &res) {
  11777. res.set_content("ok", "text/plain");
  11778. });
  11779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. t.join();
  11783. });
  11784. svr.wait_until_ready();
  11785. SSLClient cli(HOST, PORT);
  11786. cli.enable_server_certificate_verification(false);
  11787. cli.set_connection_timeout(30);
  11788. bool callback_called = false;
  11789. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11790. EXPECT_NE(session, nullptr);
  11791. callback_called = true;
  11792. return SSLVerifierResponse::CertificateRejected;
  11793. });
  11794. auto res = cli.Get("/test");
  11795. EXPECT_FALSE(res);
  11796. EXPECT_TRUE(callback_called);
  11797. }
  11798. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11800. ASSERT_TRUE(svr.is_valid());
  11801. svr.Get("/test", [](const Request &, Response &res) {
  11802. res.set_content("ok", "text/plain");
  11803. });
  11804. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11805. auto se = detail::scope_exit([&] {
  11806. svr.stop();
  11807. t.join();
  11808. });
  11809. svr.wait_until_ready();
  11810. // NoDecisionMade with verification disabled should succeed (no default check)
  11811. SSLClient cli(HOST, PORT);
  11812. cli.enable_server_certificate_verification(false);
  11813. cli.set_connection_timeout(30);
  11814. bool callback_called = false;
  11815. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11816. EXPECT_NE(session, nullptr);
  11817. callback_called = true;
  11818. return SSLVerifierResponse::NoDecisionMade;
  11819. });
  11820. auto res = cli.Get("/test");
  11821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11822. EXPECT_EQ(200, res->status);
  11823. EXPECT_TRUE(callback_called);
  11824. }
  11825. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11827. ASSERT_TRUE(svr.is_valid());
  11828. svr.Get("/test", [](const Request &, Response &res) {
  11829. res.set_content("ok", "text/plain");
  11830. });
  11831. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11832. auto se = detail::scope_exit([&] {
  11833. svr.stop();
  11834. t.join();
  11835. });
  11836. svr.wait_until_ready();
  11837. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11838. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11839. // so we only check that the request fails, not whether the callback was
  11840. // called.
  11841. SSLClient cli(HOST, PORT);
  11842. cli.enable_server_certificate_verification(true);
  11843. cli.set_connection_timeout(30);
  11844. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11845. EXPECT_NE(session, nullptr);
  11846. return SSLVerifierResponse::NoDecisionMade;
  11847. });
  11848. auto res = cli.Get("/test");
  11849. EXPECT_FALSE(res);
  11850. }
  11851. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11852. // Test SSL server using PemMemory constructor with client CA certificates
  11853. // Read PEM files
  11854. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11855. read_file(SERVER_CERT_FILE, server_cert_pem);
  11856. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11857. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11858. // Create SSLServer with PemMemory constructor including client CA
  11859. SSLServer::PemMemory server_pem = {
  11860. server_cert_pem.c_str(),
  11861. server_cert_pem.size(),
  11862. server_key_pem.c_str(),
  11863. server_key_pem.size(),
  11864. client_ca_pem.c_str(),
  11865. client_ca_pem.size(),
  11866. nullptr // no password for server key
  11867. };
  11868. SSLServer svr(server_pem);
  11869. ASSERT_TRUE(svr.is_valid());
  11870. // No SSL error should be recorded for valid setup
  11871. EXPECT_EQ(0, svr.ssl_last_error());
  11872. // Set up server endpoints
  11873. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11874. res.set_content("ok", "text/plain");
  11875. });
  11876. // Start server in a thread
  11877. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11878. svr.wait_until_ready();
  11879. // Connect with client certificate (using constructor with paths)
  11880. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11881. cli.enable_server_certificate_verification(false);
  11882. auto res = cli.Get("/test-pem-ca");
  11883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11884. EXPECT_EQ(200, res->status);
  11885. EXPECT_EQ("ok", res->body);
  11886. svr.stop();
  11887. server_thread.join();
  11888. }
  11889. #endif
  11890. #ifdef _WIN32
  11891. TEST(CleanupTest, WSACleanup) {
  11892. int ret = WSACleanup();
  11893. ASSERT_EQ(0, ret);
  11894. }
  11895. #endif
  11896. #ifndef CPPHTTPLIB_SSL_ENABLED
  11897. TEST(NoSSLSupport, SimpleInterface) {
  11898. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11899. }
  11900. #endif
  11901. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11902. TEST(InvalidScheme, SimpleInterface) {
  11903. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11904. }
  11905. #endif
  11906. TEST(NoScheme, SimpleInterface) {
  11907. Client cli("yahoo.com:80");
  11908. ASSERT_TRUE(cli.is_valid());
  11909. }
  11910. TEST(SendAPI, SimpleInterface_Online) {
  11911. Client cli("http://yahoo.com");
  11912. Request req;
  11913. req.method = "GET";
  11914. req.path = "/";
  11915. auto res = cli.send(req);
  11916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11917. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11918. }
  11919. TEST(SendAPI, WithParamsInRequest) {
  11920. Server svr;
  11921. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11922. EXPECT_TRUE(req.has_param("test"));
  11923. EXPECT_EQ("test_value", req.get_param_value("test"));
  11924. });
  11925. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. t.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. });
  11931. svr.wait_until_ready();
  11932. Client cli(HOST, PORT);
  11933. {
  11934. Request req;
  11935. req.method = "GET";
  11936. req.path = "/";
  11937. req.params.emplace("test", "test_value");
  11938. auto res = cli.send(req);
  11939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11940. }
  11941. {
  11942. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. }
  11945. }
  11946. TEST(ClientImplMethods, GetSocketTest) {
  11947. httplib::Server svr;
  11948. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11949. res.status = StatusCode::OK_200;
  11950. });
  11951. auto port = svr.bind_to_any_port("127.0.0.1");
  11952. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. thread.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. {
  11960. httplib::Client cli("127.0.0.1", port);
  11961. cli.set_keep_alive(true);
  11962. // Use the behavior of cpp-httplib of opening the connection
  11963. // only when the first request happens. If that changes,
  11964. // this test would be obsolete.
  11965. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11966. // This also implicitly tests the server. But other tests would fail much
  11967. // earlier than this one to be considered.
  11968. auto res = cli.Get("/");
  11969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11970. EXPECT_EQ(StatusCode::OK_200, res->status);
  11971. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11972. }
  11973. }
  11974. #ifdef CPPHTTPLIB_SSL_ENABLED
  11975. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11976. Client cli("http://yahoo.com");
  11977. auto res = cli.Get("/");
  11978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11979. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11980. cli.set_follow_location(true);
  11981. res = cli.Get("/");
  11982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11983. EXPECT_EQ(StatusCode::OK_200, res->status);
  11984. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11985. }
  11986. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11987. Client cli("https://yahoo.com");
  11988. auto res = cli.Get("/");
  11989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11990. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11991. cli.set_follow_location(true);
  11992. res = cli.Get("/");
  11993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11994. EXPECT_EQ(StatusCode::OK_200, res->status);
  11995. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11996. }
  11997. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11998. Client cli("https://yahoo.com");
  11999. auto res = cli.Get("/");
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. ASSERT_FALSE(!res);
  12002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12003. ASSERT_FALSE(res == nullptr);
  12004. ASSERT_TRUE(res != nullptr);
  12005. EXPECT_EQ(Error::Success, res.error());
  12006. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12007. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12008. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12009. cli.set_follow_location(true);
  12010. res = cli.Get("/");
  12011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12012. EXPECT_EQ(Error::Success, res.error());
  12013. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12014. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12015. EXPECT_EQ(StatusCode::OK_200, res->status);
  12016. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12017. }
  12018. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12019. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12020. Client cli("https://cdnjs.cloudflare.com");
  12021. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12022. Headers{{"Accept-Encoding", "br"}});
  12023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12024. EXPECT_EQ(StatusCode::OK_200, res->status);
  12025. EXPECT_EQ(287630U, res->body.size());
  12026. EXPECT_EQ("application/javascript; charset=utf-8",
  12027. res->get_header_value("Content-Type"));
  12028. }
  12029. #endif
  12030. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12031. #undef REDIR_HOST // Silence compiler warning
  12032. #define REDIR_HOST "https://httpbingo.org"
  12033. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12034. Client cli(REDIR_HOST);
  12035. cli.set_follow_location(true);
  12036. auto res =
  12037. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. }
  12041. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12042. Client cli(REDIR_HOST);
  12043. cli.set_follow_location(true);
  12044. Params params;
  12045. params.emplace("url", "http://example.com");
  12046. params.emplace("status_code", "302");
  12047. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. EXPECT_EQ(StatusCode::OK_200, res->status);
  12050. }
  12051. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12052. Client cli(REDIR_HOST);
  12053. cli.set_follow_location(true);
  12054. Params params;
  12055. params.emplace("url", "http://example.com");
  12056. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12058. EXPECT_EQ(StatusCode::OK_200, res->status);
  12059. }
  12060. TEST(HttpToHttpsRedirectTest, CertFile) {
  12061. auto ssl_port = PORT + 1;
  12062. Server svr;
  12063. ASSERT_TRUE(svr.is_valid());
  12064. svr.Get("/index", [&](const Request &, Response &res) {
  12065. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12066. "/index");
  12067. svr.stop();
  12068. });
  12069. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12070. ASSERT_TRUE(ssl_svr.is_valid());
  12071. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12072. res.set_content("test", "text/plain");
  12073. ssl_svr.stop();
  12074. });
  12075. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12076. thread t2 =
  12077. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12078. auto se = detail::scope_exit([&] {
  12079. t2.join();
  12080. t.join();
  12081. ASSERT_FALSE(svr.is_running());
  12082. });
  12083. svr.wait_until_ready();
  12084. ssl_svr.wait_until_ready();
  12085. Client cli("127.0.0.1", PORT);
  12086. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12087. cli.enable_server_certificate_verification(true);
  12088. cli.set_follow_location(true);
  12089. cli.set_connection_timeout(30);
  12090. auto res = cli.Get("/index");
  12091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12092. ASSERT_EQ(StatusCode::OK_200, res->status);
  12093. }
  12094. TEST(SSLClientRedirectTest, CertFile) {
  12095. auto ssl_port = PORT + 1;
  12096. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12097. ASSERT_TRUE(ssl_svr1.is_valid());
  12098. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12099. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12100. "/index");
  12101. ssl_svr1.stop();
  12102. });
  12103. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12104. ASSERT_TRUE(ssl_svr2.is_valid());
  12105. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12106. res.set_content("test", "text/plain");
  12107. ssl_svr2.stop();
  12108. });
  12109. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12110. thread t2 =
  12111. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12112. auto se = detail::scope_exit([&] {
  12113. t2.join();
  12114. t.join();
  12115. ASSERT_FALSE(ssl_svr1.is_running());
  12116. });
  12117. ssl_svr1.wait_until_ready();
  12118. ssl_svr2.wait_until_ready();
  12119. SSLClient cli("127.0.0.1", PORT);
  12120. std::string cert;
  12121. read_file(SERVER_CERT2_FILE, cert);
  12122. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12123. cli.enable_server_certificate_verification(true);
  12124. cli.set_follow_location(true);
  12125. cli.set_connection_timeout(30);
  12126. auto res = cli.Get("/index");
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. ASSERT_EQ(StatusCode::OK_200, res->status);
  12129. }
  12130. #endif
  12131. #ifdef CPPHTTPLIB_SSL_ENABLED
  12132. // Test that set_ca_cert_store() skips system certs (consistent with
  12133. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12134. // should be trusted - system certs should NOT be loaded.
  12135. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12136. // Load a specific cert that is NOT a system CA cert
  12137. std::string cert;
  12138. read_file(SERVER_CERT2_FILE, cert);
  12139. SSLClient cli("google.com");
  12140. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12141. cli.enable_server_certificate_verification(true);
  12142. // This should FAIL because:
  12143. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12144. // 2. System certs should NOT be loaded when custom store is set
  12145. // If system certs WERE loaded, this would succeed
  12146. auto res = cli.Get("/");
  12147. ASSERT_FALSE(res);
  12148. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12149. }
  12150. // Same as above, but through the native store handle path. Regression test:
  12151. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12152. // merged system certs into the user-provided store.
  12153. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12154. std::string cert;
  12155. read_file(SERVER_CERT2_FILE, cert);
  12156. SSLClient cli("google.com");
  12157. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12158. cli.enable_server_certificate_verification(true);
  12159. auto res = cli.Get("/");
  12160. ASSERT_FALSE(res);
  12161. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12162. }
  12163. // A custom store set via the native handle must still verify a server whose
  12164. // cert it does contain.
  12165. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12166. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12167. ASSERT_TRUE(svr.is_valid());
  12168. svr.Get("/test", [&](const Request &, Response &res) {
  12169. res.set_content("test", "text/plain");
  12170. });
  12171. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12172. auto se = detail::scope_exit([&] {
  12173. svr.stop();
  12174. t.join();
  12175. ASSERT_FALSE(svr.is_running());
  12176. });
  12177. svr.wait_until_ready();
  12178. SSLClient cli("127.0.0.1", PORT);
  12179. std::string cert;
  12180. read_file(SERVER_CERT2_FILE, cert);
  12181. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12182. cli.enable_server_certificate_verification(true);
  12183. cli.set_connection_timeout(30);
  12184. auto res = cli.Get("/test");
  12185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12186. ASSERT_EQ(StatusCode::OK_200, res->status);
  12187. }
  12188. // CA certs loaded through the universal Client must be transferred to the
  12189. // client created internally for following an HTTPS redirect. Regression test:
  12190. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12191. // the CA data for redirect transfer.
  12192. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12193. auto ssl_port = PORT + 1;
  12194. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12195. ASSERT_TRUE(ssl_svr1.is_valid());
  12196. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12197. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12198. "/index");
  12199. });
  12200. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12201. ASSERT_TRUE(ssl_svr2.is_valid());
  12202. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12203. res.set_content("test", "text/plain");
  12204. });
  12205. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12206. thread t2 =
  12207. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12208. auto se = detail::scope_exit([&] {
  12209. ssl_svr2.stop();
  12210. ssl_svr1.stop();
  12211. t2.join();
  12212. t.join();
  12213. ASSERT_FALSE(ssl_svr1.is_running());
  12214. });
  12215. ssl_svr1.wait_until_ready();
  12216. ssl_svr2.wait_until_ready();
  12217. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12218. std::string cert;
  12219. read_file(SERVER_CERT2_FILE, cert);
  12220. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12221. cli.enable_server_certificate_verification(true);
  12222. cli.set_follow_location(true);
  12223. cli.set_connection_timeout(30);
  12224. auto res = cli.Get("/index");
  12225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12226. ASSERT_EQ(StatusCode::OK_200, res->status);
  12227. }
  12228. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12229. // so a host signed by a system CA verifies even though a custom CA is set
  12230. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12231. std::string cert;
  12232. read_file(SERVER_CERT2_FILE, cert);
  12233. SSLClient cli("google.com");
  12234. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12235. cli.enable_system_ca(true);
  12236. cli.enable_server_certificate_verification(true);
  12237. auto res = cli.Get("/");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12240. }
  12241. // The custom CA remains effective when combined with the system CA
  12242. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12243. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12244. ASSERT_TRUE(svr.is_valid());
  12245. svr.Get("/test", [&](const Request &, Response &res) {
  12246. res.set_content("test", "text/plain");
  12247. });
  12248. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12249. auto se = detail::scope_exit([&] {
  12250. svr.stop();
  12251. t.join();
  12252. ASSERT_FALSE(svr.is_running());
  12253. });
  12254. svr.wait_until_ready();
  12255. SSLClient cli("127.0.0.1", PORT);
  12256. std::string cert;
  12257. read_file(SERVER_CERT2_FILE, cert);
  12258. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12259. cli.enable_system_ca(true);
  12260. cli.enable_server_certificate_verification(true);
  12261. cli.set_connection_timeout(30);
  12262. auto res = cli.Get("/test");
  12263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12264. ASSERT_EQ(StatusCode::OK_200, res->status);
  12265. }
  12266. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12267. // skip chain verification entirely (only the certificate identity was
  12268. // checked), so a server presenting an untrusted certificate with a matching
  12269. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12270. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12271. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12272. ASSERT_TRUE(svr.is_valid());
  12273. svr.Get("/test", [&](const Request &, Response &res) {
  12274. res.set_content("test", "text/plain");
  12275. });
  12276. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12277. auto se = detail::scope_exit([&] {
  12278. svr.stop();
  12279. t.join();
  12280. ASSERT_FALSE(svr.is_running());
  12281. });
  12282. svr.wait_until_ready();
  12283. SSLClient cli("127.0.0.1", PORT);
  12284. std::string cert;
  12285. // A trusted CA that did not sign the server certificate. The server cert
  12286. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12287. // this connection.
  12288. read_file(CLIENT_CA_CERT_FILE, cert);
  12289. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12290. cli.enable_server_certificate_verification(true);
  12291. cli.set_connection_timeout(30);
  12292. auto res = cli.Get("/test");
  12293. ASSERT_FALSE(res);
  12294. }
  12295. // enable_system_ca(false) prevents system CA loading entirely
  12296. TEST(SSLClientTest, DisableSystemCa_Online) {
  12297. SSLClient cli("google.com");
  12298. cli.enable_system_ca(false);
  12299. cli.enable_server_certificate_verification(true);
  12300. auto res = cli.Get("/");
  12301. ASSERT_FALSE(res);
  12302. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12303. // itself when the CA chain is empty
  12304. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12305. res.error() == Error::SSLConnection);
  12306. }
  12307. // The universal Client forwards enable_system_ca()
  12308. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12309. std::string cert;
  12310. read_file(SERVER_CERT2_FILE, cert);
  12311. Client cli("https://google.com");
  12312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12313. cli.enable_system_ca(true);
  12314. cli.enable_server_certificate_verification(true);
  12315. auto res = cli.Get("/");
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12318. }
  12319. // The system CA policy must carry over to the client created internally for
  12320. // following a cross-host HTTPS redirect
  12321. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12322. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12323. ASSERT_TRUE(svr.is_valid());
  12324. svr.Get("/index", [&](const Request &, Response &res) {
  12325. res.set_redirect("https://www.google.com/");
  12326. });
  12327. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12328. auto se = detail::scope_exit([&] {
  12329. svr.stop();
  12330. t.join();
  12331. ASSERT_FALSE(svr.is_running());
  12332. });
  12333. svr.wait_until_ready();
  12334. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12335. std::string cert;
  12336. read_file(SERVER_CERT2_FILE, cert);
  12337. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12338. cli.enable_system_ca(true);
  12339. cli.enable_server_certificate_verification(true);
  12340. cli.set_follow_location(true);
  12341. cli.set_connection_timeout(30);
  12342. // Receiving any response proves the redirect client completed the TLS
  12343. // handshake with a system-CA-signed host
  12344. auto res = cli.Get("/index");
  12345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12346. }
  12347. TEST(MultipartFormDataTest, LargeData) {
  12348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12349. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12350. const ContentReader &content_reader) {
  12351. if (req.is_multipart_form_data()) {
  12352. std::vector<FormData> items;
  12353. content_reader(
  12354. [&](const FormData &file) {
  12355. items.push_back(file);
  12356. return true;
  12357. },
  12358. [&](const char *data, size_t data_length) {
  12359. items.back().content.append(data, data_length);
  12360. return true;
  12361. });
  12362. EXPECT_TRUE(std::string(items[0].name) == "document");
  12363. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12364. EXPECT_TRUE(items[0].filename == "2MB_data");
  12365. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12366. EXPECT_TRUE(items[1].name == "hello");
  12367. EXPECT_TRUE(items[1].content == "world");
  12368. EXPECT_TRUE(items[1].filename == "");
  12369. EXPECT_TRUE(items[1].content_type == "");
  12370. } else {
  12371. std::string body;
  12372. content_reader([&](const char *data, size_t data_length) {
  12373. body.append(data, data_length);
  12374. return true;
  12375. });
  12376. }
  12377. });
  12378. auto port = svr.bind_to_any_port(HOST);
  12379. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12380. auto se = detail::scope_exit([&] {
  12381. svr.stop();
  12382. t.join();
  12383. ASSERT_FALSE(svr.is_running());
  12384. });
  12385. svr.wait_until_ready();
  12386. {
  12387. std::string data(1024 * 1024 * 2, '.');
  12388. std::stringstream buffer;
  12389. buffer << data;
  12390. SSLClient cli(HOST, port);
  12391. cli.enable_server_certificate_verification(false);
  12392. UploadFormDataItems items{
  12393. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12394. {"hello", "world", "", ""},
  12395. };
  12396. auto res = cli.Post("/post", items);
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. ASSERT_EQ(StatusCode::OK_200, res->status);
  12399. }
  12400. }
  12401. TEST(MultipartFormDataTest, DataProviderItems) {
  12402. std::random_device seed_gen;
  12403. std::mt19937 random(seed_gen());
  12404. std::string rand1;
  12405. rand1.resize(1000);
  12406. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12407. std::string rand2;
  12408. rand2.resize(3000);
  12409. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12411. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12412. const ContentReader &content_reader) {
  12413. ASSERT_FALSE(req.is_multipart_form_data());
  12414. std::string body;
  12415. content_reader([&](const char *data, size_t data_length) {
  12416. body.append(data, data_length);
  12417. return true;
  12418. });
  12419. EXPECT_EQ(body, "");
  12420. });
  12421. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12422. const ContentReader &content_reader) {
  12423. ASSERT_TRUE(req.is_multipart_form_data());
  12424. std::vector<FormData> items;
  12425. content_reader(
  12426. [&](const FormData &file) {
  12427. items.push_back(file);
  12428. return true;
  12429. },
  12430. [&](const char *data, size_t data_length) {
  12431. items.back().content.append(data, data_length);
  12432. return true;
  12433. });
  12434. ASSERT_TRUE(items.size() == 2);
  12435. EXPECT_EQ(std::string(items[0].name), "name1");
  12436. EXPECT_EQ(items[0].content, "Testing123");
  12437. EXPECT_EQ(items[0].filename, "filename1");
  12438. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12439. EXPECT_EQ(items[1].name, "name2");
  12440. EXPECT_EQ(items[1].content, "Testing456");
  12441. EXPECT_EQ(items[1].filename, "");
  12442. EXPECT_EQ(items[1].content_type, "");
  12443. });
  12444. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12445. const ContentReader &content_reader) {
  12446. ASSERT_TRUE(req.is_multipart_form_data());
  12447. std::vector<FormData> items;
  12448. content_reader(
  12449. [&](const FormData &file) {
  12450. items.push_back(file);
  12451. return true;
  12452. },
  12453. [&](const char *data, size_t data_length) {
  12454. items.back().content.append(data, data_length);
  12455. return true;
  12456. });
  12457. ASSERT_TRUE(items.size() == 2);
  12458. EXPECT_EQ(items[0].name, "name3");
  12459. EXPECT_EQ(items[0].content, rand1);
  12460. EXPECT_EQ(items[0].filename, "filename3");
  12461. EXPECT_EQ(items[0].content_type, "");
  12462. EXPECT_EQ(items[1].name, "name4");
  12463. EXPECT_EQ(items[1].content, rand2);
  12464. EXPECT_EQ(items[1].filename, "filename4");
  12465. EXPECT_EQ(items[1].content_type, "");
  12466. });
  12467. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12468. const ContentReader &content_reader) {
  12469. ASSERT_TRUE(req.is_multipart_form_data());
  12470. std::vector<FormData> items;
  12471. content_reader(
  12472. [&](const FormData &file) {
  12473. items.push_back(file);
  12474. return true;
  12475. },
  12476. [&](const char *data, size_t data_length) {
  12477. items.back().content.append(data, data_length);
  12478. return true;
  12479. });
  12480. ASSERT_TRUE(items.size() == 4);
  12481. EXPECT_EQ(std::string(items[0].name), "name1");
  12482. EXPECT_EQ(items[0].content, "Testing123");
  12483. EXPECT_EQ(items[0].filename, "filename1");
  12484. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12485. EXPECT_EQ(items[1].name, "name2");
  12486. EXPECT_EQ(items[1].content, "Testing456");
  12487. EXPECT_EQ(items[1].filename, "");
  12488. EXPECT_EQ(items[1].content_type, "");
  12489. EXPECT_EQ(items[2].name, "name3");
  12490. EXPECT_EQ(items[2].content, rand1);
  12491. EXPECT_EQ(items[2].filename, "filename3");
  12492. EXPECT_EQ(items[2].content_type, "");
  12493. EXPECT_EQ(items[3].name, "name4");
  12494. EXPECT_EQ(items[3].content, rand2);
  12495. EXPECT_EQ(items[3].filename, "filename4");
  12496. EXPECT_EQ(items[3].content_type, "");
  12497. });
  12498. auto port = svr.bind_to_any_port("localhost");
  12499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. t.join();
  12503. ASSERT_FALSE(svr.is_running());
  12504. });
  12505. svr.wait_until_ready();
  12506. {
  12507. SSLClient cli("localhost", port);
  12508. cli.enable_server_certificate_verification(false);
  12509. UploadFormDataItems items{
  12510. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12511. {"name2", "Testing456", "", ""}, // not a file
  12512. };
  12513. {
  12514. auto res = cli.Post("/post-none", {}, {}, {});
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. ASSERT_EQ(StatusCode::OK_200, res->status);
  12517. }
  12518. FormDataProviderItems providers;
  12519. {
  12520. auto res =
  12521. cli.Post("/post-items", {}, items, providers); // empty providers
  12522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12523. ASSERT_EQ(StatusCode::OK_200, res->status);
  12524. }
  12525. providers.push_back({"name3",
  12526. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12527. // test the offset is given correctly at each step
  12528. if (!offset)
  12529. sink.os.write(rand1.data(), 30);
  12530. else if (offset == 30)
  12531. sink.os.write(rand1.data() + 30, 300);
  12532. else if (offset == 330)
  12533. sink.os.write(rand1.data() + 330, 670);
  12534. else if (offset == rand1.size())
  12535. sink.done();
  12536. return true;
  12537. },
  12538. "filename3",
  12539. {}});
  12540. providers.push_back({"name4",
  12541. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12542. // test the offset is given correctly at each step
  12543. if (!offset)
  12544. sink.os.write(rand2.data(), 2000);
  12545. else if (offset == 2000)
  12546. sink.os.write(rand2.data() + 2000, 1);
  12547. else if (offset == 2001)
  12548. sink.os.write(rand2.data() + 2001, 999);
  12549. else if (offset == rand2.size())
  12550. sink.done();
  12551. return true;
  12552. },
  12553. "filename4",
  12554. {}});
  12555. {
  12556. auto res = cli.Post("/post-providers", {}, {}, providers);
  12557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12558. ASSERT_EQ(StatusCode::OK_200, res->status);
  12559. }
  12560. {
  12561. auto res = cli.Post("/post-both", {}, items, providers);
  12562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12563. ASSERT_EQ(StatusCode::OK_200, res->status);
  12564. }
  12565. }
  12566. }
  12567. TEST(MultipartFormDataTest, BadHeader) {
  12568. Server svr;
  12569. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12570. res.set_content("ok", "text/plain");
  12571. });
  12572. thread t = thread([&] { svr.listen(HOST, PORT); });
  12573. auto se = detail::scope_exit([&] {
  12574. svr.stop();
  12575. t.join();
  12576. ASSERT_FALSE(svr.is_running());
  12577. });
  12578. svr.wait_until_ready();
  12579. const std::string body =
  12580. "This is the preamble. It is to be ignored, though it\r\n"
  12581. "is a handy place for composition agents to include an\r\n"
  12582. "explanatory note to non-MIME conformant readers.\r\n"
  12583. "\r\n"
  12584. "\r\n"
  12585. "--simple boundary\r\n"
  12586. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12587. ": BAD...\r\n"
  12588. "\r\n"
  12589. "value1\r\n"
  12590. "--simple boundary\r\n"
  12591. "Content-Disposition: form-data; name=\"field2\"; "
  12592. "filename=\"example.txt\"\r\n"
  12593. "\r\n"
  12594. "value2\r\n"
  12595. "--simple boundary--\r\n"
  12596. "This is the epilogue. It is also to be ignored.\r\n";
  12597. std::string content_type =
  12598. R"(multipart/form-data; boundary="simple boundary")";
  12599. Client cli(HOST, PORT);
  12600. auto res = cli.Post("/post", body, content_type.c_str());
  12601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12603. }
  12604. TEST(MultipartFormDataTest, WithPreamble) {
  12605. Server svr;
  12606. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12607. res.set_content("ok", "text/plain");
  12608. });
  12609. thread t = thread([&] { svr.listen(HOST, PORT); });
  12610. auto se = detail::scope_exit([&] {
  12611. svr.stop();
  12612. t.join();
  12613. ASSERT_FALSE(svr.is_running());
  12614. });
  12615. svr.wait_until_ready();
  12616. const std::string body =
  12617. "This is the preamble. It is to be ignored, though it\r\n"
  12618. "is a handy place for composition agents to include an\r\n"
  12619. "explanatory note to non-MIME conformant readers.\r\n"
  12620. "\r\n"
  12621. "\r\n"
  12622. "--simple boundary\r\n"
  12623. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12624. "\r\n"
  12625. "value1\r\n"
  12626. "--simple boundary\r\n"
  12627. "Content-Disposition: form-data; name=\"field2\"; "
  12628. "filename=\"example.txt\"\r\n"
  12629. "\r\n"
  12630. "value2\r\n"
  12631. "--simple boundary--\r\n"
  12632. "This is the epilogue. It is also to be ignored.\r\n";
  12633. std::string content_type =
  12634. R"(multipart/form-data; boundary="simple boundary")";
  12635. Client cli(HOST, PORT);
  12636. auto res = cli.Post("/post", body, content_type.c_str());
  12637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12638. EXPECT_EQ(StatusCode::OK_200, res->status);
  12639. }
  12640. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12642. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12643. const ContentReader &content_reader) {
  12644. if (req.is_multipart_form_data()) {
  12645. std::vector<FormData> items;
  12646. content_reader(
  12647. [&](const FormData &file) {
  12648. items.push_back(file);
  12649. return true;
  12650. },
  12651. [&](const char *data, size_t data_length) {
  12652. items.back().content.append(data, data_length);
  12653. return true;
  12654. });
  12655. EXPECT_TRUE(std::string(items[0].name) == "document");
  12656. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12657. EXPECT_TRUE(items[0].filename == "2MB_data");
  12658. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12659. EXPECT_TRUE(items[1].name == "hello");
  12660. EXPECT_TRUE(items[1].content == "world");
  12661. EXPECT_TRUE(items[1].filename == "");
  12662. EXPECT_TRUE(items[1].content_type == "");
  12663. } else {
  12664. std::string body;
  12665. content_reader([&](const char *data, size_t data_length) {
  12666. body.append(data, data_length);
  12667. return true;
  12668. });
  12669. }
  12670. });
  12671. auto port = svr.bind_to_any_port("localhost");
  12672. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12673. auto se = detail::scope_exit([&] {
  12674. svr.stop();
  12675. t.join();
  12676. ASSERT_FALSE(svr.is_running());
  12677. });
  12678. svr.wait_until_ready();
  12679. {
  12680. std::string data(1024 * 1024 * 2, '.');
  12681. std::stringstream buffer;
  12682. buffer << data;
  12683. SSLClient cli("localhost", port);
  12684. cli.enable_server_certificate_verification(false);
  12685. UploadFormDataItems items{
  12686. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12687. {"hello", "world", "", ""},
  12688. };
  12689. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12691. ASSERT_EQ(StatusCode::OK_200, res->status);
  12692. }
  12693. }
  12694. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12695. std::string data(1024 * 1024 * 2, '&');
  12696. std::stringstream buffer;
  12697. buffer << data;
  12698. Client cli("https://localhost:8080");
  12699. UploadFormDataItems items{
  12700. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12701. {"hello", "world", "", ""},
  12702. };
  12703. for (const char &c : " \t\r\n") {
  12704. auto res =
  12705. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12706. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12707. ASSERT_FALSE(res);
  12708. }
  12709. }
  12710. TEST(MultipartFormDataTest, PutFormData) {
  12711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12712. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12713. const ContentReader &content_reader) {
  12714. if (req.is_multipart_form_data()) {
  12715. std::vector<FormData> items;
  12716. content_reader(
  12717. [&](const FormData &file) {
  12718. items.push_back(file);
  12719. return true;
  12720. },
  12721. [&](const char *data, size_t data_length) {
  12722. items.back().content.append(data, data_length);
  12723. return true;
  12724. });
  12725. EXPECT_TRUE(std::string(items[0].name) == "document");
  12726. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12727. EXPECT_TRUE(items[0].filename == "2MB_data");
  12728. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12729. EXPECT_TRUE(items[1].name == "hello");
  12730. EXPECT_TRUE(items[1].content == "world");
  12731. EXPECT_TRUE(items[1].filename == "");
  12732. EXPECT_TRUE(items[1].content_type == "");
  12733. } else {
  12734. std::string body;
  12735. content_reader([&](const char *data, size_t data_length) {
  12736. body.append(data, data_length);
  12737. return true;
  12738. });
  12739. }
  12740. });
  12741. auto port = svr.bind_to_any_port("localhost");
  12742. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12743. auto se = detail::scope_exit([&] {
  12744. svr.stop();
  12745. t.join();
  12746. ASSERT_FALSE(svr.is_running());
  12747. });
  12748. svr.wait_until_ready();
  12749. {
  12750. std::string data(1024 * 1024 * 2, '&');
  12751. std::stringstream buffer;
  12752. buffer << data;
  12753. SSLClient cli("localhost", port);
  12754. cli.enable_server_certificate_verification(false);
  12755. UploadFormDataItems items{
  12756. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12757. {"hello", "world", "", ""},
  12758. };
  12759. auto res = cli.Put("/put", items);
  12760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12761. ASSERT_EQ(StatusCode::OK_200, res->status);
  12762. }
  12763. }
  12764. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. svr.Put("/put_customboundary",
  12767. [&](const Request &req, const Response & /*res*/,
  12768. const ContentReader &content_reader) {
  12769. if (req.is_multipart_form_data()) {
  12770. std::vector<FormData> items;
  12771. content_reader(
  12772. [&](const FormData &file) {
  12773. items.push_back(file);
  12774. return true;
  12775. },
  12776. [&](const char *data, size_t data_length) {
  12777. items.back().content.append(data, data_length);
  12778. return true;
  12779. });
  12780. EXPECT_TRUE(std::string(items[0].name) == "document");
  12781. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12782. EXPECT_TRUE(items[0].filename == "2MB_data");
  12783. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12784. EXPECT_TRUE(items[1].name == "hello");
  12785. EXPECT_TRUE(items[1].content == "world");
  12786. EXPECT_TRUE(items[1].filename == "");
  12787. EXPECT_TRUE(items[1].content_type == "");
  12788. } else {
  12789. std::string body;
  12790. content_reader([&](const char *data, size_t data_length) {
  12791. body.append(data, data_length);
  12792. return true;
  12793. });
  12794. }
  12795. });
  12796. auto port = svr.bind_to_any_port("localhost");
  12797. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12798. auto se = detail::scope_exit([&] {
  12799. svr.stop();
  12800. t.join();
  12801. ASSERT_FALSE(svr.is_running());
  12802. });
  12803. svr.wait_until_ready();
  12804. {
  12805. std::string data(1024 * 1024 * 2, '&');
  12806. std::stringstream buffer;
  12807. buffer << data;
  12808. SSLClient cli("localhost", port);
  12809. cli.enable_server_certificate_verification(false);
  12810. UploadFormDataItems items{
  12811. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12812. {"hello", "world", "", ""},
  12813. };
  12814. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12816. ASSERT_EQ(StatusCode::OK_200, res->status);
  12817. }
  12818. }
  12819. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12820. std::string data(1024 * 1024 * 2, '&');
  12821. std::stringstream buffer;
  12822. buffer << data;
  12823. Client cli("https://localhost:8080");
  12824. cli.enable_server_certificate_verification(false);
  12825. UploadFormDataItems items{
  12826. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12827. {"hello", "world", "", ""},
  12828. };
  12829. for (const char &c : " \t\r\n") {
  12830. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12831. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12832. ASSERT_FALSE(res);
  12833. }
  12834. }
  12835. TEST(MultipartFormDataTest, AlternateFilename) {
  12836. auto handled = false;
  12837. Server svr;
  12838. svr.Post("/test", [&](const Request &req, Response &res) {
  12839. ASSERT_EQ(2u, req.form.files.size());
  12840. ASSERT_EQ(1u, req.form.fields.size());
  12841. // Test files
  12842. const auto &file1 = req.form.get_file("file1");
  12843. ASSERT_EQ("file1", file1.name);
  12844. ASSERT_EQ("A.txt", file1.filename);
  12845. ASSERT_EQ("text/plain", file1.content_type);
  12846. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12847. const auto &file2 = req.form.get_file("file2");
  12848. ASSERT_EQ("file2", file2.name);
  12849. ASSERT_EQ("a.html", file2.filename);
  12850. ASSERT_EQ("text/html", file2.content_type);
  12851. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12852. file2.content);
  12853. // Test text field
  12854. const auto &text = req.form.get_field("text");
  12855. ASSERT_EQ("text default", text);
  12856. res.set_content("ok", "text/plain");
  12857. handled = true;
  12858. });
  12859. thread t = thread([&] { svr.listen(HOST, PORT); });
  12860. auto se = detail::scope_exit([&] {
  12861. svr.stop();
  12862. t.join();
  12863. ASSERT_FALSE(svr.is_running());
  12864. ASSERT_TRUE(handled);
  12865. });
  12866. svr.wait_until_ready();
  12867. auto req = "POST /test HTTP/1.1\r\n"
  12868. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12869. "Content-Length: 399\r\n"
  12870. "\r\n"
  12871. "----------\r\n"
  12872. "Content-Disposition: form-data; name=\"text\"\r\n"
  12873. "\r\n"
  12874. "text default\r\n"
  12875. "----------\r\n"
  12876. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12877. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12878. "Content-Type: text/plain\r\n"
  12879. "\r\n"
  12880. "Content of a.txt.\r\n"
  12881. "\r\n"
  12882. "----------\r\n"
  12883. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12884. "\"a.html\"\r\n"
  12885. "Content-Type: text/html\r\n"
  12886. "\r\n"
  12887. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12888. "\r\n"
  12889. "------------\r\n";
  12890. ASSERT_TRUE(send_request(1, req));
  12891. }
  12892. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12893. auto handled = false;
  12894. Server svr;
  12895. svr.Post("/test", [&](const Request &req, Response &res) {
  12896. // Case-insensitive "utf-8''" prefix with a long value
  12897. const auto &file = req.form.get_file("file1");
  12898. ASSERT_EQ("file1", file.name);
  12899. // 8000 chars exercises both the Content-Disposition parser and the
  12900. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12901. // Prior to the fix, std::regex_match on this header would cause O(N)
  12902. // stack recursion in libstdc++, leading to SIGSEGV.
  12903. std::string expected_filename(8000, 'A');
  12904. ASSERT_EQ(expected_filename, file.filename);
  12905. res.set_content("ok", "text/plain");
  12906. handled = true;
  12907. });
  12908. thread t = thread([&] { svr.listen(HOST, PORT); });
  12909. auto se = detail::scope_exit([&] {
  12910. svr.stop();
  12911. t.join();
  12912. ASSERT_FALSE(svr.is_running());
  12913. ASSERT_TRUE(handled);
  12914. });
  12915. svr.wait_until_ready();
  12916. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12917. // Regression test for GHSA-qq6v-r583-3h69
  12918. std::string long_filename(8000, 'A');
  12919. std::string body = "----------\r\n"
  12920. "Content-Disposition: form-data; name=\"file1\"; "
  12921. "filename*=\"Utf-8''" +
  12922. long_filename +
  12923. "\"\r\n"
  12924. "\r\n"
  12925. "hello\r\n"
  12926. "------------\r\n";
  12927. auto req = "POST /test HTTP/1.1\r\n"
  12928. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12929. "Content-Length: " +
  12930. std::to_string(body.size()) + "\r\n\r\n" + body;
  12931. ASSERT_TRUE(send_request(1, req));
  12932. }
  12933. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12934. auto handled = false;
  12935. Server svr;
  12936. svr.Post("/test", [&](const Request &req, Response &) {
  12937. ASSERT_EQ(2u, req.form.fields.size());
  12938. const auto &text1 = req.form.get_field("text1");
  12939. ASSERT_EQ("text1", text1);
  12940. const auto &text2 = req.form.get_field("text2");
  12941. ASSERT_EQ("text2", text2);
  12942. handled = true;
  12943. });
  12944. thread t = thread([&] { svr.listen(HOST, PORT); });
  12945. auto se = detail::scope_exit([&] {
  12946. svr.stop();
  12947. t.join();
  12948. ASSERT_FALSE(svr.is_running());
  12949. ASSERT_TRUE(handled);
  12950. });
  12951. svr.wait_until_ready();
  12952. auto req = "POST /test HTTP/1.1\r\n"
  12953. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12954. "Content-Length: 146\r\n"
  12955. "\r\n----------\r\n"
  12956. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12957. "\r\n"
  12958. "text1"
  12959. "\r\n----------\r\n"
  12960. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12961. "\r\n"
  12962. "text2"
  12963. "\r\n------------";
  12964. std::string response;
  12965. ASSERT_TRUE(send_request(1, req, &response));
  12966. ASSERT_EQ("200", response.substr(9, 3));
  12967. }
  12968. TEST(MultipartFormDataTest, ContentLength) {
  12969. auto handled = false;
  12970. Server svr;
  12971. svr.Post("/test", [&](const Request &req, Response &) {
  12972. ASSERT_EQ(2u, req.form.fields.size());
  12973. const auto &text1 = req.form.get_field("text1");
  12974. ASSERT_EQ("text1", text1);
  12975. const auto &text2 = req.form.get_field("text2");
  12976. ASSERT_EQ("text2", text2);
  12977. handled = true;
  12978. });
  12979. thread t = thread([&] { svr.listen(HOST, PORT); });
  12980. auto se = detail::scope_exit([&] {
  12981. svr.stop();
  12982. t.join();
  12983. ASSERT_FALSE(svr.is_running());
  12984. ASSERT_TRUE(handled);
  12985. });
  12986. svr.wait_until_ready();
  12987. auto req = "POST /test HTTP/1.1\r\n"
  12988. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12989. "Content-Length: 167\r\n"
  12990. "\r\n----------\r\n"
  12991. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12992. "Content-Length: 5\r\n"
  12993. "\r\n"
  12994. "text1"
  12995. "\r\n----------\r\n"
  12996. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12997. "\r\n"
  12998. "text2"
  12999. "\r\n------------\r\n";
  13000. std::string response;
  13001. ASSERT_TRUE(send_request(1, req, &response));
  13002. ASSERT_EQ("200", response.substr(9, 3));
  13003. }
  13004. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13005. auto handled = false;
  13006. Server svr;
  13007. svr.Post("/test", [&](const Request &req, Response &) {
  13008. ASSERT_EQ(2u, req.form.fields.size());
  13009. const auto &text1 = req.form.get_field("text1");
  13010. ASSERT_EQ("text1", text1);
  13011. // TODO: Add header access for text fields if needed
  13012. const auto &text2 = req.form.get_field("text2");
  13013. ASSERT_EQ("text2", text2);
  13014. // TODO: Header access for text fields needs to be implemented
  13015. // auto &headers = it->second.headers;
  13016. // ASSERT_EQ(3U, headers.size());
  13017. // auto custom_header = headers.find("x-whatever");
  13018. // ASSERT_TRUE(custom_header != headers.end());
  13019. // ASSERT_NE("customvalue", custom_header->second);
  13020. // ASSERT_EQ("CustomValue", custom_header->second);
  13021. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13022. handled = true;
  13023. });
  13024. thread t = thread([&] { svr.listen(HOST, PORT); });
  13025. auto se = detail::scope_exit([&] {
  13026. svr.stop();
  13027. t.join();
  13028. ASSERT_FALSE(svr.is_running());
  13029. ASSERT_TRUE(handled);
  13030. });
  13031. svr.wait_until_ready();
  13032. auto req = "POST /test HTTP/1.1\r\n"
  13033. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13034. "Content-Length: 232\r\n"
  13035. "\r\n----------\r\n"
  13036. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13037. "Content-Length: 5\r\n"
  13038. "X-Test: 1\r\n"
  13039. "\r\n"
  13040. "text1"
  13041. "\r\n----------\r\n"
  13042. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13043. "Content-Type: text/plain\r\n"
  13044. "X-Whatever: CustomValue\r\n"
  13045. "\r\n"
  13046. "text2"
  13047. "\r\n------------\r\n"
  13048. "That should be disregarded. Not even read";
  13049. std::string response;
  13050. ASSERT_TRUE(send_request(1, req, &response));
  13051. ASSERT_EQ("200", response.substr(9, 3));
  13052. }
  13053. TEST(MultipartFormDataTest, LargeHeader) {
  13054. auto handled = false;
  13055. Server svr;
  13056. svr.Post("/test", [&](const Request &req, Response &) {
  13057. ASSERT_EQ(1u, req.form.fields.size());
  13058. const auto &text = req.form.get_field("name1");
  13059. ASSERT_EQ("text1", text);
  13060. handled = true;
  13061. });
  13062. thread t = thread([&] { svr.listen(HOST, PORT); });
  13063. auto se = detail::scope_exit([&] {
  13064. svr.stop();
  13065. t.join();
  13066. ASSERT_FALSE(svr.is_running());
  13067. ASSERT_TRUE(handled);
  13068. });
  13069. svr.wait_until_ready();
  13070. auto boundary = std::string("cpp-httplib-multipart-data");
  13071. std::string content = "--" + boundary +
  13072. "\r\n"
  13073. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13074. "\r\n"
  13075. "text1\r\n"
  13076. "--" +
  13077. boundary + "--\r\n";
  13078. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13079. "Content-Type: multipart/form-data;boundary=" +
  13080. boundary +
  13081. "\r\n"
  13082. "Content-Length: " +
  13083. std::to_string(content.size()) +
  13084. "\r\n"
  13085. "Dummy-Header: ";
  13086. std::string header_suffix = "\r\n"
  13087. "\r\n";
  13088. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13089. size_t header_dummy_size =
  13090. read_buff_size -
  13091. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13092. auto header_dummy = std::string(header_dummy_size, '@');
  13093. auto req = header_prefix + header_dummy + header_suffix + content;
  13094. std::string response;
  13095. ASSERT_TRUE(send_request(1, req, &response));
  13096. ASSERT_EQ("200", response.substr(9, 3));
  13097. }
  13098. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13099. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13100. // (not chunked Transfer-Encoding) after the streaming refactor.
  13101. auto handled = false;
  13102. Server svr;
  13103. svr.Post("/upload", [&](const Request &req, Response &res) {
  13104. auto cl_it = req.headers.find("Content-Length");
  13105. EXPECT_TRUE(cl_it != req.headers.end());
  13106. auto te_it = req.headers.find("Transfer-Encoding");
  13107. EXPECT_TRUE(te_it == req.headers.end());
  13108. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13109. res.set_content("ok", "text/plain");
  13110. handled = true;
  13111. });
  13112. auto port = svr.bind_to_any_port(HOST);
  13113. auto t = thread([&] { svr.listen_after_bind(); });
  13114. auto se = detail::scope_exit([&] {
  13115. svr.stop();
  13116. t.join();
  13117. ASSERT_FALSE(svr.is_running());
  13118. ASSERT_TRUE(handled);
  13119. });
  13120. svr.wait_until_ready();
  13121. UploadFormDataItems items = {
  13122. {"field1", "hello", "", "text/plain"},
  13123. {"file1", "world", "test.txt", "application/octet-stream"},
  13124. };
  13125. Client cli(HOST, port);
  13126. auto res = cli.Post("/upload", {}, items);
  13127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13128. EXPECT_EQ(StatusCode::OK_200, res->status);
  13129. }
  13130. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13131. // Verify that make_multipart_content_provider coalesces many small segments
  13132. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13133. constexpr size_t kItemCount = 1000;
  13134. UploadFormDataItems items;
  13135. items.reserve(kItemCount);
  13136. for (size_t i = 0; i < kItemCount; i++) {
  13137. items.push_back(
  13138. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13139. }
  13140. const std::string boundary = "----test-boundary";
  13141. auto content_length = detail::get_multipart_content_length(items, boundary);
  13142. auto provider = detail::make_multipart_content_provider(items, boundary);
  13143. // Drive the provider the same way write_content_with_progress does
  13144. size_t write_count = 0;
  13145. size_t total_bytes = 0;
  13146. DataSink sink;
  13147. size_t offset = 0;
  13148. sink.write = [&](const char *d, size_t l) -> bool {
  13149. (void)d;
  13150. write_count++;
  13151. total_bytes += l;
  13152. offset += l;
  13153. return true;
  13154. };
  13155. sink.is_writable = []() -> bool { return true; };
  13156. while (offset < content_length) {
  13157. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13158. }
  13159. EXPECT_EQ(content_length, total_bytes);
  13160. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13161. // With buffering into 64KB blocks, write_count should be much smaller.
  13162. auto segment_count = 3 * kItemCount + 1;
  13163. EXPECT_LT(write_count, segment_count / 10);
  13164. }
  13165. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13166. // Integration test: send many UploadFormDataItems and verify the server
  13167. // receives all of them correctly (#2410).
  13168. constexpr size_t kItemCount = 500;
  13169. auto handled = false;
  13170. Server svr;
  13171. svr.Post("/upload", [&](const Request &req, Response &res) {
  13172. EXPECT_EQ(kItemCount, req.form.fields.size());
  13173. for (size_t i = 0; i < kItemCount; i++) {
  13174. auto key = "field" + std::to_string(i);
  13175. auto val = "value" + std::to_string(i);
  13176. auto it = req.form.fields.find(key);
  13177. if (it != req.form.fields.end()) {
  13178. EXPECT_EQ(val, it->second.content);
  13179. } else {
  13180. ADD_FAILURE() << "Missing field: " << key;
  13181. }
  13182. }
  13183. res.set_content("ok", "text/plain");
  13184. handled = true;
  13185. });
  13186. auto port = svr.bind_to_any_port(HOST);
  13187. auto t = thread([&] { svr.listen_after_bind(); });
  13188. auto se = detail::scope_exit([&] {
  13189. svr.stop();
  13190. t.join();
  13191. ASSERT_FALSE(svr.is_running());
  13192. ASSERT_TRUE(handled);
  13193. });
  13194. svr.wait_until_ready();
  13195. UploadFormDataItems items;
  13196. items.reserve(kItemCount);
  13197. for (size_t i = 0; i < kItemCount; i++) {
  13198. items.push_back(
  13199. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13200. }
  13201. Client cli(HOST, port);
  13202. auto res = cli.Post("/upload", items);
  13203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13204. EXPECT_EQ(StatusCode::OK_200, res->status);
  13205. }
  13206. TEST(MultipartFormDataTest, MakeFileProvider) {
  13207. // Verify make_file_provider sends a file's contents correctly.
  13208. const std::string file_content(4096, 'Z');
  13209. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13210. {
  13211. std::ofstream ofs(tmp_path, std::ios::binary);
  13212. ofs.write(file_content.data(),
  13213. static_cast<std::streamsize>(file_content.size()));
  13214. }
  13215. auto handled = false;
  13216. Server svr;
  13217. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13218. const ContentReader &content_reader) {
  13219. ASSERT_TRUE(req.is_multipart_form_data());
  13220. std::vector<FormData> items;
  13221. content_reader(
  13222. [&](const FormData &file) {
  13223. items.push_back(file);
  13224. return true;
  13225. },
  13226. [&](const char *data, size_t data_length) {
  13227. items.back().content.append(data, data_length);
  13228. return true;
  13229. });
  13230. ASSERT_EQ(1u, items.size());
  13231. EXPECT_EQ("myfile", items[0].name);
  13232. EXPECT_EQ("data.bin", items[0].filename);
  13233. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13234. EXPECT_EQ(file_content, items[0].content);
  13235. handled = true;
  13236. });
  13237. auto port = svr.bind_to_any_port(HOST);
  13238. auto t = thread([&] { svr.listen_after_bind(); });
  13239. auto se = detail::scope_exit([&] {
  13240. svr.stop();
  13241. t.join();
  13242. ASSERT_FALSE(svr.is_running());
  13243. ASSERT_TRUE(handled);
  13244. std::remove(tmp_path.c_str());
  13245. });
  13246. svr.wait_until_ready();
  13247. FormDataProviderItems providers;
  13248. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13249. "application/octet-stream"));
  13250. Client cli(HOST, port);
  13251. auto res = cli.Post("/upload", {}, {}, providers);
  13252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13253. EXPECT_EQ(StatusCode::OK_200, res->status);
  13254. }
  13255. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13256. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13257. // (100) headers is rejected with a 400 Bad Request response.
  13258. Server svr;
  13259. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13260. res.set_content("ok", "text/plain");
  13261. });
  13262. thread t = thread([&] { svr.listen(HOST, PORT); });
  13263. auto se = detail::scope_exit([&] {
  13264. svr.stop();
  13265. t.join();
  13266. ASSERT_FALSE(svr.is_running());
  13267. });
  13268. svr.wait_until_ready();
  13269. // Build a multipart part with 101 custom headers (exceeding
  13270. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13271. std::stringstream body;
  13272. body << "--simpleboundary\r\n"
  13273. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13274. for (int i = 0; i < 101; i++) {
  13275. body << "X-Custom-Header-" << i << ": value\r\n";
  13276. }
  13277. body << "\r\n"
  13278. << "value1\r\n"
  13279. << "--simpleboundary--\r\n";
  13280. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13281. Client cli(HOST, PORT);
  13282. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13284. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13285. }
  13286. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13287. // A body that never contains the declared boundary must not be accumulated
  13288. // while the parser waits for it. Buffering it would also make every read
  13289. // rescan everything seen so far, which is quadratic in the body size.
  13290. Server svr;
  13291. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13292. res.set_content("ok", "text/plain");
  13293. });
  13294. auto port = svr.bind_to_any_port(HOST);
  13295. thread t = thread([&] { svr.listen_after_bind(); });
  13296. auto se = detail::scope_exit([&] {
  13297. svr.stop();
  13298. t.join();
  13299. ASSERT_FALSE(svr.is_running());
  13300. });
  13301. svr.wait_until_ready();
  13302. Client cli(HOST, port);
  13303. cli.set_read_timeout(60, 0);
  13304. cli.set_write_timeout(60, 0);
  13305. // '-' is the worst case: it matches the first character of the boundary, so
  13306. // every position has to be checked against it.
  13307. auto post_dashes = [&](size_t size) {
  13308. const std::string body(size, '-');
  13309. auto start = std::chrono::steady_clock::now();
  13310. auto res =
  13311. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13312. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13313. std::chrono::steady_clock::now() - start)
  13314. .count();
  13315. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13316. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13317. return ms;
  13318. };
  13319. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13320. // Windows.
  13321. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13322. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13323. // Comparing the two sizes rather than checking an absolute duration keeps
  13324. // this meaningful across build types and CI load, both of which move the
  13325. // absolute numbers by more than an order of magnitude. Four times the bytes
  13326. // costs about four times the time when parsing is linear, and about sixteen
  13327. // times when the body is buffered and rescanned.
  13328. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13329. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13330. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13331. << "ms, which suggests the body is being buffered and rescanned";
  13332. }
  13333. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13334. // A boundary can only be followed by CRLF or by "--", so anything else is
  13335. // malformed no matter what comes next. The parser must say so right away
  13336. // instead of buffering the rest of the declared body.
  13337. Server svr;
  13338. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. auto port = svr.bind_to_any_port(HOST);
  13342. thread t = thread([&] { svr.listen_after_bind(); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13350. // buffers instead of failing would still be waiting for the remaining bytes.
  13351. const std::string body = "--zzzz\r\n"
  13352. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13353. "\r\n"
  13354. "text1"
  13355. "\r\n--zzzzXX";
  13356. const std::string req = "POST /post HTTP/1.1\r\n"
  13357. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13358. "Content-Length: 1048576\r\n"
  13359. "\r\n" +
  13360. body;
  13361. std::string response;
  13362. ASSERT_TRUE(send_request(3, req, &response, port));
  13363. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13364. EXPECT_EQ("400", response.substr(9, 3));
  13365. }
  13366. // Posts a multipart body split into two writes, so that the server sees the
  13367. // split at whatever offset the caller chose, and expects the single "text1"
  13368. // field to come through.
  13369. static void expect_split_multipart_ok(const std::string &body1,
  13370. const std::string &body2) {
  13371. auto handled = false;
  13372. Server svr;
  13373. svr.Post("/post", [&](const Request &req, Response &) {
  13374. EXPECT_EQ(1u, req.form.fields.size());
  13375. EXPECT_EQ("text1", req.form.get_field("text1"));
  13376. handled = true;
  13377. });
  13378. auto port = svr.bind_to_any_port(HOST);
  13379. thread t = thread([&] { svr.listen_after_bind(); });
  13380. auto se = detail::scope_exit([&] {
  13381. svr.stop();
  13382. t.join();
  13383. ASSERT_FALSE(svr.is_running());
  13384. ASSERT_TRUE(handled);
  13385. });
  13386. svr.wait_until_ready();
  13387. // "Connection: close" makes the server close once it has answered, so the
  13388. // response drain ends immediately instead of idling until the read timeout.
  13389. const std::string head =
  13390. "POST /post HTTP/1.1\r\n"
  13391. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13392. "Connection: close\r\n"
  13393. "Content-Length: " +
  13394. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13395. std::string response;
  13396. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13397. ASSERT_GE(response.size(), 12u) << "no response";
  13398. EXPECT_EQ("200", response.substr(9, 3));
  13399. }
  13400. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13401. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13402. // ignored, including when it does not arrive in the same read as the
  13403. // close-delimiter itself.
  13404. expect_split_multipart_ok("--zzzz\r\n"
  13405. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13406. "\r\n"
  13407. "text1"
  13408. "\r\n--zzzz--",
  13409. "\r\nthis epilogue must be ignored\r\n");
  13410. }
  13411. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13412. // The initial boundary may be preceded by a preamble of any length and may
  13413. // straddle a read boundary. Discarding data while waiting for it must not
  13414. // throw away a partial boundary sitting at the end of the buffer.
  13415. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13416. "zz\r\n"
  13417. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13418. "\r\n"
  13419. "text1"
  13420. "\r\n--zzzz--\r\n");
  13421. }
  13422. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13423. // The received boundary was only checked for being non-empty, so it could be
  13424. // as long as a header is allowed to be. The parser scans the body for
  13425. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13426. // costs a nearly full comparison at nearly every position, making the
  13427. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13428. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13429. Server svr;
  13430. svr.Post("/post", [](const Request &req, Response &res) {
  13431. EXPECT_EQ(1u, req.form.fields.size());
  13432. EXPECT_EQ("text1", req.form.get_field("text1"));
  13433. res.set_content("ok", "text/plain");
  13434. });
  13435. auto port = svr.bind_to_any_port(HOST);
  13436. thread t = thread([&] { svr.listen_after_bind(); });
  13437. auto se = detail::scope_exit([&] {
  13438. svr.stop();
  13439. t.join();
  13440. ASSERT_FALSE(svr.is_running());
  13441. });
  13442. svr.wait_until_ready();
  13443. Client cli(HOST, port);
  13444. auto post_with_boundary_of_length = [&](size_t len) {
  13445. const std::string boundary(len, 'a');
  13446. const std::string body =
  13447. "--" + boundary +
  13448. "\r\n"
  13449. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13450. "\r\n"
  13451. "text1"
  13452. "\r\n--" +
  13453. boundary + "--\r\n";
  13454. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13455. };
  13456. auto res = post_with_boundary_of_length(70);
  13457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13458. EXPECT_EQ(StatusCode::OK_200, res->status);
  13459. res = post_with_boundary_of_length(71);
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13462. }
  13463. TEST(MakeFileBodyTest, Basic) {
  13464. const std::string file_content(4096, 'Z');
  13465. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13466. {
  13467. std::ofstream ofs(tmp_path, std::ios::binary);
  13468. ofs.write(file_content.data(),
  13469. static_cast<std::streamsize>(file_content.size()));
  13470. }
  13471. auto handled = false;
  13472. Server svr;
  13473. svr.Post("/upload", [&](const Request &req, Response &res) {
  13474. EXPECT_EQ(file_content, req.body);
  13475. handled = true;
  13476. res.status = StatusCode::OK_200;
  13477. });
  13478. auto port = svr.bind_to_any_port(HOST);
  13479. auto t = thread([&] { svr.listen_after_bind(); });
  13480. auto se = detail::scope_exit([&] {
  13481. svr.stop();
  13482. t.join();
  13483. ASSERT_FALSE(svr.is_running());
  13484. ASSERT_TRUE(handled);
  13485. std::remove(tmp_path.c_str());
  13486. });
  13487. svr.wait_until_ready();
  13488. auto fb = make_file_body(tmp_path);
  13489. ASSERT_GT(fb.first, 0u);
  13490. Client cli(HOST, port);
  13491. auto res =
  13492. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. EXPECT_EQ(StatusCode::OK_200, res->status);
  13495. }
  13496. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13497. static constexpr unsigned int number_of_tasks{1000000};
  13498. std::atomic_uint count{0};
  13499. std::unique_ptr<TaskQueue> task_queue{
  13500. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13501. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13502. auto queued = task_queue->enqueue(
  13503. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13504. EXPECT_TRUE(queued);
  13505. }
  13506. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13507. task_queue->shutdown();
  13508. #else
  13509. EXPECT_NO_THROW(task_queue->shutdown());
  13510. #endif
  13511. EXPECT_EQ(number_of_tasks, count.load());
  13512. }
  13513. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13514. static constexpr unsigned int number_of_tasks{1000000};
  13515. static constexpr unsigned int qlimit{2};
  13516. unsigned int queued_count{0};
  13517. std::atomic_uint count{0};
  13518. std::unique_ptr<TaskQueue> task_queue{
  13519. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13520. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13521. if (task_queue->enqueue(
  13522. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13523. queued_count++;
  13524. }
  13525. }
  13526. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13527. task_queue->shutdown();
  13528. #else
  13529. EXPECT_NO_THROW(task_queue->shutdown());
  13530. #endif
  13531. EXPECT_EQ(queued_count, count.load());
  13532. EXPECT_TRUE(queued_count <= number_of_tasks);
  13533. EXPECT_TRUE(queued_count >= qlimit);
  13534. }
  13535. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13536. // Use a short idle timeout so a dynamic thread spawns, times out and
  13537. // exits during the test, and the pool keeps working afterwards.
  13538. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13539. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13540. /*idle_timeout_sec=*/1}};
  13541. std::atomic_uint count{0};
  13542. std::condition_variable cv;
  13543. std::mutex mtx;
  13544. bool release = false;
  13545. // Block the base thread so the second task spawns a dynamic thread.
  13546. EXPECT_TRUE(task_queue->enqueue([&] {
  13547. std::unique_lock<std::mutex> lock(mtx);
  13548. while (!release) {
  13549. cv.wait(lock);
  13550. }
  13551. count++;
  13552. }));
  13553. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13554. // Let the dynamic thread finish its task and exceed the idle timeout.
  13555. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13556. {
  13557. std::unique_lock<std::mutex> lock(mtx);
  13558. release = true;
  13559. }
  13560. cv.notify_all();
  13561. // The pool must still accept and run tasks after the dynamic thread exited.
  13562. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13563. task_queue->shutdown();
  13564. EXPECT_EQ(3u, count.load());
  13565. }
  13566. TEST(TaskQueueTest, MaxQueuedRequests) {
  13567. static constexpr unsigned int qlimit{3};
  13568. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13569. std::condition_variable sem_cv;
  13570. std::mutex sem_mtx;
  13571. int credits = 0;
  13572. bool queued;
  13573. /* Fill up the queue with tasks that will block until we give them credits to
  13574. * complete. */
  13575. for (unsigned int n = 0; n <= qlimit;) {
  13576. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13577. std::unique_lock<std::mutex> lock(sem_mtx);
  13578. while (credits <= 0) {
  13579. sem_cv.wait(lock);
  13580. }
  13581. /* Consume the credit and signal the test code if they are all gone. */
  13582. if (--credits == 0) { sem_cv.notify_one(); }
  13583. });
  13584. if (n < qlimit) {
  13585. /* The first qlimit enqueues must succeed. */
  13586. EXPECT_TRUE(queued);
  13587. } else {
  13588. /* The last one will succeed only when the worker thread
  13589. * starts and dequeues the first blocking task. Although
  13590. * not necessary for the correctness of this test, we sleep for
  13591. * a short while to avoid busy waiting. */
  13592. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13593. }
  13594. if (queued) { n++; }
  13595. }
  13596. /* Further enqueues must fail since the queue is full. */
  13597. for (auto i = 0; i < 4; i++) {
  13598. queued = task_queue->enqueue([] {});
  13599. EXPECT_FALSE(queued);
  13600. }
  13601. /* Give the credits to allow the previous tasks to complete. */
  13602. {
  13603. std::unique_lock<std::mutex> lock(sem_mtx);
  13604. credits += qlimit + 1;
  13605. }
  13606. sem_cv.notify_all();
  13607. /* Wait for all the credits to be consumed. */
  13608. {
  13609. std::unique_lock<std::mutex> lock(sem_mtx);
  13610. while (credits > 0) {
  13611. sem_cv.wait(lock);
  13612. }
  13613. }
  13614. /* Check that we are able again to enqueue at least qlimit tasks. */
  13615. for (unsigned int i = 0; i < qlimit; i++) {
  13616. queued = task_queue->enqueue([] {});
  13617. EXPECT_TRUE(queued);
  13618. }
  13619. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13620. task_queue->shutdown();
  13621. #else
  13622. EXPECT_NO_THROW(task_queue->shutdown());
  13623. #endif
  13624. }
  13625. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13626. Server svr;
  13627. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13628. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13629. });
  13630. svr.Get("/hello", [](const Request &req, Response &res) {
  13631. res.set_content(req.get_param_value("key"), "text/plain");
  13632. });
  13633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13634. auto se = detail::scope_exit([&] {
  13635. svr.stop();
  13636. thread.join();
  13637. ASSERT_FALSE(svr.is_running());
  13638. });
  13639. svr.wait_until_ready();
  13640. {
  13641. Client cli(HOST, PORT);
  13642. cli.set_follow_location(true);
  13643. auto res = cli.Get("/");
  13644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13645. EXPECT_EQ(StatusCode::OK_200, res->status);
  13646. EXPECT_EQ("val&key2=val2", res->body);
  13647. }
  13648. }
  13649. #endif
  13650. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13651. Server svr;
  13652. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13653. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13654. });
  13655. svr.Get("/hello", [](const Request &req, Response &res) {
  13656. res.set_content(req.get_param_value("key"), "text/plain");
  13657. });
  13658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. thread.join();
  13662. ASSERT_FALSE(svr.is_running());
  13663. });
  13664. svr.wait_until_ready();
  13665. {
  13666. Client cli(HOST, PORT);
  13667. cli.set_follow_location(true);
  13668. auto res = cli.Get("/");
  13669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13670. EXPECT_EQ(StatusCode::OK_200, res->status);
  13671. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13672. }
  13673. }
  13674. TEST(RedirectTest, RedirectWithPlusInPath) {
  13675. Server svr;
  13676. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13677. res.set_redirect("/a+b");
  13678. });
  13679. // Route pattern uses regex; escape + as \\+
  13680. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13681. res.set_content(req.path, "text/plain");
  13682. });
  13683. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13684. auto se = detail::scope_exit([&] {
  13685. svr.stop();
  13686. thread.join();
  13687. ASSERT_FALSE(svr.is_running());
  13688. });
  13689. svr.wait_until_ready();
  13690. {
  13691. Client cli(HOST, PORT);
  13692. cli.set_follow_location(true);
  13693. auto res = cli.Get("/");
  13694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13695. EXPECT_EQ(StatusCode::OK_200, res->status);
  13696. EXPECT_EQ("/a+b", res->body);
  13697. }
  13698. }
  13699. #ifdef CPPHTTPLIB_SSL_ENABLED
  13700. TEST(RedirectTest, Issue2185_Online) {
  13701. SSLClient client("github.com");
  13702. client.set_follow_location(true);
  13703. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13704. "Coollab-Windows.zip");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. EXPECT_EQ(StatusCode::OK_200, res->status);
  13707. EXPECT_EQ(9920427U, res->body.size());
  13708. }
  13709. #endif
  13710. TEST(VulnerabilityTest, CRLFInjection) {
  13711. Server svr;
  13712. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13713. res.set_content("Hello 1", "text/plain");
  13714. });
  13715. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13716. res.set_content("Hello 2", "text/plain");
  13717. });
  13718. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13719. res.set_content("Hello 3", "text/plain");
  13720. });
  13721. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13722. res.set_content("Hello 4", "text/plain");
  13723. });
  13724. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13725. for (const auto &x : req.headers) {
  13726. auto key = x.first;
  13727. EXPECT_STRNE("evil", key.c_str());
  13728. }
  13729. });
  13730. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. thread.join();
  13734. ASSERT_FALSE(svr.is_running());
  13735. });
  13736. svr.wait_until_ready();
  13737. {
  13738. Client cli(HOST, PORT);
  13739. cli.Post("/test1", "A=B",
  13740. "application/x-www-form-urlencoded\r\nevil: hello1");
  13741. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13742. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13743. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13744. }
  13745. }
  13746. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13747. auto server_thread = std::thread([] {
  13748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13749. default_socket_options(srv);
  13750. sockaddr_in addr{};
  13751. addr.sin_family = AF_INET;
  13752. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13753. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13754. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13755. ::listen(srv, 1);
  13756. sockaddr_in cli_addr{};
  13757. socklen_t cli_len = sizeof(cli_addr);
  13758. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13759. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13760. std::string buf_all;
  13761. char buf[2048];
  13762. ssize_t n;
  13763. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13764. buf_all.append(buf, static_cast<size_t>(n));
  13765. size_t pos;
  13766. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13767. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13768. auto e = request_block.find("\r\n");
  13769. if (e != std::string::npos) {
  13770. auto request_line = request_block.substr(0, e);
  13771. std::string msg =
  13772. "CRLF injection detected in request line: '" + request_line + "'";
  13773. EXPECT_FALSE(true) << msg;
  13774. }
  13775. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13776. ::send(cli,
  13777. #ifdef _WIN32
  13778. static_cast<const char *>(resp.c_str()),
  13779. static_cast<int>(resp.size()),
  13780. #else
  13781. resp.c_str(), resp.size(),
  13782. #endif
  13783. 0);
  13784. buf_all.erase(0, pos + 4);
  13785. }
  13786. }
  13787. detail::close_socket(cli);
  13788. detail::close_socket(srv);
  13789. });
  13790. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13791. auto cli = Client("127.0.0.1", PORT + 1);
  13792. auto headers = Headers{
  13793. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13794. {"Connection", "keep-alive"}};
  13795. auto res = cli.Get("/hi", headers);
  13796. EXPECT_FALSE(res);
  13797. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13798. server_thread.join();
  13799. }
  13800. TEST(PathParamsTest, StaticMatch) {
  13801. const auto pattern = "/users/all";
  13802. detail::PathParamsMatcher matcher(pattern);
  13803. Request request;
  13804. request.path = "/users/all";
  13805. ASSERT_TRUE(matcher.match(request));
  13806. std::unordered_map<std::string, std::string> expected_params = {};
  13807. EXPECT_EQ(request.path_params, expected_params);
  13808. }
  13809. TEST(PathParamsTest, StaticMismatch) {
  13810. const auto pattern = "/users/all";
  13811. detail::PathParamsMatcher matcher(pattern);
  13812. Request request;
  13813. request.path = "/users/1";
  13814. ASSERT_FALSE(matcher.match(request));
  13815. }
  13816. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13817. const auto pattern = "/users/:id/subscriptions";
  13818. detail::PathParamsMatcher matcher(pattern);
  13819. Request request;
  13820. request.path = "/users/42/subscriptions";
  13821. ASSERT_TRUE(matcher.match(request));
  13822. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13823. EXPECT_EQ(request.path_params, expected_params);
  13824. }
  13825. TEST(PathParamsTest, SingleParamInTheEnd) {
  13826. const auto pattern = "/users/:id";
  13827. detail::PathParamsMatcher matcher(pattern);
  13828. Request request;
  13829. request.path = "/users/24";
  13830. ASSERT_TRUE(matcher.match(request));
  13831. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13832. EXPECT_EQ(request.path_params, expected_params);
  13833. }
  13834. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13835. const auto pattern = "/users/:id/";
  13836. detail::PathParamsMatcher matcher(pattern);
  13837. Request request;
  13838. request.path = "/users/42/";
  13839. ASSERT_TRUE(matcher.match(request));
  13840. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13841. EXPECT_EQ(request.path_params, expected_params);
  13842. }
  13843. TEST(PathParamsTest, EmptyParam) {
  13844. const auto pattern = "/users/:id/";
  13845. detail::PathParamsMatcher matcher(pattern);
  13846. Request request;
  13847. request.path = "/users//";
  13848. ASSERT_TRUE(matcher.match(request));
  13849. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13850. EXPECT_EQ(request.path_params, expected_params);
  13851. }
  13852. TEST(PathParamsTest, FragmentMismatch) {
  13853. const auto pattern = "/users/:id/";
  13854. detail::PathParamsMatcher matcher(pattern);
  13855. Request request;
  13856. request.path = "/admins/24/";
  13857. ASSERT_FALSE(matcher.match(request));
  13858. }
  13859. TEST(PathParamsTest, ExtraFragments) {
  13860. const auto pattern = "/users/:id";
  13861. detail::PathParamsMatcher matcher(pattern);
  13862. Request request;
  13863. request.path = "/users/42/subscriptions";
  13864. ASSERT_FALSE(matcher.match(request));
  13865. }
  13866. TEST(PathParamsTest, MissingTrailingParam) {
  13867. const auto pattern = "/users/:id";
  13868. detail::PathParamsMatcher matcher(pattern);
  13869. Request request;
  13870. request.path = "/users";
  13871. ASSERT_FALSE(matcher.match(request));
  13872. }
  13873. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13874. const auto pattern = "/users/:id/subscriptions";
  13875. detail::PathParamsMatcher matcher(pattern);
  13876. Request request;
  13877. request.path = "/users/subscriptions";
  13878. ASSERT_FALSE(matcher.match(request));
  13879. }
  13880. TEST(PathParamsTest, MultipleParams) {
  13881. const auto pattern = "/users/:userid/subscriptions/:subid";
  13882. detail::PathParamsMatcher matcher(pattern);
  13883. Request request;
  13884. request.path = "/users/42/subscriptions/2";
  13885. ASSERT_TRUE(matcher.match(request));
  13886. std::unordered_map<std::string, std::string> expected_params = {
  13887. {"userid", "42"}, {"subid", "2"}};
  13888. EXPECT_EQ(request.path_params, expected_params);
  13889. }
  13890. TEST(PathParamsTest, SequenceOfParams) {
  13891. const auto pattern = "/values/:x/:y/:z";
  13892. detail::PathParamsMatcher matcher(pattern);
  13893. Request request;
  13894. request.path = "/values/1/2/3";
  13895. ASSERT_TRUE(matcher.match(request));
  13896. std::unordered_map<std::string, std::string> expected_params = {
  13897. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13898. EXPECT_EQ(request.path_params, expected_params);
  13899. }
  13900. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13901. const auto pattern = "/prefix:suffix";
  13902. detail::PathParamsMatcher matcher(pattern);
  13903. Request request;
  13904. request.path = "/prefix:suffix";
  13905. ASSERT_TRUE(matcher.match(request));
  13906. const std::unordered_map<std::string, std::string> expected_params = {};
  13907. EXPECT_EQ(request.path_params, expected_params);
  13908. }
  13909. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13910. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13911. // calling thread's stack on a long enough path for a quantified pattern;
  13912. // RegexMatcher must refuse to run regex matching on paths beyond
  13913. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13914. detail::RegexMatcher matcher("/files/(.*)");
  13915. Request within_limit;
  13916. within_limit.path = "/files/" + std::string(10, 'A');
  13917. EXPECT_TRUE(matcher.match(within_limit));
  13918. Request over_limit;
  13919. over_limit.path =
  13920. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13921. EXPECT_FALSE(matcher.match(over_limit));
  13922. }
  13923. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13924. Server svr;
  13925. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13926. res.set_content("ok", "text/plain");
  13927. });
  13928. auto port = svr.bind_to_any_port(HOST);
  13929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13930. auto se = detail::scope_exit([&] {
  13931. svr.stop();
  13932. thread.join();
  13933. ASSERT_FALSE(svr.is_running());
  13934. });
  13935. svr.wait_until_ready();
  13936. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13937. // request URI limit; this used to be able to crash the process.
  13938. std::string path =
  13939. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13940. std::string req = "GET " + path +
  13941. " HTTP/1.1\r\n"
  13942. "Host: " +
  13943. std::string(HOST) + ":" + std::to_string(port) +
  13944. "\r\n"
  13945. "Connection: close\r\n"
  13946. "\r\n";
  13947. std::string response;
  13948. ASSERT_TRUE(send_request(5, req, &response, port));
  13949. EXPECT_NE(std::string::npos, response.find("404"));
  13950. }
  13951. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13952. Server svr;
  13953. auto handler = [](const Request & /*req*/, Response &res) {
  13954. res.set_content("hit", "text/plain");
  13955. };
  13956. // No regex metacharacter, so this one is compared literally
  13957. svr.Get("/literal/route", handler);
  13958. // '.' is a regex metacharacter, so this one must keep regex semantics
  13959. svr.Get("/a.c", handler);
  13960. auto port = svr.bind_to_any_port(HOST);
  13961. std::thread t([&]() { svr.listen_after_bind(); });
  13962. auto se = detail::scope_exit([&] {
  13963. svr.stop();
  13964. t.join();
  13965. ASSERT_FALSE(svr.is_running());
  13966. });
  13967. svr.wait_until_ready();
  13968. Client cli(HOST, port);
  13969. struct {
  13970. const char *path;
  13971. int status;
  13972. } cases[] = {
  13973. {"/literal/route", StatusCode::OK_200},
  13974. {"/literal/routes", StatusCode::NotFound_404},
  13975. {"/literal/rout", StatusCode::NotFound_404},
  13976. {"/abc", StatusCode::OK_200},
  13977. {"/a.c", StatusCode::OK_200},
  13978. };
  13979. for (const auto &x : cases) {
  13980. auto res = cli.Get(x.path);
  13981. ASSERT_TRUE(res) << x.path;
  13982. EXPECT_EQ(x.status, res->status) << x.path;
  13983. }
  13984. }
  13985. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13986. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13987. // from exhausting the stack, so it must only constrain routes that actually
  13988. // run a regular expression. A literal route is matched by comparison and
  13989. // stays usable at any length.
  13990. Server svr;
  13991. const std::string pattern =
  13992. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13993. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13994. res.set_content("hit", "text/plain");
  13995. });
  13996. auto port = svr.bind_to_any_port(HOST);
  13997. std::thread t([&]() { svr.listen_after_bind(); });
  13998. auto se = detail::scope_exit([&] {
  13999. svr.stop();
  14000. t.join();
  14001. ASSERT_FALSE(svr.is_running());
  14002. });
  14003. svr.wait_until_ready();
  14004. Client cli(HOST, port);
  14005. auto res = cli.Get(pattern);
  14006. ASSERT_TRUE(res);
  14007. EXPECT_EQ(StatusCode::OK_200, res->status);
  14008. }
  14009. TEST(ParseUrlTest, VariousPatterns) {
  14010. {
  14011. detail::UrlComponents uc;
  14012. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14013. EXPECT_EQ("http", uc.scheme);
  14014. EXPECT_EQ("example.com", uc.host);
  14015. EXPECT_EQ("8080", uc.port);
  14016. EXPECT_EQ("/path", uc.path);
  14017. EXPECT_EQ("?q=1", uc.query);
  14018. }
  14019. {
  14020. detail::UrlComponents uc;
  14021. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14022. EXPECT_EQ("https", uc.scheme);
  14023. EXPECT_EQ("example.com", uc.host);
  14024. EXPECT_TRUE(uc.port.empty());
  14025. EXPECT_EQ("/path", uc.path);
  14026. }
  14027. {
  14028. detail::UrlComponents uc;
  14029. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14030. EXPECT_EQ("::1", uc.host);
  14031. EXPECT_EQ("8080", uc.port);
  14032. EXPECT_EQ("/path", uc.path);
  14033. }
  14034. {
  14035. detail::UrlComponents uc;
  14036. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14037. }
  14038. {
  14039. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14040. // the path while the connection still targets the bracketed host.
  14041. detail::UrlComponents uc;
  14042. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14043. }
  14044. {
  14045. detail::UrlComponents uc;
  14046. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14047. }
  14048. {
  14049. detail::UrlComponents uc;
  14050. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14051. EXPECT_EQ("::1", uc.host);
  14052. EXPECT_TRUE(uc.port.empty());
  14053. EXPECT_EQ("/path", uc.path);
  14054. }
  14055. {
  14056. detail::UrlComponents uc;
  14057. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14058. EXPECT_TRUE(uc.scheme.empty());
  14059. EXPECT_EQ("example.com", uc.host);
  14060. EXPECT_EQ("/path", uc.path);
  14061. EXPECT_EQ("?q=1", uc.query);
  14062. }
  14063. {
  14064. detail::UrlComponents uc;
  14065. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14066. EXPECT_TRUE(uc.host.empty());
  14067. EXPECT_EQ("/path", uc.path);
  14068. EXPECT_EQ("?q=1", uc.query);
  14069. }
  14070. {
  14071. detail::UrlComponents uc;
  14072. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14073. EXPECT_EQ("example.com", uc.host);
  14074. EXPECT_EQ("8080", uc.port);
  14075. }
  14076. {
  14077. // Unix socket path — must not be parsed as host
  14078. detail::UrlComponents uc;
  14079. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14080. EXPECT_TRUE(uc.host.empty());
  14081. }
  14082. {
  14083. detail::UrlComponents uc;
  14084. ASSERT_TRUE(detail::parse_url("", uc));
  14085. EXPECT_TRUE(uc.host.empty());
  14086. EXPECT_TRUE(uc.path.empty());
  14087. }
  14088. {
  14089. detail::UrlComponents uc;
  14090. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14091. }
  14092. {
  14093. detail::UrlComponents uc;
  14094. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14095. }
  14096. {
  14097. // Accepted by parse_url; callers restrict to http/https
  14098. detail::UrlComponents uc;
  14099. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14100. EXPECT_EQ("ftp", uc.scheme);
  14101. }
  14102. {
  14103. detail::UrlComponents uc;
  14104. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14105. }
  14106. {
  14107. detail::UrlComponents uc;
  14108. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14109. }
  14110. }
  14111. TEST(ParseUrlTest, FragmentHandling) {
  14112. {
  14113. detail::UrlComponents uc;
  14114. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14115. EXPECT_EQ("/path", uc.path);
  14116. EXPECT_TRUE(uc.query.empty());
  14117. }
  14118. {
  14119. detail::UrlComponents uc;
  14120. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14121. EXPECT_TRUE(uc.path.empty());
  14122. EXPECT_TRUE(uc.query.empty());
  14123. }
  14124. }
  14125. TEST(ParseUrlTest, UserinfoHandling) {
  14126. // Userinfo with @ but no colon — host includes @
  14127. detail::UrlComponents uc;
  14128. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14129. EXPECT_EQ("user@host.com", uc.host);
  14130. EXPECT_EQ("/path", uc.path);
  14131. }
  14132. TEST(ParseUrlTest, IPv6EdgeCases) {
  14133. {
  14134. detail::UrlComponents uc;
  14135. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14136. EXPECT_TRUE(uc.scheme.empty());
  14137. EXPECT_EQ("::1", uc.host);
  14138. EXPECT_EQ("8080", uc.port);
  14139. }
  14140. {
  14141. // Zone ID '%25' is not in [a-fA-F0-9:]
  14142. detail::UrlComponents uc;
  14143. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14144. }
  14145. }
  14146. TEST(ParseUrlTest, SchemeEdgeCases) {
  14147. {
  14148. detail::UrlComponents uc;
  14149. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14150. }
  14151. {
  14152. detail::UrlComponents uc;
  14153. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14154. }
  14155. {
  14156. detail::UrlComponents uc;
  14157. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14158. }
  14159. }
  14160. TEST(ParseUrlTest, PortEdgeCases) {
  14161. {
  14162. detail::UrlComponents uc;
  14163. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14164. EXPECT_TRUE(uc.port.empty());
  14165. EXPECT_EQ("/path", uc.path);
  14166. }
  14167. {
  14168. // parse_url accepts any port string; validation is done by parse_port
  14169. detail::UrlComponents uc;
  14170. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14171. EXPECT_EQ("abc", uc.port);
  14172. }
  14173. }
  14174. TEST(ParseUrlTest, WebSocketPatterns) {
  14175. {
  14176. detail::UrlComponents uc;
  14177. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14178. EXPECT_EQ("ws", uc.scheme);
  14179. EXPECT_EQ("echo.example.com", uc.host);
  14180. EXPECT_EQ("8080", uc.port);
  14181. EXPECT_EQ("/ws", uc.path);
  14182. }
  14183. {
  14184. detail::UrlComponents uc;
  14185. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14186. EXPECT_EQ("wss", uc.scheme);
  14187. EXPECT_EQ("echo.example.com", uc.host);
  14188. EXPECT_TRUE(uc.port.empty());
  14189. EXPECT_EQ("/ws", uc.path);
  14190. }
  14191. }
  14192. TEST(ParseUrlTest, QueryOnly) {
  14193. detail::UrlComponents uc;
  14194. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14195. EXPECT_TRUE(uc.host.empty());
  14196. EXPECT_TRUE(uc.path.empty());
  14197. EXPECT_EQ("?q=1&r=2", uc.query);
  14198. }
  14199. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14200. detail::UrlComponents uc;
  14201. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14202. EXPECT_TRUE(uc.scheme.empty());
  14203. EXPECT_EQ("example.com", uc.host);
  14204. EXPECT_EQ("443", uc.port);
  14205. EXPECT_EQ("/path", uc.path);
  14206. }
  14207. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14208. // If ipv6 regex working, regex match codepath is taken.
  14209. // else port will default to 80 in Client impl
  14210. int clientImplMagicPort = 80;
  14211. int port = 4321;
  14212. // above ports must be different to avoid false negative
  14213. EXPECT_NE(clientImplMagicPort, port);
  14214. std::string ipV6TestURL = "http://[ff06::c3]";
  14215. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14216. CLIENT_PRIVATE_KEY_FILE);
  14217. EXPECT_EQ(cli.port(), port);
  14218. }
  14219. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14220. auto file_path = "./www/dir/index.html";
  14221. auto dir_path = "./www/dir";
  14222. detail::FileStat stat_file(file_path);
  14223. EXPECT_TRUE(stat_file.is_file());
  14224. EXPECT_FALSE(stat_file.is_dir());
  14225. detail::FileStat stat_dir(dir_path);
  14226. EXPECT_FALSE(stat_dir.is_file());
  14227. EXPECT_TRUE(stat_dir.is_dir());
  14228. }
  14229. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14230. // IPv4 with default HTTP port (80)
  14231. EXPECT_EQ("example.com",
  14232. detail::make_host_and_port_string("example.com", 80, false));
  14233. // IPv4 with default HTTPS port (443)
  14234. EXPECT_EQ("example.com",
  14235. detail::make_host_and_port_string("example.com", 443, true));
  14236. // IPv4 with non-default HTTP port
  14237. EXPECT_EQ("example.com:8080",
  14238. detail::make_host_and_port_string("example.com", 8080, false));
  14239. // IPv4 with non-default HTTPS port
  14240. EXPECT_EQ("example.com:8443",
  14241. detail::make_host_and_port_string("example.com", 8443, true));
  14242. // IPv6 with default HTTP port (80)
  14243. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14244. // IPv6 with default HTTPS port (443)
  14245. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14246. // IPv6 with non-default HTTP port
  14247. EXPECT_EQ("[::1]:8080",
  14248. detail::make_host_and_port_string("::1", 8080, false));
  14249. // IPv6 with non-default HTTPS port
  14250. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14251. // IPv6 full address with default port
  14252. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14253. detail::make_host_and_port_string(
  14254. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14255. // IPv6 full address with non-default port
  14256. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14257. detail::make_host_and_port_string(
  14258. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14259. // IPv6 localhost with non-default port
  14260. EXPECT_EQ("[::1]:3000",
  14261. detail::make_host_and_port_string("::1", 3000, false));
  14262. // IPv6 with zone ID (link-local address) with default port
  14263. EXPECT_EQ("[fe80::1%eth0]",
  14264. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14265. // IPv6 with zone ID (link-local address) with non-default port
  14266. EXPECT_EQ("[fe80::1%eth0]:8080",
  14267. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14268. // Edge case: Port 443 with is_ssl=false (should add port)
  14269. EXPECT_EQ("example.com:443",
  14270. detail::make_host_and_port_string("example.com", 443, false));
  14271. // Edge case: Port 80 with is_ssl=true (should add port)
  14272. EXPECT_EQ("example.com:80",
  14273. detail::make_host_and_port_string("example.com", 80, true));
  14274. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14275. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14276. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14277. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14278. // Security fix: Already bracketed IPv6 should not get double brackets
  14279. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14280. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14281. EXPECT_EQ("[::1]:8080",
  14282. detail::make_host_and_port_string("[::1]", 8080, false));
  14283. EXPECT_EQ("[2001:db8::1]:8080",
  14284. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14285. EXPECT_EQ("[fe80::1%eth0]",
  14286. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14287. EXPECT_EQ("[fe80::1%eth0]:8080",
  14288. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14289. // Edge case: Empty host (should return as-is)
  14290. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14291. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14292. // This is a known limitation but shouldn't crash
  14293. EXPECT_EQ("[host:name]",
  14294. detail::make_host_and_port_string("host:name", 80, false));
  14295. // Port number edge cases (no validation, but should not crash)
  14296. EXPECT_EQ("example.com:0",
  14297. detail::make_host_and_port_string("example.com", 0, false));
  14298. EXPECT_EQ("example.com:-1",
  14299. detail::make_host_and_port_string("example.com", -1, false));
  14300. EXPECT_EQ("example.com:65535",
  14301. detail::make_host_and_port_string("example.com", 65535, false));
  14302. EXPECT_EQ("example.com:65536",
  14303. detail::make_host_and_port_string("example.com", 65536, false));
  14304. }
  14305. #ifdef CPPHTTPLIB_SSL_ENABLED
  14306. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14307. httplib::SSLClient cli("roblox.com", 443);
  14308. cli.set_follow_location(true);
  14309. auto res = cli.Get("/");
  14310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14311. EXPECT_EQ(StatusCode::OK_200, res->status);
  14312. }
  14313. #endif
  14314. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14315. Server svr;
  14316. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14317. EXPECT_EQ(res.status, 400);
  14318. });
  14319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14320. auto se = detail::scope_exit([&] {
  14321. svr.stop();
  14322. thread.join();
  14323. ASSERT_FALSE(svr.is_running());
  14324. });
  14325. svr.wait_until_ready();
  14326. Client cli(HOST, PORT);
  14327. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14328. }
  14329. TEST(InvalidHeaderCharsTest, is_field_name) {
  14330. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14331. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14332. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14333. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14334. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14335. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14336. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14337. EXPECT_FALSE(detail::fields::is_field_name(""));
  14338. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14339. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14340. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14341. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14342. }
  14343. TEST(InvalidHeaderCharsTest, is_field_value) {
  14344. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14345. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14346. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14347. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14348. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14349. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14350. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14351. EXPECT_TRUE(detail::fields::is_field_value(""));
  14352. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14353. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14354. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14355. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14356. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14357. }
  14358. TEST(InvalidHeaderCharsTest, OnServer) {
  14359. Server svr;
  14360. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14361. std::string header = "Not Set";
  14362. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14363. res.set_header(header, "value");
  14364. res.set_content("Page Content Page Content", "text/plain");
  14365. });
  14366. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14367. std::string header = "Not Set";
  14368. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14369. res.set_header("X-Test", header);
  14370. res.set_content("Page Content Page Content", "text/plain");
  14371. });
  14372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14373. auto se = detail::scope_exit([&] {
  14374. svr.stop();
  14375. thread.join();
  14376. ASSERT_FALSE(svr.is_running());
  14377. });
  14378. svr.wait_until_ready();
  14379. Client cli(HOST, PORT);
  14380. {
  14381. auto res = cli.Get(
  14382. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14384. EXPECT_EQ("Page Content Page Content", res->body);
  14385. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14386. }
  14387. {
  14388. auto res = cli.Get(
  14389. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14391. EXPECT_EQ("Page Content Page Content", res->body);
  14392. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14393. }
  14394. }
  14395. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14396. auto handled = false;
  14397. Server svr;
  14398. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14399. thread t = thread([&] { svr.listen(HOST, PORT); });
  14400. auto se = detail::scope_exit([&] {
  14401. svr.stop();
  14402. t.join();
  14403. ASSERT_FALSE(svr.is_running());
  14404. ASSERT_FALSE(handled);
  14405. });
  14406. svr.wait_until_ready();
  14407. auto req = "POST /test HTTP/1.1\r\n"
  14408. "Content-Length: x\r\n"
  14409. "\r\n";
  14410. std::string response;
  14411. ASSERT_TRUE(send_request(1, req, &response));
  14412. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14413. response.substr(0, response.find("\r\n")));
  14414. }
  14415. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14416. // case-insensitive, and a server that receives a 100-continue expectation in
  14417. // an HTTP/1.0 request MUST ignore it.
  14418. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14419. std::string response;
  14420. ASSERT_TRUE(send_request(1, req, &response, port));
  14421. *got_100 = response.find("100 Continue") != std::string::npos;
  14422. }
  14423. class ExpectTokenTest : public ::testing::Test {
  14424. protected:
  14425. void SetUp() override {
  14426. svr_.Post("/p", [](const Request &, Response &res) {
  14427. res.set_content("ok", "text/plain");
  14428. });
  14429. port_ = svr_.bind_to_any_port(HOST);
  14430. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14431. svr_.wait_until_ready();
  14432. }
  14433. void TearDown() override {
  14434. svr_.stop();
  14435. if (thread_.joinable()) { thread_.join(); }
  14436. }
  14437. std::string request(const char *version, const char *expect_value) const {
  14438. return std::string("POST /p ") + version +
  14439. "\r\n"
  14440. "Host: localhost\r\n"
  14441. "Content-Length: 2\r\n"
  14442. "Connection: close\r\n"
  14443. "Expect: " +
  14444. expect_value +
  14445. "\r\n"
  14446. "\r\n"
  14447. "hi";
  14448. }
  14449. Server svr_;
  14450. int port_ = 0;
  14451. thread thread_;
  14452. };
  14453. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14454. bool got_100 = false;
  14455. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14456. EXPECT_TRUE(got_100);
  14457. }
  14458. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14459. bool got_100 = true;
  14460. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14461. EXPECT_FALSE(got_100);
  14462. }
  14463. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14464. bool got_100 = false;
  14465. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14466. EXPECT_TRUE(got_100);
  14467. }
  14468. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14469. bool got_100 = false;
  14470. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14471. EXPECT_TRUE(got_100);
  14472. }
  14473. #ifndef _WIN32
  14474. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14475. static constexpr char reject[] = "Unauthorized";
  14476. static constexpr char accept[] = "Upload accepted";
  14477. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14478. Server svr;
  14479. svr.set_expect_100_continue_handler(
  14480. [](const Request & /*req*/, Response &res) {
  14481. res.status = StatusCode::Unauthorized_401;
  14482. res.set_content(reject, "text/plain");
  14483. return res.status;
  14484. });
  14485. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14486. res.set_content(accept, "text/plain");
  14487. });
  14488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14489. auto se = detail::scope_exit([&] {
  14490. svr.stop();
  14491. thread.join();
  14492. ASSERT_FALSE(svr.is_running());
  14493. });
  14494. svr.wait_until_ready();
  14495. {
  14496. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14497. curl_easy_init(), &curl_easy_cleanup};
  14498. ASSERT_NE(curl, nullptr);
  14499. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14500. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14501. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14502. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14503. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14504. &curl_slist_free_all};
  14505. ASSERT_NE(list, nullptr);
  14506. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14507. struct read_data {
  14508. size_t read_size;
  14509. size_t total_size;
  14510. } data = {0, total_size};
  14511. using read_callback_t =
  14512. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14513. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14514. void *userdata) -> size_t {
  14515. read_data *d = (read_data *)userdata;
  14516. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14517. std::fill_n(ptr, size * nmemb, 'A');
  14518. d->read_size += size * nmemb;
  14519. return size * nmemb;
  14520. };
  14521. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14522. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14523. std::vector<char> buffer;
  14524. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14525. using write_callback_t =
  14526. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14527. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14528. void *userdata) -> size_t {
  14529. std::vector<char> *buf = (std::vector<char> *)userdata;
  14530. buf->reserve(buf->size() + size * nmemb + 1);
  14531. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14532. return size * nmemb;
  14533. };
  14534. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14535. {
  14536. const auto res = curl_easy_perform(curl.get());
  14537. ASSERT_EQ(res, CURLE_OK);
  14538. }
  14539. {
  14540. auto response_code = long{};
  14541. const auto res =
  14542. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14543. ASSERT_EQ(res, CURLE_OK);
  14544. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14545. }
  14546. {
  14547. auto dl = curl_off_t{};
  14548. const auto res =
  14549. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14550. ASSERT_EQ(res, CURLE_OK);
  14551. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14552. }
  14553. {
  14554. buffer.push_back('\0');
  14555. ASSERT_STRCASEEQ(buffer.data(), reject);
  14556. }
  14557. }
  14558. }
  14559. #endif
  14560. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14561. // Regression test for #2458.
  14562. //
  14563. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14564. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14565. // ticket can make the client socket spuriously readable during the
  14566. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14567. // the client withholds the body and then blocks reading a response that never
  14568. // comes, failing with `Failed to read connection`.
  14569. //
  14570. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14571. // within the timeout. This raw OpenSSL server deliberately never sends
  14572. // `100 Continue`; the client must still deliver the body and receive 200.
  14573. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14574. signal(SIGPIPE, SIG_IGN);
  14575. const auto port = PORT + 4;
  14576. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14577. ASSERT_NE(srv, INVALID_SOCKET);
  14578. int opt = 1;
  14579. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14580. sockaddr_in addr{};
  14581. addr.sin_family = AF_INET;
  14582. addr.sin_port = htons(static_cast<uint16_t>(port));
  14583. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14584. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14585. ASSERT_EQ(0, ::listen(srv, 1));
  14586. std::atomic<size_t> server_body_bytes{0};
  14587. auto server_thread = std::thread([&] {
  14588. sockaddr_in cli_addr{};
  14589. socklen_t cli_len = sizeof(cli_addr);
  14590. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14591. if (cli == INVALID_SOCKET) { return; }
  14592. // Bound the lifetime of the server side so a buggy client (which never
  14593. // sends the body) cannot make this thread block forever on join.
  14594. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14595. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14596. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14597. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14598. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14599. SSL *ssl = SSL_new(ctx);
  14600. SSL_set_fd(ssl, static_cast<int>(cli));
  14601. if (SSL_accept(ssl) > 0) {
  14602. // Read the request headers. Reading here also flushes the TLS 1.3
  14603. // session tickets to the client. Deliberately do NOT send
  14604. // `100 Continue`.
  14605. std::string buf;
  14606. char tmp[1024];
  14607. while (buf.find("\r\n\r\n") == std::string::npos) {
  14608. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14609. if (n <= 0) { break; }
  14610. buf.append(tmp, static_cast<size_t>(n));
  14611. }
  14612. // A correct client sends the body now; count what arrives.
  14613. auto pos = buf.find("\r\n\r\n");
  14614. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14615. while (body < 4096) {
  14616. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14617. if (n <= 0) { break; }
  14618. body += static_cast<size_t>(n);
  14619. }
  14620. server_body_bytes = body;
  14621. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14622. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14623. SSL_shutdown(ssl);
  14624. }
  14625. SSL_free(ssl);
  14626. detail::close_socket(cli);
  14627. SSL_CTX_free(ctx);
  14628. });
  14629. auto se = detail::scope_exit([&] {
  14630. server_thread.join();
  14631. detail::close_socket(srv);
  14632. });
  14633. SSLClient cli("127.0.0.1", port);
  14634. cli.enable_server_certificate_verification(false);
  14635. cli.set_connection_timeout(5, 0);
  14636. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14637. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14638. std::string body(4096, 'A');
  14639. auto res = cli.Put("/api/test", body, "application/json");
  14640. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14641. EXPECT_EQ(StatusCode::OK_200, res->status);
  14642. EXPECT_EQ(body.size(), server_body_bytes.load());
  14643. }
  14644. #endif
  14645. template <typename S, typename C>
  14646. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14647. svr.Get("/stream", [&](const Request &, Response &res) {
  14648. auto data = new std::string("01234567890123456789");
  14649. res.set_content_provider(
  14650. data->size(), "text/plain",
  14651. [&, data](size_t offset, size_t length, DataSink &sink) {
  14652. const size_t DATA_CHUNK_SIZE = 4;
  14653. const auto &d = *data;
  14654. std::this_thread::sleep_for(std::chrono::seconds(1));
  14655. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14656. return true;
  14657. },
  14658. [data](bool success) {
  14659. EXPECT_FALSE(success);
  14660. delete data;
  14661. });
  14662. });
  14663. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14664. auto i = new size_t(0);
  14665. res.set_content_provider(
  14666. "text/plain",
  14667. [i](size_t, DataSink &sink) {
  14668. if (*i < 5) {
  14669. std::this_thread::sleep_for(std::chrono::seconds(1));
  14670. sink.write("abcd", 4);
  14671. (*i)++;
  14672. } else {
  14673. sink.done();
  14674. }
  14675. return true;
  14676. },
  14677. [i](bool success) {
  14678. EXPECT_FALSE(success);
  14679. delete i;
  14680. });
  14681. });
  14682. svr.Get("/chunked", [&](const Request &, Response &res) {
  14683. auto i = new size_t(0);
  14684. res.set_chunked_content_provider(
  14685. "text/plain",
  14686. [i](size_t, DataSink &sink) {
  14687. if (*i < 5) {
  14688. std::this_thread::sleep_for(std::chrono::seconds(1));
  14689. sink.os << "abcd";
  14690. (*i)++;
  14691. } else {
  14692. sink.done();
  14693. }
  14694. return true;
  14695. },
  14696. [i](bool success) {
  14697. EXPECT_FALSE(success);
  14698. delete i;
  14699. });
  14700. });
  14701. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14702. auto se = detail::scope_exit([&] {
  14703. svr.stop();
  14704. listen_thread.join();
  14705. ASSERT_FALSE(svr.is_running());
  14706. });
  14707. svr.wait_until_ready();
  14708. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14709. {
  14710. auto start = std::chrono::steady_clock::now();
  14711. auto res = cli.Get("/stream");
  14712. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14713. std::chrono::steady_clock::now() - start)
  14714. .count();
  14715. ASSERT_FALSE(res);
  14716. EXPECT_EQ(Error::Read, res.error());
  14717. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14718. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14719. }
  14720. {
  14721. auto start = std::chrono::steady_clock::now();
  14722. auto res = cli.Get("/stream_without_length");
  14723. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14724. std::chrono::steady_clock::now() - start)
  14725. .count();
  14726. ASSERT_FALSE(res);
  14727. EXPECT_EQ(Error::Read, res.error());
  14728. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14729. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14730. }
  14731. {
  14732. auto start = std::chrono::steady_clock::now();
  14733. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14734. EXPECT_EQ("abcd", string(data, data_length));
  14735. return true;
  14736. });
  14737. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14738. std::chrono::steady_clock::now() - start)
  14739. .count();
  14740. ASSERT_FALSE(res);
  14741. EXPECT_EQ(Error::Read, res.error());
  14742. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14743. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14744. }
  14745. }
  14746. TEST(MaxTimeoutTest, ContentStream) {
  14747. time_t timeout = 2000;
  14748. time_t threshold = 200;
  14749. Server svr;
  14750. Client cli("localhost", PORT);
  14751. max_timeout_test(svr, cli, timeout, threshold);
  14752. }
  14753. #ifdef CPPHTTPLIB_SSL_ENABLED
  14754. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14755. time_t timeout = 2000;
  14756. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14758. SSLClient cli("localhost", PORT);
  14759. cli.enable_server_certificate_verification(false);
  14760. max_timeout_test(svr, cli, timeout, threshold);
  14761. }
  14762. #endif
  14763. class EventDispatcher {
  14764. public:
  14765. EventDispatcher() {}
  14766. bool wait_event(DataSink *sink) {
  14767. unique_lock<mutex> lk(m_);
  14768. int id = id_;
  14769. // Wait with timeout to prevent hanging if client disconnects
  14770. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14771. [&] { return cid_ == id; })) {
  14772. return false; // Timeout occurred
  14773. }
  14774. sink->write(message_.data(), message_.size());
  14775. return true;
  14776. }
  14777. void send_event(const string &message) {
  14778. lock_guard<mutex> lk(m_);
  14779. cid_ = id_++;
  14780. message_ = message;
  14781. cv_.notify_all();
  14782. }
  14783. private:
  14784. mutex m_;
  14785. condition_variable cv_;
  14786. atomic_int id_{0};
  14787. atomic_int cid_{-1};
  14788. string message_;
  14789. };
  14790. TEST(ClientInThreadTest, Issue2068) {
  14791. EventDispatcher ed;
  14792. Server svr;
  14793. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14794. res.set_chunked_content_provider("text/event-stream",
  14795. [&](size_t /*offset*/, DataSink &sink) {
  14796. return ed.wait_event(&sink);
  14797. });
  14798. });
  14799. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14800. svr.wait_until_ready();
  14801. thread event_thread([&] {
  14802. int id = 0;
  14803. while (svr.is_running()) {
  14804. this_thread::sleep_for(chrono::milliseconds(500));
  14805. std::stringstream ss;
  14806. ss << "data: " << id << "\n\n";
  14807. ed.send_event(ss.str());
  14808. id++;
  14809. }
  14810. });
  14811. auto se = detail::scope_exit([&] {
  14812. svr.stop();
  14813. listen_thread.join();
  14814. event_thread.join();
  14815. ASSERT_FALSE(svr.is_running());
  14816. });
  14817. {
  14818. auto client = detail::make_unique<Client>(HOST, PORT);
  14819. client->set_read_timeout(std::chrono::minutes(10));
  14820. std::atomic<bool> stop{false};
  14821. std::thread t([&] {
  14822. client->Get("/event1",
  14823. [&](const char *, size_t) -> bool { return !stop; });
  14824. });
  14825. std::this_thread::sleep_for(std::chrono::seconds(2));
  14826. stop = true;
  14827. client->stop();
  14828. t.join();
  14829. // Reset client after thread has finished
  14830. client.reset();
  14831. }
  14832. }
  14833. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14834. auto handled = false;
  14835. Server svr;
  14836. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14838. auto se = detail::scope_exit([&] {
  14839. svr.stop();
  14840. t.join();
  14841. ASSERT_FALSE(svr.is_running());
  14842. ASSERT_FALSE(handled);
  14843. });
  14844. svr.wait_until_ready();
  14845. // Two Content-Length headers with different values — must be rejected
  14846. auto req = "POST /test HTTP/1.1\r\n"
  14847. "Content-Length: 5\r\n"
  14848. "Content-Length: 10\r\n"
  14849. "\r\n"
  14850. "hello";
  14851. std::string response;
  14852. ASSERT_TRUE(send_request(1, req, &response));
  14853. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14854. response.substr(0, response.find("\r\n")));
  14855. }
  14856. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14857. auto handled = false;
  14858. Server svr;
  14859. svr.Post("/test", [&](const Request &, Response &res) {
  14860. handled = true;
  14861. res.set_content("ok", "text/plain");
  14862. });
  14863. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14864. auto se = detail::scope_exit([&] {
  14865. svr.stop();
  14866. t.join();
  14867. ASSERT_FALSE(svr.is_running());
  14868. ASSERT_TRUE(handled);
  14869. });
  14870. svr.wait_until_ready();
  14871. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14872. auto req = "POST /test HTTP/1.1\r\n"
  14873. "Content-Length: 5\r\n"
  14874. "Content-Length: 5\r\n"
  14875. "\r\n"
  14876. "hello";
  14877. std::string response;
  14878. ASSERT_TRUE(send_request(1, req, &response));
  14879. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14880. }
  14881. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14882. Server svr;
  14883. svr.Get("/", [](const Request &req, Response &res) {
  14884. EXPECT_EQ(2U, req.trailers.size());
  14885. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14886. // Denied
  14887. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14888. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14889. // Accepted
  14890. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14891. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14892. EXPECT_TRUE(req.has_trailer("X-World"));
  14893. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14894. res.set_content("ok", "text/plain");
  14895. });
  14896. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14897. auto se = detail::scope_exit([&] {
  14898. svr.stop();
  14899. t.join();
  14900. ASSERT_FALSE(svr.is_running());
  14901. });
  14902. svr.wait_until_ready();
  14903. const std::string req = "GET / HTTP/1.1\r\n"
  14904. "Transfer-Encoding: chunked\r\n"
  14905. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14906. "\r\n"
  14907. "0\r\n"
  14908. "Content-Length: 10\r\n"
  14909. "Host: internal.local\r\n"
  14910. "Content-Type: malicious/content\r\n"
  14911. "Cookie: any\r\n"
  14912. "Set-Cookie: any\r\n"
  14913. "X-Forwarded-For: attacker.com\r\n"
  14914. "X-Real-Ip: 1.1.1.1\r\n"
  14915. "X-Hello: hello\r\n"
  14916. "X-World: world\r\n"
  14917. "\r\n";
  14918. std::string res;
  14919. ASSERT_TRUE(send_request(1, req, &res));
  14920. }
  14921. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14922. // several field lines, and the combined value is what has to be parsed. A
  14923. // Trailer field split across lines therefore declares every name it lists;
  14924. // reading only the first line silently drops the trailers the later lines
  14925. // declare. The prohibited-trailer filter still applies to every line.
  14926. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14927. Server svr;
  14928. size_t observed_trailer_count = 0;
  14929. std::string observed_hello;
  14930. std::string observed_world;
  14931. bool observed_content_length = true;
  14932. svr.Get("/", [&](const Request &req, Response &res) {
  14933. observed_trailer_count = req.trailers.size();
  14934. observed_hello = req.get_trailer_value("X-Hello");
  14935. observed_world = req.get_trailer_value("X-World");
  14936. observed_content_length = req.has_trailer("Content-Length");
  14937. res.set_content("ok", "text/plain");
  14938. });
  14939. auto port = svr.bind_to_any_port(HOST);
  14940. thread t = thread([&]() { svr.listen_after_bind(); });
  14941. auto se = detail::scope_exit([&] {
  14942. svr.stop();
  14943. t.join();
  14944. ASSERT_FALSE(svr.is_running());
  14945. });
  14946. svr.wait_until_ready();
  14947. const std::string req = "GET / HTTP/1.1\r\n"
  14948. "Transfer-Encoding: chunked\r\n"
  14949. "Trailer: X-Hello\r\n"
  14950. "Trailer: X-World, Content-Length\r\n"
  14951. "\r\n"
  14952. "0\r\n"
  14953. "X-Hello: hello\r\n"
  14954. "X-World: world\r\n"
  14955. "Content-Length: 10\r\n"
  14956. "\r\n";
  14957. std::string res;
  14958. ASSERT_TRUE(send_request(1, req, &res, port));
  14959. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14960. // Accepted: both field lines contribute to the declared set
  14961. EXPECT_EQ(2U, observed_trailer_count);
  14962. EXPECT_EQ(observed_hello, "hello");
  14963. EXPECT_EQ(observed_world, "world");
  14964. // Denied: a prohibited name stays prohibited on a later field line
  14965. EXPECT_FALSE(observed_content_length);
  14966. }
  14967. // A direct client that is not listed in trusted_proxies must not be able to
  14968. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14969. // the peer address on the actual TCP connection determines whether the
  14970. // header is honored.
  14971. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14972. Server svr;
  14973. // Deliberately does NOT include the loopback address the test client
  14974. // actually connects from, so the direct connection is not a trusted proxy.
  14975. svr.set_trusted_proxies({"203.0.113.66"});
  14976. std::string observed_remote_addr;
  14977. svr.Get("/ip", [&](const Request &req, Response &res) {
  14978. observed_remote_addr = req.remote_addr;
  14979. res.set_content("ok", "text/plain");
  14980. });
  14981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14982. auto se = detail::scope_exit([&] {
  14983. svr.stop();
  14984. t.join();
  14985. ASSERT_FALSE(svr.is_running());
  14986. });
  14987. svr.wait_until_ready();
  14988. Client cli(HOST, PORT);
  14989. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14991. EXPECT_EQ(StatusCode::OK_200, res->status);
  14992. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14993. // ignored entirely and the real connection-level address retained.
  14994. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14995. observed_remote_addr == "127.0.0.1");
  14996. }
  14997. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14998. Server svr;
  14999. std::string observed_remote_addr;
  15000. std::string observed_xff;
  15001. svr.Get("/ip", [&](const Request &req, Response &res) {
  15002. observed_remote_addr = req.remote_addr;
  15003. observed_xff = req.get_header_value("X-Forwarded-For");
  15004. res.set_content("ok", "text/plain");
  15005. });
  15006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15007. auto se = detail::scope_exit([&] {
  15008. svr.stop();
  15009. t.join();
  15010. ASSERT_FALSE(svr.is_running());
  15011. });
  15012. svr.wait_until_ready();
  15013. Client cli(HOST, PORT);
  15014. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. EXPECT_EQ(observed_xff, "203.0.113.66");
  15018. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15019. observed_remote_addr == "127.0.0.1");
  15020. }
  15021. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15022. Server svr;
  15023. svr.set_trusted_proxies({"203.0.113.66"});
  15024. std::string observed_remote_addr;
  15025. std::string observed_xff;
  15026. svr.Get("/ip", [&](const Request &req, Response &res) {
  15027. observed_remote_addr = req.remote_addr;
  15028. observed_xff = req.get_header_value("X-Forwarded-For");
  15029. res.set_content("ok", "text/plain");
  15030. });
  15031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15032. auto se = detail::scope_exit([&] {
  15033. svr.stop();
  15034. t.join();
  15035. ASSERT_FALSE(svr.is_running());
  15036. });
  15037. svr.wait_until_ready();
  15038. Client cli(HOST, PORT);
  15039. auto res = cli.Get("/ip");
  15040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15041. EXPECT_EQ(StatusCode::OK_200, res->status);
  15042. EXPECT_EQ(observed_xff, "");
  15043. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15044. observed_remote_addr == "127.0.0.1");
  15045. }
  15046. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15047. Server svr;
  15048. // Include the loopback address the test client actually connects from, so
  15049. // the direct connection itself is recognized as the trusted proxy hop.
  15050. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15051. std::string observed_remote_addr;
  15052. std::string observed_xff;
  15053. svr.Get("/ip", [&](const Request &req, Response &res) {
  15054. observed_remote_addr = req.remote_addr;
  15055. observed_xff = req.get_header_value("X-Forwarded-For");
  15056. res.set_content("ok", "text/plain");
  15057. });
  15058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15059. auto se = detail::scope_exit([&] {
  15060. svr.stop();
  15061. t.join();
  15062. ASSERT_FALSE(svr.is_running());
  15063. });
  15064. svr.wait_until_ready();
  15065. Client cli(HOST, PORT);
  15066. auto res = cli.Get(
  15067. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15069. EXPECT_EQ(StatusCode::OK_200, res->status);
  15070. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15071. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15072. }
  15073. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15074. Server svr;
  15075. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15076. std::string observed_remote_addr;
  15077. std::string observed_xff;
  15078. svr.Get("/ip", [&](const Request &req, Response &res) {
  15079. observed_remote_addr = req.remote_addr;
  15080. observed_xff = req.get_header_value("X-Forwarded-For");
  15081. res.set_content("ok", "text/plain");
  15082. });
  15083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15084. auto se = detail::scope_exit([&] {
  15085. svr.stop();
  15086. t.join();
  15087. ASSERT_FALSE(svr.is_running());
  15088. });
  15089. svr.wait_until_ready();
  15090. Client cli(HOST, PORT);
  15091. auto res = cli.Get(
  15092. "/ip",
  15093. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15095. EXPECT_EQ(StatusCode::OK_200, res->status);
  15096. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15097. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15098. }
  15099. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15100. Server svr;
  15101. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15102. std::string observed_remote_addr;
  15103. std::string observed_xff;
  15104. svr.Get("/ip", [&](const Request &req, Response &res) {
  15105. observed_remote_addr = req.remote_addr;
  15106. observed_xff = req.get_header_value("X-Forwarded-For");
  15107. res.set_content("ok", "text/plain");
  15108. });
  15109. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15110. auto se = detail::scope_exit([&] {
  15111. svr.stop();
  15112. t.join();
  15113. ASSERT_FALSE(svr.is_running());
  15114. });
  15115. svr.wait_until_ready();
  15116. Client cli(HOST, PORT);
  15117. auto res = cli.Get(
  15118. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15120. EXPECT_EQ(StatusCode::OK_200, res->status);
  15121. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15122. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15123. // and must not be selected.
  15124. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15125. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15126. }
  15127. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15128. Server svr;
  15129. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15130. std::string observed_remote_addr;
  15131. svr.Get("/ip", [&](const Request &req, Response &res) {
  15132. observed_remote_addr = req.remote_addr;
  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. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15143. // a forged address and the trusted proxy's own address; the forged value must
  15144. // not win over the address the trusted proxy actually recorded.
  15145. Client cli(HOST, PORT);
  15146. auto res = cli.Get(
  15147. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15149. EXPECT_EQ(StatusCode::OK_200, res->status);
  15150. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15151. }
  15152. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15153. Server svr;
  15154. svr.set_trusted_proxies({"192.0.2.45", "::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",
  15172. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. EXPECT_EQ(StatusCode::OK_200, res->status);
  15175. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15176. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15177. }
  15178. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15179. Server svr;
  15180. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15181. std::string observed_remote_addr;
  15182. std::string observed_xff;
  15183. svr.Get("/ip", [&](const Request &req, Response &res) {
  15184. observed_remote_addr = req.remote_addr;
  15185. observed_xff = req.get_header_value("X-Forwarded-For");
  15186. res.set_content("ok", "text/plain");
  15187. });
  15188. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15189. auto se = detail::scope_exit([&] {
  15190. svr.stop();
  15191. t.join();
  15192. ASSERT_FALSE(svr.is_running());
  15193. });
  15194. svr.wait_until_ready();
  15195. std::string raw_req =
  15196. "GET /ip HTTP/1.1\r\n"
  15197. "Host: localhost\r\n"
  15198. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15199. "Connection: close\r\n"
  15200. "\r\n";
  15201. std::string out;
  15202. ASSERT_TRUE(send_request(5, raw_req, &out));
  15203. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15204. // Header parser trims surrounding whitespace of the header value
  15205. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15206. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15207. }
  15208. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15209. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15210. // their own X-Forwarded-For as a separate field line rather than extending the
  15211. // one the client sent, so every occurrence has to be taken into account.
  15212. // Reading only the first one hands back the address the client chose.
  15213. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15214. Server svr;
  15215. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15216. std::string observed_remote_addr;
  15217. size_t observed_xff_count = 0;
  15218. svr.Get("/ip", [&](const Request &req, Response &res) {
  15219. observed_remote_addr = req.remote_addr;
  15220. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15221. res.set_content("ok", "text/plain");
  15222. });
  15223. auto port = svr.bind_to_any_port(HOST);
  15224. thread t = thread([&]() { svr.listen_after_bind(); });
  15225. auto se = detail::scope_exit([&] {
  15226. svr.stop();
  15227. t.join();
  15228. ASSERT_FALSE(svr.is_running());
  15229. });
  15230. svr.wait_until_ready();
  15231. // The client supplies the first field line; the trusted proxy appends the
  15232. // address it observed as a second one.
  15233. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15234. "Host: localhost\r\n"
  15235. "X-Forwarded-For: 1.2.3.4\r\n"
  15236. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15237. "Connection: close\r\n"
  15238. "\r\n";
  15239. std::string out;
  15240. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15241. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15242. EXPECT_EQ(observed_xff_count, 2U);
  15243. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15244. // The same chain spread over one field line per hop derives the same client
  15245. // address, i.e. the split and the comma-joined representations agree.
  15246. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15247. "Host: localhost\r\n"
  15248. "X-Forwarded-For: 1.2.3.4\r\n"
  15249. "X-Forwarded-For: 198.51.100.23\r\n"
  15250. "X-Forwarded-For: 192.0.2.45\r\n"
  15251. "Connection: close\r\n"
  15252. "\r\n";
  15253. out.clear();
  15254. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15255. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15256. EXPECT_EQ(observed_xff_count, 3U);
  15257. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15258. }
  15259. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15260. // crash the server (it used to call front() on an empty vector inside
  15261. // get_client_ip). The connection-level remote address must be retained instead.
  15262. static void run_malformed_xff_test(const std::string &xff_value) {
  15263. Server svr;
  15264. svr.set_trusted_proxies({"192.0.2.45"});
  15265. std::string observed_remote_addr;
  15266. svr.Get("/ip", [&](const Request &req, Response &res) {
  15267. observed_remote_addr = req.remote_addr;
  15268. res.set_content("ok", "text/plain");
  15269. });
  15270. int port = 0;
  15271. thread t = thread([&]() {
  15272. port = svr.bind_to_any_port(HOST);
  15273. svr.listen_after_bind();
  15274. });
  15275. auto se = detail::scope_exit([&] {
  15276. svr.stop();
  15277. t.join();
  15278. ASSERT_FALSE(svr.is_running());
  15279. });
  15280. svr.wait_until_ready();
  15281. Client cli(HOST, port);
  15282. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15284. EXPECT_EQ(StatusCode::OK_200, res->status);
  15285. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15286. observed_remote_addr == "127.0.0.1");
  15287. }
  15288. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15289. run_malformed_xff_test("");
  15290. }
  15291. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15292. run_malformed_xff_test(",");
  15293. }
  15294. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15295. run_malformed_xff_test(", , ,");
  15296. }
  15297. // The same rule applies to Accept: a request whose acceptable types are spread
  15298. // over several field lines must be negotiated against all of them.
  15299. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15300. // case-insensitive connection options. Comparing the whole field value against
  15301. // one option misses a client that sends several of them, and misses every
  15302. // casing but the one written in the comparison.
  15303. //
  15304. // Sends req, reads the response, then reuses the same socket for a second
  15305. // request to find out whether the server kept the connection.
  15306. static void probe_connection_reuse(int port, const std::string &req,
  15307. bool *announced_close, bool *reusable) {
  15308. auto error = Error::Success;
  15309. auto sock = detail::create_client_socket(
  15310. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15311. /*connection_timeout_sec=*/5, 0,
  15312. /*read_timeout_sec=*/1, 0,
  15313. /*write_timeout_sec=*/5, 0, std::string(), error);
  15314. ASSERT_NE(sock, INVALID_SOCKET);
  15315. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15316. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15317. "Host: localhost\r\n"
  15318. "Connection: close\r\n"
  15319. "\r\n";
  15320. std::string first_response;
  15321. std::string second_response;
  15322. detail::process_client_socket(
  15323. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15324. [&](Stream &strm) {
  15325. if (strm.write(req.data(), req.size()) !=
  15326. static_cast<ssize_t>(req.size())) {
  15327. return false;
  15328. }
  15329. char buf[512];
  15330. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15331. // Headers plus the two-byte body of the handler below
  15332. while (reader.getline()) {
  15333. first_response += reader.ptr();
  15334. if (first_response.find("ok") != std::string::npos) { break; }
  15335. }
  15336. if (strm.write(second.data(), second.size()) !=
  15337. static_cast<ssize_t>(second.size())) {
  15338. return true;
  15339. }
  15340. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15341. while (reader2.getline()) {
  15342. second_response += reader2.ptr();
  15343. if (second_response.find("ok") != std::string::npos) { break; }
  15344. }
  15345. return true;
  15346. });
  15347. *announced_close =
  15348. first_response.find("Connection: close") != std::string::npos;
  15349. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15350. }
  15351. class ConnectionTokenTest : public ::testing::Test {
  15352. protected:
  15353. void SetUp() override {
  15354. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15355. res.set_content("ok", "text/plain");
  15356. });
  15357. port_ = svr_.bind_to_any_port(HOST);
  15358. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15359. svr_.wait_until_ready();
  15360. }
  15361. void TearDown() override {
  15362. svr_.stop();
  15363. if (thread_.joinable()) { thread_.join(); }
  15364. }
  15365. Server svr_;
  15366. int port_ = 0;
  15367. thread thread_;
  15368. };
  15369. // "close" alongside another option still closes the connection, and the
  15370. // response says so rather than leaving the peer to discover it.
  15371. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15372. bool announced_close = false;
  15373. bool reusable = true;
  15374. probe_connection_reuse(port_,
  15375. "GET /keepalive HTTP/1.1\r\n"
  15376. "Host: localhost\r\n"
  15377. "Connection: keep-alive, close\r\n"
  15378. "\r\n",
  15379. &announced_close, &reusable);
  15380. EXPECT_TRUE(announced_close);
  15381. EXPECT_FALSE(reusable);
  15382. }
  15383. // "close" split over two field lines is the same list, so it is honored too.
  15384. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15385. bool announced_close = false;
  15386. bool reusable = true;
  15387. probe_connection_reuse(port_,
  15388. "GET /keepalive HTTP/1.1\r\n"
  15389. "Host: localhost\r\n"
  15390. "Connection: keep-alive\r\n"
  15391. "Connection: close\r\n"
  15392. "\r\n",
  15393. &announced_close, &reusable);
  15394. EXPECT_TRUE(announced_close);
  15395. EXPECT_FALSE(reusable);
  15396. }
  15397. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15398. // keep-alive in the spelling everyone actually sends keeps its connection.
  15399. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15400. bool announced_close = false;
  15401. bool reusable = false;
  15402. probe_connection_reuse(port_,
  15403. "GET /keepalive HTTP/1.0\r\n"
  15404. "Host: localhost\r\n"
  15405. "Connection: keep-alive\r\n"
  15406. "\r\n",
  15407. &announced_close, &reusable);
  15408. EXPECT_FALSE(announced_close);
  15409. EXPECT_TRUE(reusable);
  15410. }
  15411. // A token the value merely contains is not the token itself.
  15412. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15413. bool announced_close = false;
  15414. bool reusable = false;
  15415. probe_connection_reuse(port_,
  15416. "GET /keepalive HTTP/1.1\r\n"
  15417. "Host: localhost\r\n"
  15418. "Connection: notclose\r\n"
  15419. "\r\n",
  15420. &announced_close, &reusable);
  15421. EXPECT_FALSE(announced_close);
  15422. EXPECT_TRUE(reusable);
  15423. }
  15424. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15425. Server svr;
  15426. std::vector<std::string> observed_types;
  15427. svr.Get("/", [&](const Request &req, Response &res) {
  15428. observed_types = req.accept_content_types;
  15429. res.set_content("ok", "text/plain");
  15430. });
  15431. auto port = svr.bind_to_any_port(HOST);
  15432. thread t = thread([&]() { svr.listen_after_bind(); });
  15433. auto se = detail::scope_exit([&] {
  15434. svr.stop();
  15435. t.join();
  15436. ASSERT_FALSE(svr.is_running());
  15437. });
  15438. svr.wait_until_ready();
  15439. Client cli(HOST, port);
  15440. Headers headers;
  15441. headers.emplace("Accept", "text/plain;q=0.5");
  15442. headers.emplace("Accept", "application/json");
  15443. auto res = cli.Get("/", headers);
  15444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15445. EXPECT_EQ(StatusCode::OK_200, res->status);
  15446. // Sorted by q-value, so the second field line's type comes first
  15447. ASSERT_EQ(2U, observed_types.size());
  15448. EXPECT_EQ("application/json", observed_types[0]);
  15449. EXPECT_EQ("text/plain", observed_types[1]);
  15450. }
  15451. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15452. // empty field line must not contribute a bare comma to the combined value.
  15453. // parse_accept_header() rejects a leading comma outright, so a stray one would
  15454. // turn a legal request into 400 Bad Request.
  15455. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15456. Server svr;
  15457. std::vector<std::string> observed_types;
  15458. svr.Get("/", [&](const Request &req, Response &res) {
  15459. observed_types = req.accept_content_types;
  15460. res.set_content("ok", "text/plain");
  15461. });
  15462. auto port = svr.bind_to_any_port(HOST);
  15463. thread t = thread([&]() { svr.listen_after_bind(); });
  15464. auto se = detail::scope_exit([&] {
  15465. svr.stop();
  15466. t.join();
  15467. ASSERT_FALSE(svr.is_running());
  15468. });
  15469. svr.wait_until_ready();
  15470. // Empty first field line, then a real one
  15471. std::string raw_req = "GET / HTTP/1.1\r\n"
  15472. "Host: localhost\r\n"
  15473. "Accept:\r\n"
  15474. "Accept: application/json\r\n"
  15475. "Connection: close\r\n"
  15476. "\r\n";
  15477. std::string out;
  15478. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15479. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15480. ASSERT_EQ(1U, observed_types.size());
  15481. EXPECT_EQ("application/json", observed_types[0]);
  15482. }
  15483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15484. // An encoding offered on a later Accept-Encoding field line is still offered.
  15485. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15486. Server svr;
  15487. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15488. res.set_content(std::string(1024, 'x'), "text/plain");
  15489. });
  15490. auto port = svr.bind_to_any_port(HOST);
  15491. thread t = thread([&]() { svr.listen_after_bind(); });
  15492. auto se = detail::scope_exit([&] {
  15493. svr.stop();
  15494. t.join();
  15495. ASSERT_FALSE(svr.is_running());
  15496. });
  15497. svr.wait_until_ready();
  15498. Client cli(HOST, port);
  15499. cli.set_decompress(false);
  15500. Headers headers;
  15501. headers.emplace("Accept-Encoding", "identity");
  15502. headers.emplace("Accept-Encoding", "gzip");
  15503. auto res = cli.Get("/", headers);
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_EQ(StatusCode::OK_200, res->status);
  15506. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15507. }
  15508. #endif
  15509. #ifndef _WIN32
  15510. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15511. Server svr;
  15512. svr.Post("/post", [&](const Request &req, Response &res) {
  15513. res.set_content(req.body, "text/plain");
  15514. });
  15515. svr.Put("/put", [&](const Request &req, Response &res) {
  15516. res.set_content(req.body, "text/plain");
  15517. });
  15518. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15519. res.set_content(req.body, "text/plain");
  15520. });
  15521. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15522. res.set_content(req.body, "text/plain");
  15523. });
  15524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15525. auto se = detail::scope_exit([&] {
  15526. svr.stop();
  15527. t.join();
  15528. ASSERT_FALSE(svr.is_running());
  15529. });
  15530. svr.wait_until_ready();
  15531. std::string resp;
  15532. // POST without Content-Length
  15533. ASSERT_TRUE(send_request(5,
  15534. "POST /post HTTP/1.1\r\n"
  15535. "Host: localhost\r\n"
  15536. "Connection: close\r\n"
  15537. "\r\n",
  15538. &resp));
  15539. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15540. // PUT without Content-Length
  15541. resp.clear();
  15542. ASSERT_TRUE(send_request(5,
  15543. "PUT /put HTTP/1.1\r\n"
  15544. "Host: localhost\r\n"
  15545. "Connection: close\r\n"
  15546. "\r\n",
  15547. &resp));
  15548. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15549. // PATCH without Content-Length
  15550. resp.clear();
  15551. ASSERT_TRUE(send_request(5,
  15552. "PATCH /patch HTTP/1.1\r\n"
  15553. "Host: localhost\r\n"
  15554. "Connection: close\r\n"
  15555. "\r\n",
  15556. &resp));
  15557. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15558. // DELETE without Content-Length
  15559. resp.clear();
  15560. ASSERT_TRUE(send_request(5,
  15561. "DELETE /delete HTTP/1.1\r\n"
  15562. "Host: localhost\r\n"
  15563. "Connection: close\r\n"
  15564. "\r\n",
  15565. &resp));
  15566. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15567. }
  15568. #endif
  15569. //==============================================================================
  15570. // open_stream() Tests
  15571. //==============================================================================
  15572. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15573. std::string result;
  15574. char buf[8192];
  15575. ssize_t n;
  15576. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15577. result.append(buf, static_cast<size_t>(n));
  15578. }
  15579. return result;
  15580. }
  15581. // Mock stream for unit tests
  15582. class MockStream : public Stream {
  15583. public:
  15584. std::string data;
  15585. size_t pos = 0;
  15586. ssize_t error_after = -1; // -1 = no error
  15587. explicit MockStream(const std::string &d, ssize_t err = -1)
  15588. : data(d), error_after(err) {}
  15589. bool is_readable() const override { return true; }
  15590. bool wait_readable() const override { return true; }
  15591. bool wait_writable() const override { return true; }
  15592. ssize_t read(char *ptr, size_t size) override {
  15593. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15594. if (pos >= data.size()) return 0;
  15595. size_t limit =
  15596. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15597. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15598. std::memcpy(ptr, data.data() + pos, to_read);
  15599. pos += to_read;
  15600. return static_cast<ssize_t>(to_read);
  15601. }
  15602. ssize_t write(const char *, size_t) override { return -1; }
  15603. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15604. ip = "127.0.0.1";
  15605. port = 0;
  15606. }
  15607. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15608. ip = "127.0.0.1";
  15609. port = 0;
  15610. }
  15611. socket_t socket() const override { return INVALID_SOCKET; }
  15612. time_t duration() const override { return 0; }
  15613. };
  15614. TEST(StreamHandleTest, Basic) {
  15615. ClientImpl::StreamHandle handle;
  15616. EXPECT_FALSE(handle.is_valid());
  15617. handle.response = detail::make_unique<Response>();
  15618. handle.error = Error::Connection;
  15619. EXPECT_FALSE(handle.is_valid());
  15620. handle.error = Error::Success;
  15621. EXPECT_TRUE(handle.is_valid());
  15622. }
  15623. TEST(BodyReaderTest, Basic) {
  15624. MockStream stream("Hello, World!");
  15625. detail::BodyReader reader;
  15626. reader.stream = &stream;
  15627. reader.content_length = 13;
  15628. char buf[32];
  15629. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15630. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15631. EXPECT_TRUE(reader.eof);
  15632. }
  15633. TEST(BodyReaderTest, NoStream) {
  15634. detail::BodyReader reader;
  15635. char buf[32];
  15636. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15637. EXPECT_EQ(Error::Connection, reader.last_error);
  15638. }
  15639. TEST(BodyReaderTest, Error) {
  15640. MockStream stream("Hello, World!", 5);
  15641. detail::BodyReader reader;
  15642. reader.stream = &stream;
  15643. reader.content_length = 13;
  15644. char buf[32];
  15645. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15646. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15647. EXPECT_EQ(Error::Read, reader.last_error);
  15648. }
  15649. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15650. // Mock-based StreamHandle tests relying on private internals are removed.
  15651. class OpenStreamTest : public ::testing::Test {
  15652. protected:
  15653. void SetUp() override {
  15654. svr_.Get("/hello", [](const Request &, Response &res) {
  15655. res.set_content("Hello World!", "text/plain");
  15656. });
  15657. svr_.Get("/large", [](const Request &, Response &res) {
  15658. res.set_content(std::string(10000, 'X'), "text/plain");
  15659. });
  15660. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15661. res.set_content("Hello World!", "image/jpeg");
  15662. res.set_header("Content-Encoding", "UTF-8");
  15663. });
  15664. svr_.Get("/chunked", [](const Request &, Response &res) {
  15665. res.set_chunked_content_provider("text/plain",
  15666. [](size_t offset, DataSink &sink) {
  15667. if (offset < 15) {
  15668. sink.write("chunk", 5);
  15669. return true;
  15670. }
  15671. sink.done();
  15672. return true;
  15673. });
  15674. });
  15675. svr_.Get("/compressible", [](const Request &, Response &res) {
  15676. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15677. DataSink &sink) {
  15678. if (offset < 100 * 1024) {
  15679. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15680. sink.write(chunk.data(), chunk.size());
  15681. return true;
  15682. }
  15683. sink.done();
  15684. return true;
  15685. });
  15686. });
  15687. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15688. [](const Request & /*req*/, Response &res) {
  15689. auto i = new int(0);
  15690. res.set_header("Trailer", "Content-Length, X-Allowed");
  15691. res.set_chunked_content_provider(
  15692. "text/plain",
  15693. [i](size_t /*offset*/, DataSink &sink) {
  15694. switch (*i) {
  15695. case 0: sink.os << "123"; break;
  15696. case 1: sink.os << "456"; break;
  15697. case 2: sink.os << "789"; break;
  15698. case 3: {
  15699. sink.done_with_trailer(
  15700. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15701. } break;
  15702. }
  15703. (*i)++;
  15704. return true;
  15705. },
  15706. [i](bool success) {
  15707. EXPECT_TRUE(success);
  15708. delete i;
  15709. });
  15710. });
  15711. // Echo headers endpoint for header-related tests
  15712. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15713. std::string body;
  15714. for (const auto &h : req.headers) {
  15715. body.append(h.first);
  15716. body.push_back(':');
  15717. body.append(h.second);
  15718. body.push_back('\n');
  15719. }
  15720. res.set_content(body, "text/plain");
  15721. });
  15722. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15723. std::string body;
  15724. for (const auto &h : req.headers) {
  15725. body.append(h.first);
  15726. body.push_back(':');
  15727. body.append(h.second);
  15728. body.push_back('\n');
  15729. }
  15730. res.set_content(body, "text/plain");
  15731. });
  15732. port_ = svr_.bind_to_any_port("127.0.0.1");
  15733. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15734. svr_.wait_until_ready();
  15735. }
  15736. void TearDown() override {
  15737. svr_.stop();
  15738. if (thread_.joinable()) thread_.join();
  15739. }
  15740. Server svr_;
  15741. std::thread thread_;
  15742. int port_ = 0;
  15743. };
  15744. TEST_F(OpenStreamTest, Basic) {
  15745. Client cli("127.0.0.1", port_);
  15746. auto handle = cli.open_stream("GET", "/hello");
  15747. EXPECT_TRUE(handle.is_valid());
  15748. EXPECT_EQ("Hello World!", read_all(handle));
  15749. }
  15750. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15751. Client cli("127.0.0.1", port_);
  15752. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15753. ASSERT_TRUE(handle.is_valid());
  15754. EXPECT_EQ("Hello World!", read_all(handle));
  15755. }
  15756. TEST_F(OpenStreamTest, SmallBuffer) {
  15757. Client cli("127.0.0.1", port_);
  15758. auto handle = cli.open_stream("GET", "/hello");
  15759. std::string result;
  15760. char buf[4];
  15761. ssize_t n;
  15762. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15763. result.append(buf, static_cast<size_t>(n));
  15764. EXPECT_EQ("Hello World!", result);
  15765. }
  15766. TEST_F(OpenStreamTest, DefaultHeaders) {
  15767. Client cli("127.0.0.1", port_);
  15768. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15769. {
  15770. auto handle = cli.open_stream("GET", "/echo-headers");
  15771. ASSERT_TRUE(handle.is_valid());
  15772. auto body = read_all(handle);
  15773. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15774. std::string::npos);
  15775. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15776. std::string::npos);
  15777. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15778. }
  15779. // open_stream POST with body and no explicit content_type should NOT add
  15780. // text/plain Content-Type (behavior differs from non-streaming path), but
  15781. // should include Content-Length
  15782. {
  15783. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15784. ASSERT_TRUE(handle.is_valid());
  15785. auto body = read_all(handle);
  15786. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15787. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15788. }
  15789. // open_stream POST with explicit Content-Type should preserve it
  15790. {
  15791. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15792. {{"Content-Type", "application/custom"}},
  15793. "{}", "application/custom");
  15794. ASSERT_TRUE(handle.is_valid());
  15795. auto body = read_all(handle);
  15796. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15797. }
  15798. // User-specified User-Agent must not be overwritten for stream API
  15799. {
  15800. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15801. {{"User-Agent", "MyAgent/1.2"}});
  15802. ASSERT_TRUE(handle.is_valid());
  15803. auto body = read_all(handle);
  15804. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15805. }
  15806. }
  15807. TEST_F(OpenStreamTest, Large) {
  15808. Client cli("127.0.0.1", port_);
  15809. auto handle = cli.open_stream("GET", "/large");
  15810. EXPECT_EQ(10000u, read_all(handle).size());
  15811. }
  15812. TEST_F(OpenStreamTest, ConnectionError) {
  15813. Client cli("127.0.0.1", 9999);
  15814. auto handle = cli.open_stream("GET", "/hello");
  15815. EXPECT_FALSE(handle.is_valid());
  15816. }
  15817. TEST_F(OpenStreamTest, Chunked) {
  15818. Client cli("127.0.0.1", port_);
  15819. auto handle = cli.open_stream("GET", "/chunked");
  15820. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15821. "Transfer-Encoding") == "chunked");
  15822. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15823. }
  15824. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15825. Client cli("127.0.0.1", port_);
  15826. auto handle =
  15827. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15828. ASSERT_TRUE(handle.is_valid());
  15829. // Consume body to allow trailers to be received/parsed
  15830. auto body = read_all(handle);
  15831. // Explicitly parse trailers (ensure trailers are available for assertion)
  15832. handle.parse_trailers_if_needed();
  15833. EXPECT_EQ(std::string("123456789"), body);
  15834. // The response should include a Trailer header declaring both names
  15835. ASSERT_TRUE(handle.response);
  15836. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15837. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15838. handle.response->get_header_value("Trailer"));
  15839. // Prohibited trailer must not be present
  15840. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15841. // Allowed trailer should be present
  15842. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15843. EXPECT_EQ(std::string("yes"),
  15844. handle.response->get_trailer_value("X-Allowed"));
  15845. // Verify trailers are NOT present as regular headers
  15846. EXPECT_EQ(std::string(""),
  15847. handle.response->get_header_value("Content-Length"));
  15848. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15849. }
  15850. static std::thread serve_single_response(std::promise<int> &port_promise,
  15851. const std::string &response) {
  15852. return std::thread([&port_promise, response] {
  15853. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15854. default_socket_options(srv);
  15855. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15856. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15857. sockaddr_in addr{};
  15858. addr.sin_family = AF_INET;
  15859. addr.sin_port = htons(0); // Let OS assign a free port
  15860. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15861. int opt = 1;
  15862. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15863. #ifdef _WIN32
  15864. reinterpret_cast<const char *>(&opt),
  15865. #else
  15866. &opt,
  15867. #endif
  15868. sizeof(opt));
  15869. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15870. ::listen(srv, 1) != 0) {
  15871. port_promise.set_value(-1);
  15872. detail::close_socket(srv);
  15873. return;
  15874. }
  15875. socklen_t addr_len = sizeof(addr);
  15876. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15877. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15878. sockaddr_in cli_addr{};
  15879. socklen_t cli_len = sizeof(cli_addr);
  15880. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15881. if (cli != INVALID_SOCKET) {
  15882. // Read the complete HTTP request (until the blank line that terminates
  15883. // headers) before sending the response. If the server closes the socket
  15884. // while the client's request data is still unread in the kernel receive
  15885. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15886. // connection on both sides: it discards the client's receive buffer
  15887. // (which already holds our response) and causes any in-progress write on
  15888. // the client to fail with ECONNRESET. Reading all request data first
  15889. // ensures close() emits a graceful FIN.
  15890. {
  15891. char rbuf[256];
  15892. std::string req;
  15893. while (req.find("\r\n\r\n") == std::string::npos) {
  15894. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15895. if (n <= 0) { break; }
  15896. req.append(rbuf, static_cast<size_t>(n));
  15897. }
  15898. }
  15899. ::send(cli,
  15900. #ifdef _WIN32
  15901. static_cast<const char *>(response.c_str()),
  15902. static_cast<int>(response.size()),
  15903. #else
  15904. response.c_str(), response.size(),
  15905. #endif
  15906. 0);
  15907. detail::close_socket(cli);
  15908. }
  15909. detail::close_socket(srv);
  15910. });
  15911. }
  15912. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15913. #ifndef _WIN32
  15914. signal(SIGPIPE, SIG_IGN);
  15915. #endif
  15916. std::promise<int> port_promise;
  15917. auto port_future = port_promise.get_future();
  15918. auto server_thread =
  15919. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15920. "Content-Type: text/plain\r\n"
  15921. "Content-Length: not-a-number\r\n"
  15922. "Connection: close\r\n"
  15923. "\r\n"
  15924. "hello");
  15925. auto port = port_future.get();
  15926. ASSERT_GT(port, 0);
  15927. Client cli("127.0.0.1", port);
  15928. auto handle = cli.open_stream("GET", "/");
  15929. EXPECT_FALSE(handle.is_valid());
  15930. server_thread.join();
  15931. }
  15932. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15933. #ifndef _WIN32
  15934. signal(SIGPIPE, SIG_IGN);
  15935. #endif
  15936. std::promise<int> port_promise;
  15937. auto port_future = port_promise.get_future();
  15938. auto server_thread = serve_single_response(
  15939. port_promise, "HTTP/1.1 200 OK\r\n"
  15940. "Content-Type: text/plain\r\n"
  15941. "Content-Length: 99999999999999999999999999\r\n"
  15942. "Connection: close\r\n"
  15943. "\r\n"
  15944. "hello");
  15945. auto port = port_future.get();
  15946. ASSERT_GT(port, 0);
  15947. // Historically std::stoull would throw std::out_of_range here and crash
  15948. // the process, then parsing silently clamped to a bogus framing length and
  15949. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15950. // so the stream fails to open, matching the not-a-number case above. The
  15951. // process still must NOT terminate.
  15952. Client cli("127.0.0.1", port);
  15953. auto handle = cli.open_stream("GET", "/");
  15954. EXPECT_FALSE(handle.is_valid());
  15955. server_thread.join();
  15956. }
  15957. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15958. TEST_F(OpenStreamTest, Gzip) {
  15959. Client cli("127.0.0.1", port_);
  15960. auto handle = cli.open_stream("GET", "/compressible", {},
  15961. {{"Accept-Encoding", "gzip"}});
  15962. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15963. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15964. }
  15965. #endif
  15966. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15967. TEST_F(OpenStreamTest, Brotli) {
  15968. Client cli("127.0.0.1", port_);
  15969. auto handle =
  15970. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15971. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15972. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15973. }
  15974. #endif
  15975. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15976. TEST_F(OpenStreamTest, Zstd) {
  15977. Client cli("127.0.0.1", port_);
  15978. auto handle = cli.open_stream("GET", "/compressible", {},
  15979. {{"Accept-Encoding", "zstd"}});
  15980. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15981. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15982. }
  15983. #endif
  15984. #ifdef CPPHTTPLIB_SSL_ENABLED
  15985. class SSLOpenStreamTest : public ::testing::Test {
  15986. protected:
  15987. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15988. void SetUp() override {
  15989. svr_.Get("/hello", [](const Request &, Response &res) {
  15990. res.set_content("Hello SSL World!", "text/plain");
  15991. });
  15992. svr_.Get("/chunked", [](const Request &, Response &res) {
  15993. res.set_chunked_content_provider("text/plain",
  15994. [](size_t offset, DataSink &sink) {
  15995. if (offset < 15) {
  15996. sink.write("chunk", 5);
  15997. return true;
  15998. }
  15999. sink.done();
  16000. return true;
  16001. });
  16002. });
  16003. svr_.Post("/echo", [](const Request &req, Response &res) {
  16004. res.set_content(req.body, req.get_header_value("Content-Type"));
  16005. });
  16006. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16007. std::string body = req.body;
  16008. res.set_chunked_content_provider(
  16009. "text/plain", [body](size_t offset, DataSink &sink) {
  16010. if (offset < body.size()) {
  16011. sink.write(body.data() + offset, body.size() - offset);
  16012. }
  16013. sink.done();
  16014. return true;
  16015. });
  16016. });
  16017. port_ = svr_.bind_to_any_port("127.0.0.1");
  16018. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16019. svr_.wait_until_ready();
  16020. }
  16021. void TearDown() override {
  16022. svr_.stop();
  16023. if (thread_.joinable()) thread_.join();
  16024. }
  16025. SSLServer svr_;
  16026. std::thread thread_;
  16027. int port_ = 0;
  16028. };
  16029. TEST_F(SSLOpenStreamTest, Basic) {
  16030. SSLClient cli("127.0.0.1", port_);
  16031. cli.enable_server_certificate_verification(false);
  16032. auto handle = cli.open_stream("GET", "/hello");
  16033. ASSERT_TRUE(handle.is_valid());
  16034. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16035. }
  16036. TEST_F(SSLOpenStreamTest, Chunked) {
  16037. SSLClient cli("127.0.0.1", port_);
  16038. cli.enable_server_certificate_verification(false);
  16039. auto handle = cli.open_stream("GET", "/chunked");
  16040. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16041. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16042. "Transfer-Encoding") == "chunked");
  16043. auto body = read_all(handle);
  16044. EXPECT_EQ("chunkchunkchunk", body);
  16045. }
  16046. TEST_F(SSLOpenStreamTest, Post) {
  16047. SSLClient cli("127.0.0.1", port_);
  16048. cli.enable_server_certificate_verification(false);
  16049. auto handle =
  16050. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16051. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16052. EXPECT_EQ(200, handle.response->status);
  16053. auto body = read_all(handle);
  16054. EXPECT_EQ("Hello SSL POST", body);
  16055. }
  16056. TEST_F(SSLOpenStreamTest, PostChunked) {
  16057. SSLClient cli("127.0.0.1", port_);
  16058. cli.enable_server_certificate_verification(false);
  16059. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16060. "Chunked SSL Data", "text/plain");
  16061. ASSERT_TRUE(handle.is_valid());
  16062. EXPECT_EQ(200, handle.response->status);
  16063. auto body = read_all(handle);
  16064. EXPECT_EQ("Chunked SSL Data", body);
  16065. }
  16066. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16067. // Content-Length is terminated by the server closing the connection. When the
  16068. // SSL peer sends a close_notify after the body, the client must treat it as a
  16069. // clean EOF and return a successful response rather than an error.
  16070. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16072. ASSERT_TRUE(svr.is_valid());
  16073. svr.set_keep_alive_max_count(1);
  16074. const std::string expected_body = "Hello from connection-close response!";
  16075. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16076. res.set_content_provider("text/plain",
  16077. [&](size_t offset, DataSink &sink) -> bool {
  16078. if (offset < expected_body.size()) {
  16079. sink.write(expected_body.data() + offset,
  16080. expected_body.size() - offset);
  16081. }
  16082. sink.done();
  16083. return true;
  16084. });
  16085. });
  16086. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16087. auto se = detail::scope_exit([&] {
  16088. svr.stop();
  16089. listen_thread.join();
  16090. ASSERT_FALSE(svr.is_running());
  16091. });
  16092. svr.wait_until_ready();
  16093. SSLClient cli(HOST, PORT);
  16094. cli.enable_server_certificate_verification(false);
  16095. auto res = cli.Get("/no-content-length");
  16096. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16097. EXPECT_EQ(StatusCode::OK_200, res->status);
  16098. EXPECT_EQ(expected_body, res->body);
  16099. }
  16100. #endif // CPPHTTPLIB_SSL_ENABLED
  16101. //==============================================================================
  16102. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16103. // results for various scenarios.
  16104. //==============================================================================
  16105. TEST(ParityTest, GetVsOpenStream) {
  16106. Server svr;
  16107. const std::string path = "/parity";
  16108. const std::string content = "Parity test content: hello world";
  16109. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16110. res.set_content(content, "text/plain");
  16111. });
  16112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16113. auto se = detail::scope_exit([&] {
  16114. svr.stop();
  16115. t.join();
  16116. ASSERT_FALSE(svr.is_running());
  16117. });
  16118. svr.wait_until_ready();
  16119. Client cli(HOST, PORT);
  16120. // Non-stream path
  16121. auto r1 = cli.Get(path);
  16122. ASSERT_TRUE(r1);
  16123. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16124. // Stream path
  16125. auto h = cli.open_stream("GET", path);
  16126. ASSERT_TRUE(h.is_valid());
  16127. EXPECT_EQ(r1->body, read_all(h));
  16128. }
  16129. // Helper to compress data with provided compressor type T
  16130. template <typename Compressor>
  16131. static std::string compress_payload_for_parity(const std::string &in) {
  16132. std::string out;
  16133. Compressor compressor;
  16134. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16135. [&](const char *data, size_t n) {
  16136. out.append(data, n);
  16137. return true;
  16138. });
  16139. EXPECT_TRUE(ok);
  16140. return out;
  16141. }
  16142. // Helper function for compression parity tests
  16143. template <typename Compressor>
  16144. static void test_compression_parity(const std::string &original,
  16145. const std::string &path,
  16146. const std::string &encoding) {
  16147. const std::string compressed =
  16148. compress_payload_for_parity<Compressor>(original);
  16149. Server svr;
  16150. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16151. res.set_content(compressed, "application/octet-stream");
  16152. res.set_header("Content-Encoding", encoding);
  16153. });
  16154. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. });
  16160. svr.wait_until_ready();
  16161. Client cli(HOST, PORT);
  16162. // Non-streaming
  16163. {
  16164. auto res = cli.Get(path);
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. EXPECT_EQ(original, res->body);
  16168. }
  16169. // Streaming
  16170. {
  16171. auto h = cli.open_stream("GET", path);
  16172. ASSERT_TRUE(h.is_valid());
  16173. EXPECT_EQ(original, read_all(h));
  16174. }
  16175. }
  16176. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16177. TEST(ParityTest, Gzip) {
  16178. test_compression_parity<detail::gzip_compressor>(
  16179. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16180. }
  16181. #endif
  16182. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16183. TEST(ParityTest, Brotli) {
  16184. test_compression_parity<detail::brotli_compressor>(
  16185. "Hello, brotli parity test payload", "/parity-br", "br");
  16186. }
  16187. #endif
  16188. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16189. TEST(ParityTest, Zstd) {
  16190. test_compression_parity<detail::zstd_compressor>(
  16191. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16192. }
  16193. #endif
  16194. //==============================================================================
  16195. // New Stream API Tests
  16196. //==============================================================================
  16197. inline std::string read_body(httplib::stream::Result &result) {
  16198. std::string body;
  16199. while (result.next()) {
  16200. body.append(result.data(), result.size());
  16201. }
  16202. return body;
  16203. }
  16204. TEST(ClientConnectionTest, Basic) {
  16205. httplib::ClientConnection conn;
  16206. EXPECT_FALSE(conn.is_open());
  16207. conn.sock = 1;
  16208. EXPECT_TRUE(conn.is_open());
  16209. httplib::ClientConnection conn2(std::move(conn));
  16210. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16211. conn2.sock = INVALID_SOCKET;
  16212. }
  16213. // Unified test server for all stream::* tests
  16214. class StreamApiTest : public ::testing::Test {
  16215. protected:
  16216. void SetUp() override {
  16217. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16218. res.set_content("Hello World!", "text/plain");
  16219. });
  16220. svr_.Get("/echo-params",
  16221. [](const httplib::Request &req, httplib::Response &res) {
  16222. std::string r;
  16223. for (const auto &p : req.params) {
  16224. if (!r.empty()) r += "&";
  16225. r += p.first + "=" + p.second;
  16226. }
  16227. res.set_content(r, "text/plain");
  16228. });
  16229. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16230. res.set_content(req.body, req.get_header_value("Content-Type"));
  16231. });
  16232. svr_.Post("/echo-headers",
  16233. [](const httplib::Request &req, httplib::Response &res) {
  16234. std::string r;
  16235. for (const auto &h : req.headers)
  16236. r += h.first + ": " + h.second + "\n";
  16237. res.set_content(r, "text/plain");
  16238. });
  16239. svr_.Post("/echo-params",
  16240. [](const httplib::Request &req, httplib::Response &res) {
  16241. std::string r = "params:";
  16242. for (const auto &p : req.params)
  16243. r += p.first + "=" + p.second + ";";
  16244. res.set_content(r + " body:" + req.body, "text/plain");
  16245. });
  16246. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16247. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16248. });
  16249. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16250. res.set_content("PUT:" + req.body, "text/plain");
  16251. });
  16252. svr_.Patch("/echo",
  16253. [](const httplib::Request &req, httplib::Response &res) {
  16254. res.set_content("PATCH:" + req.body, "text/plain");
  16255. });
  16256. svr_.Delete(
  16257. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16258. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16259. "text/plain");
  16260. });
  16261. svr_.Get("/head-test",
  16262. [](const httplib::Request &, httplib::Response &res) {
  16263. res.set_content("body for HEAD", "text/plain");
  16264. });
  16265. svr_.Options("/options",
  16266. [](const httplib::Request &, httplib::Response &res) {
  16267. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16268. });
  16269. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16270. svr_.wait_until_ready();
  16271. }
  16272. void TearDown() override {
  16273. svr_.stop();
  16274. if (thread_.joinable()) thread_.join();
  16275. }
  16276. httplib::Server svr_;
  16277. std::thread thread_;
  16278. };
  16279. // stream::Get tests
  16280. TEST_F(StreamApiTest, GetBasic) {
  16281. httplib::Client cli(HOST, PORT);
  16282. auto result = httplib::stream::Get(cli, "/hello");
  16283. ASSERT_TRUE(result.is_valid());
  16284. EXPECT_EQ(200, result.status());
  16285. EXPECT_EQ("Hello World!", read_body(result));
  16286. }
  16287. TEST_F(StreamApiTest, GetWithParams) {
  16288. httplib::Client cli(HOST, PORT);
  16289. httplib::Params params{{"foo", "bar"}};
  16290. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16291. ASSERT_TRUE(result.is_valid());
  16292. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16293. }
  16294. TEST_F(StreamApiTest, GetConnectionError) {
  16295. httplib::Client cli(HOST, 9999);
  16296. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16297. }
  16298. TEST_F(StreamApiTest, Get404) {
  16299. httplib::Client cli(HOST, PORT);
  16300. auto result = httplib::stream::Get(cli, "/nonexistent");
  16301. EXPECT_TRUE(result.is_valid());
  16302. EXPECT_EQ(404, result.status());
  16303. }
  16304. // stream::Post tests
  16305. TEST_F(StreamApiTest, PostBasic) {
  16306. httplib::Client cli(HOST, PORT);
  16307. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16308. "application/json");
  16309. ASSERT_TRUE(result.is_valid());
  16310. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16311. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16312. }
  16313. TEST_F(StreamApiTest, PostWithHeaders) {
  16314. httplib::Client cli(HOST, PORT);
  16315. httplib::Headers headers{{"X-Custom", "value"}};
  16316. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16317. "text/plain");
  16318. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16319. }
  16320. TEST_F(StreamApiTest, PostWithParams) {
  16321. httplib::Client cli(HOST, PORT);
  16322. httplib::Params params{{"k", "v"}};
  16323. auto result =
  16324. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16325. auto body = read_body(result);
  16326. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16327. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16328. }
  16329. TEST_F(StreamApiTest, PostLarge) {
  16330. httplib::Client cli(HOST, PORT);
  16331. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16332. size_t total = 0;
  16333. while (result.next()) {
  16334. total += result.size();
  16335. }
  16336. EXPECT_EQ(100u * 1024u, total);
  16337. }
  16338. // stream::Put/Patch tests
  16339. TEST_F(StreamApiTest, PutAndPatch) {
  16340. httplib::Client cli(HOST, PORT);
  16341. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16342. EXPECT_EQ("PUT:test", read_body(put));
  16343. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16344. EXPECT_EQ("PATCH:test", read_body(patch));
  16345. }
  16346. // stream::Delete tests
  16347. TEST_F(StreamApiTest, Delete) {
  16348. httplib::Client cli(HOST, PORT);
  16349. auto del1 = httplib::stream::Delete(cli, "/resource");
  16350. EXPECT_EQ("Deleted", read_body(del1));
  16351. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16352. EXPECT_EQ("Deleted:data", read_body(del2));
  16353. }
  16354. // stream::Head/Options tests
  16355. TEST_F(StreamApiTest, HeadAndOptions) {
  16356. httplib::Client cli(HOST, PORT);
  16357. auto head = httplib::stream::Head(cli, "/head-test");
  16358. EXPECT_TRUE(head.is_valid());
  16359. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16360. auto opts = httplib::stream::Options(cli, "/options");
  16361. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16362. }
  16363. // SSL stream::* tests
  16364. #ifdef CPPHTTPLIB_SSL_ENABLED
  16365. class SSLStreamApiTest : public ::testing::Test {
  16366. protected:
  16367. void SetUp() override {
  16368. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16369. res.set_content("Hello SSL!", "text/plain");
  16370. });
  16371. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16372. res.set_content(req.body, "text/plain");
  16373. });
  16374. port_ = svr_.bind_to_any_port("127.0.0.1");
  16375. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16376. svr_.wait_until_ready();
  16377. }
  16378. void TearDown() override {
  16379. svr_.stop();
  16380. if (thread_.joinable()) thread_.join();
  16381. }
  16382. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16383. std::thread thread_;
  16384. int port_ = 0;
  16385. };
  16386. TEST_F(SSLStreamApiTest, GetAndPost) {
  16387. httplib::SSLClient cli("127.0.0.1", port_);
  16388. cli.enable_server_certificate_verification(false);
  16389. auto get = httplib::stream::Get(cli, "/hello");
  16390. EXPECT_EQ("Hello SSL!", read_body(get));
  16391. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16392. EXPECT_EQ("test", read_body(post));
  16393. }
  16394. #endif
  16395. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16396. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16397. // BodyReader
  16398. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16399. // Test that read timeout during streaming is detected
  16400. // Use a large content-length response where server delays mid-stream
  16401. Server svr;
  16402. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16403. // Send a large response with delay in the middle
  16404. res.set_content_provider(
  16405. 1000, // content_length
  16406. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16407. if (offset < 100) {
  16408. // Send first 100 bytes immediately
  16409. std::string data(100, 'A');
  16410. sink.write(data.c_str(), data.size());
  16411. return true;
  16412. }
  16413. // Then delay longer than client timeout
  16414. std::this_thread::sleep_for(std::chrono::seconds(3));
  16415. std::string data(900, 'B');
  16416. sink.write(data.c_str(), data.size());
  16417. return true;
  16418. });
  16419. });
  16420. auto port = 8091;
  16421. std::thread t([&]() { svr.listen("localhost", port); });
  16422. svr.wait_until_ready();
  16423. Client cli("localhost", port);
  16424. cli.set_read_timeout(1, 0); // 1 second timeout
  16425. auto handle = cli.open_stream("GET", "/slow-stream");
  16426. ASSERT_TRUE(handle.is_valid());
  16427. char buf[256];
  16428. ssize_t total = 0;
  16429. ssize_t n;
  16430. bool got_error = false;
  16431. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16432. total += n;
  16433. }
  16434. if (n < 0) {
  16435. got_error = true;
  16436. // Should be timeout or read error
  16437. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16438. handle.get_read_error() == Error::Read)
  16439. << "Actual error: " << to_string(handle.get_read_error());
  16440. }
  16441. // Either we got an error, or we got less data than expected
  16442. EXPECT_TRUE(got_error || total < 1000)
  16443. << "Expected timeout but got all " << total << " bytes";
  16444. svr.stop();
  16445. t.join();
  16446. }
  16447. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16448. // Test connection closed detection via BodyReader
  16449. Server svr;
  16450. std::atomic<bool> close_now{false};
  16451. svr.Get("/will-close", [&](const Request &, Response &res) {
  16452. res.set_content_provider(
  16453. 10000, // Large content_length that we won't fully send
  16454. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16455. if (offset < 100) {
  16456. std::string data(100, 'X');
  16457. sink.write(data.c_str(), data.size());
  16458. return true;
  16459. }
  16460. // Wait for signal then abort
  16461. while (!close_now) {
  16462. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16463. }
  16464. return false; // Abort - server will close connection
  16465. });
  16466. });
  16467. auto port = 8092;
  16468. std::thread t([&]() { svr.listen("localhost", port); });
  16469. svr.wait_until_ready();
  16470. Client cli("localhost", port);
  16471. auto handle = cli.open_stream("GET", "/will-close");
  16472. ASSERT_TRUE(handle.is_valid());
  16473. char buf[256];
  16474. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16475. EXPECT_GT(n, 0) << "First read should succeed";
  16476. // Signal server to close
  16477. close_now = true;
  16478. // Keep reading until error or EOF
  16479. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16480. // Keep reading
  16481. }
  16482. // Should get an error since content_length wasn't satisfied
  16483. if (n < 0) {
  16484. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16485. handle.get_read_error() == Error::Read)
  16486. << "Actual error: " << to_string(handle.get_read_error());
  16487. }
  16488. svr.stop();
  16489. t.join();
  16490. }
  16491. #ifdef CPPHTTPLIB_SSL_ENABLED
  16492. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16493. // Test that read timeout during SSL streaming is detected
  16494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16495. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16496. res.set_content_provider(
  16497. 1000, "text/plain",
  16498. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16499. if (offset < 100) {
  16500. std::string data(100, 'A');
  16501. sink.write(data.c_str(), data.size());
  16502. return true;
  16503. }
  16504. std::this_thread::sleep_for(std::chrono::seconds(3));
  16505. std::string data(900, 'B');
  16506. sink.write(data.c_str(), data.size());
  16507. return true;
  16508. });
  16509. });
  16510. auto port = 8093;
  16511. std::thread t([&]() { svr.listen("localhost", port); });
  16512. svr.wait_until_ready();
  16513. SSLClient cli("localhost", port);
  16514. cli.enable_server_certificate_verification(false);
  16515. cli.set_read_timeout(1, 0); // 1 second timeout
  16516. auto handle = cli.open_stream("GET", "/slow-stream");
  16517. ASSERT_TRUE(handle.is_valid());
  16518. char buf[256];
  16519. ssize_t total = 0;
  16520. ssize_t n;
  16521. bool got_error = false;
  16522. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16523. total += n;
  16524. }
  16525. if (n < 0) {
  16526. got_error = true;
  16527. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16528. handle.get_read_error() == Error::Read)
  16529. << "Actual error: " << to_string(handle.get_read_error());
  16530. }
  16531. EXPECT_TRUE(got_error || total < 1000)
  16532. << "Expected timeout but got all " << total << " bytes";
  16533. svr.stop();
  16534. t.join();
  16535. }
  16536. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16537. // Test SSL connection closed detection
  16538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16539. std::atomic<bool> close_now{false};
  16540. svr.Get("/will-close", [&](const Request &, Response &res) {
  16541. res.set_content_provider(
  16542. 10000, "text/plain",
  16543. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16544. if (offset < 100) {
  16545. std::string data(100, 'X');
  16546. sink.write(data.c_str(), data.size());
  16547. return true;
  16548. }
  16549. while (!close_now) {
  16550. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16551. }
  16552. return false;
  16553. });
  16554. });
  16555. auto port = 8094;
  16556. std::thread t([&]() { svr.listen("localhost", port); });
  16557. svr.wait_until_ready();
  16558. SSLClient cli("localhost", port);
  16559. cli.enable_server_certificate_verification(false);
  16560. auto handle = cli.open_stream("GET", "/will-close");
  16561. ASSERT_TRUE(handle.is_valid());
  16562. char buf[256];
  16563. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16564. EXPECT_GT(n, 0);
  16565. // Signal server to close
  16566. close_now = true;
  16567. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16568. // Keep reading
  16569. }
  16570. if (n < 0) {
  16571. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16572. handle.get_read_error() == Error::Read)
  16573. << "Actual error: " << to_string(handle.get_read_error());
  16574. }
  16575. svr.stop();
  16576. t.join();
  16577. }
  16578. #endif
  16579. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16580. using namespace httplib;
  16581. // Create a test file
  16582. const char *fname = "etag_testfile.txt";
  16583. const char *content = "etag-content";
  16584. {
  16585. std::ofstream ofs(fname);
  16586. ofs << content;
  16587. ASSERT_TRUE(ofs.good());
  16588. }
  16589. Server svr;
  16590. svr.set_mount_point("/static", ".");
  16591. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16592. svr.wait_until_ready();
  16593. Client cli(HOST, PORT);
  16594. // First request: should get 200 with ETag header
  16595. auto res1 = cli.Get("/static/etag_testfile.txt");
  16596. ASSERT_TRUE(res1);
  16597. ASSERT_EQ(200, res1->status);
  16598. ASSERT_TRUE(res1->has_header("ETag"));
  16599. std::string etag = res1->get_header_value("ETag");
  16600. EXPECT_FALSE(etag.empty());
  16601. // Verify ETag format: W/"hex-hex"
  16602. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16603. EXPECT_EQ('W', etag[0]);
  16604. EXPECT_EQ('/', etag[1]);
  16605. EXPECT_EQ('"', etag[2]);
  16606. EXPECT_EQ('"', etag.back());
  16607. // Exact match: expect 304 Not Modified
  16608. Headers h2 = {{"If-None-Match", etag}};
  16609. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16610. ASSERT_TRUE(res2);
  16611. EXPECT_EQ(304, res2->status);
  16612. // Wildcard match: expect 304 Not Modified
  16613. Headers h3 = {{"If-None-Match", "*"}};
  16614. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16615. ASSERT_TRUE(res3);
  16616. EXPECT_EQ(304, res3->status);
  16617. // Non-matching ETag: expect 200
  16618. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16619. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16620. ASSERT_TRUE(res4);
  16621. EXPECT_EQ(200, res4->status);
  16622. // Multiple ETags with one matching: expect 304
  16623. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16624. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16625. ASSERT_TRUE(res5);
  16626. EXPECT_EQ(304, res5->status);
  16627. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16628. // that equivalent to the single comma-separated list above, so the match on
  16629. // the second line must still be found.
  16630. Headers h6;
  16631. h6.emplace("If-None-Match", "W/\"other\"");
  16632. h6.emplace("If-None-Match", etag);
  16633. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16634. ASSERT_TRUE(res6);
  16635. EXPECT_EQ(304, res6->status);
  16636. svr.stop();
  16637. t.join();
  16638. std::remove(fname);
  16639. }
  16640. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16641. using namespace httplib;
  16642. Server svr;
  16643. svr.set_mount_point("/static", ".");
  16644. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16645. svr.wait_until_ready();
  16646. Client cli(HOST, PORT);
  16647. // Send If-None-Match: * to a non-existent file
  16648. Headers h = {{"If-None-Match", "*"}};
  16649. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16651. EXPECT_EQ(404, res->status);
  16652. svr.stop();
  16653. t.join();
  16654. }
  16655. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16656. using namespace httplib;
  16657. // Create a test file
  16658. const char *fname = "etag_boundary_testfile.txt";
  16659. const char *content = "boundary-test";
  16660. {
  16661. std::ofstream ofs(fname);
  16662. ofs << content;
  16663. ASSERT_TRUE(ofs.good());
  16664. }
  16665. Server svr;
  16666. svr.set_mount_point("/static", ".");
  16667. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16668. svr.wait_until_ready();
  16669. Client cli(HOST, PORT);
  16670. // Get the actual ETag
  16671. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16672. ASSERT_TRUE(res1);
  16673. ASSERT_EQ(200, res1->status);
  16674. ASSERT_TRUE(res1->has_header("ETag"));
  16675. std::string etag = res1->get_header_value("ETag");
  16676. // Test 1: Very long ETag value (longer than actual ETag)
  16677. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16678. Headers h1 = {{"If-None-Match", "W/"
  16679. "\"very-long-etag-value-that-is-much-longer-"
  16680. "than-the-actual-etag-value\""}};
  16681. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16682. ASSERT_TRUE(res2);
  16683. EXPECT_EQ(200, res2->status); // Should not match
  16684. // Test 2: Long string followed by wildcard
  16685. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16686. // string)
  16687. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16688. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16689. ASSERT_TRUE(res3);
  16690. EXPECT_EQ(304, res3->status); // Should match on "*"
  16691. // Test 3: Wildcard followed by long string
  16692. // Should match on "*" immediately and return 304
  16693. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16694. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16695. ASSERT_TRUE(res4);
  16696. EXPECT_EQ(304, res4->status); // Should match on "*"
  16697. // Test 4: Multiple long non-matching values
  16698. // Should NOT match and return 200 (test that all comparisons are safe)
  16699. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16700. "W/\"second-long-non-matching-value\", "
  16701. "W/\"third-long-non-matching-value\""}};
  16702. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16703. ASSERT_TRUE(res5);
  16704. EXPECT_EQ(200, res5->status); // Should not match
  16705. // Test 5: Single character that is not "*" (edge case)
  16706. Headers h5 = {{"If-None-Match", "X"}};
  16707. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16708. ASSERT_TRUE(res6);
  16709. EXPECT_EQ(200, res6->status); // Should not match
  16710. svr.stop();
  16711. t.join();
  16712. std::remove(fname);
  16713. }
  16714. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16715. using namespace httplib;
  16716. // Create a test file
  16717. const char *fname = "ims_testfile.txt";
  16718. const char *content = "if-modified-since-test";
  16719. {
  16720. std::ofstream ofs(fname);
  16721. ofs << content;
  16722. ASSERT_TRUE(ofs.good());
  16723. }
  16724. Server svr;
  16725. svr.set_mount_point("/static", ".");
  16726. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16727. svr.wait_until_ready();
  16728. Client cli(HOST, PORT);
  16729. // First request: should get 200 with Last-Modified header
  16730. auto res1 = cli.Get("/static/ims_testfile.txt");
  16731. ASSERT_TRUE(res1);
  16732. ASSERT_EQ(200, res1->status);
  16733. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16734. std::string last_modified = res1->get_header_value("Last-Modified");
  16735. EXPECT_FALSE(last_modified.empty());
  16736. // If-Modified-Since with same time: expect 304
  16737. Headers h2 = {{"If-Modified-Since", last_modified}};
  16738. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16739. ASSERT_TRUE(res2);
  16740. EXPECT_EQ(304, res2->status);
  16741. // If-Modified-Since with future time: expect 304
  16742. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16743. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16744. ASSERT_TRUE(res3);
  16745. EXPECT_EQ(304, res3->status);
  16746. // If-Modified-Since with past time: expect 200
  16747. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16748. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16749. ASSERT_TRUE(res4);
  16750. EXPECT_EQ(200, res4->status);
  16751. // If-None-Match takes precedence over If-Modified-Since
  16752. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16753. ASSERT_TRUE(res1->has_header("ETag"));
  16754. std::string etag = res1->get_header_value("ETag");
  16755. Headers h5 = {{"If-None-Match", etag},
  16756. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16757. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16758. ASSERT_TRUE(res5);
  16759. EXPECT_EQ(304, res5->status);
  16760. svr.stop();
  16761. t.join();
  16762. std::remove(fname);
  16763. }
  16764. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16765. using namespace httplib;
  16766. Server svr;
  16767. // Endpoint that returns compressible content
  16768. svr.Get("/compressible", [](const Request &, Response &res) {
  16769. // Return a large enough body to trigger compression
  16770. std::string body(1000, 'a');
  16771. res.set_content(body, "text/plain");
  16772. });
  16773. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16774. svr.wait_until_ready();
  16775. Client cli(HOST, PORT);
  16776. // Request with gzip support: should get Vary header when compressed
  16777. cli.set_compress(true);
  16778. auto res1 = cli.Get("/compressible");
  16779. ASSERT_TRUE(res1);
  16780. EXPECT_EQ(200, res1->status);
  16781. // If Content-Encoding is set, Vary should also be set
  16782. if (res1->has_header("Content-Encoding")) {
  16783. EXPECT_TRUE(res1->has_header("Vary"));
  16784. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16785. }
  16786. // Request without Accept-Encoding header: should not have compression
  16787. Headers h_no_compress;
  16788. auto res2 = cli.Get("/compressible", h_no_compress);
  16789. ASSERT_TRUE(res2);
  16790. EXPECT_EQ(200, res2->status);
  16791. // Verify Vary header is present when compression is applied
  16792. // (the exact behavior depends on server configuration)
  16793. svr.stop();
  16794. t.join();
  16795. }
  16796. TEST(ETagTest, IfRangeWithETag) {
  16797. using namespace httplib;
  16798. // Create a test file with known content
  16799. const char *fname = "if_range_testfile.txt";
  16800. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16801. {
  16802. std::ofstream ofs(fname);
  16803. ofs << content;
  16804. ASSERT_TRUE(ofs.good());
  16805. }
  16806. Server svr;
  16807. svr.set_mount_point("/static", ".");
  16808. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16809. svr.wait_until_ready();
  16810. Client cli(HOST, PORT);
  16811. // First request: get ETag
  16812. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16813. ASSERT_TRUE(res1);
  16814. ASSERT_EQ(200, res1->status);
  16815. ASSERT_TRUE(res1->has_header("ETag"));
  16816. std::string etag = res1->get_header_value("ETag");
  16817. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16818. // Since our server generates weak ETags (W/"..."), If-Range with our
  16819. // ETag should NOT result in partial content - it should return full content.
  16820. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16821. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16822. ASSERT_TRUE(res2);
  16823. // Weak ETag in If-Range -> full content (200), not partial (206)
  16824. EXPECT_EQ(200, res2->status);
  16825. EXPECT_EQ(content, res2->body);
  16826. EXPECT_FALSE(res2->has_header("Content-Range"));
  16827. // Range request with non-matching If-Range (ETag): should get 200 (full
  16828. // content)
  16829. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16830. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16831. ASSERT_TRUE(res3);
  16832. EXPECT_EQ(200, res3->status);
  16833. EXPECT_EQ(content, res3->body);
  16834. EXPECT_FALSE(res3->has_header("Content-Range"));
  16835. // Range request with strong ETag (hypothetical - our server doesn't generate
  16836. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16837. // should return full content)
  16838. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16839. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16840. ASSERT_TRUE(res4);
  16841. EXPECT_EQ(200, res4->status);
  16842. EXPECT_EQ(content, res4->body);
  16843. EXPECT_FALSE(res4->has_header("Content-Range"));
  16844. svr.stop();
  16845. t.join();
  16846. std::remove(fname);
  16847. }
  16848. TEST(ETagTest, IfRangeWithDate) {
  16849. using namespace httplib;
  16850. // Create a test file
  16851. const char *fname = "if_range_date_testfile.txt";
  16852. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16853. {
  16854. std::ofstream ofs(fname);
  16855. ofs << content;
  16856. ASSERT_TRUE(ofs.good());
  16857. }
  16858. Server svr;
  16859. svr.set_mount_point("/static", ".");
  16860. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16861. svr.wait_until_ready();
  16862. Client cli(HOST, PORT);
  16863. // First request: get Last-Modified
  16864. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16865. ASSERT_TRUE(res1);
  16866. ASSERT_EQ(200, res1->status);
  16867. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16868. std::string last_modified = res1->get_header_value("Last-Modified");
  16869. // Range request with matching If-Range (date): should get 206
  16870. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16871. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16872. ASSERT_TRUE(res2);
  16873. EXPECT_EQ(206, res2->status);
  16874. EXPECT_EQ("FGHIJ", res2->body);
  16875. // Range request with old If-Range date: should get 200 (full content)
  16876. Headers h3 = {{"Range", "bytes=5-9"},
  16877. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16878. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16879. ASSERT_TRUE(res3);
  16880. EXPECT_EQ(200, res3->status);
  16881. EXPECT_EQ(content, res3->body);
  16882. // Range request with future If-Range date: should get 206
  16883. Headers h4 = {{"Range", "bytes=0-4"},
  16884. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16885. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16886. ASSERT_TRUE(res4);
  16887. EXPECT_EQ(206, res4->status);
  16888. EXPECT_EQ("ABCDE", res4->body);
  16889. svr.stop();
  16890. t.join();
  16891. std::remove(fname);
  16892. }
  16893. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16894. using namespace httplib;
  16895. const char *fname = "etag_malformed.txt";
  16896. const char *content = "malformed-etag";
  16897. {
  16898. std::ofstream ofs(fname);
  16899. ofs << content;
  16900. ASSERT_TRUE(ofs.good());
  16901. }
  16902. Server svr;
  16903. svr.set_mount_point("/static", ".");
  16904. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16905. svr.wait_until_ready();
  16906. Client cli(HOST, PORT);
  16907. // baseline: should get 200 and an ETag
  16908. auto res1 = cli.Get("/static/etag_malformed.txt");
  16909. ASSERT_TRUE(res1);
  16910. ASSERT_EQ(200, res1->status);
  16911. ASSERT_TRUE(res1->has_header("ETag"));
  16912. // Malformed ETag value (missing quotes) should be treated as non-matching
  16913. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16914. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16915. ASSERT_TRUE(res_bad);
  16916. EXPECT_EQ(200, res_bad->status);
  16917. // Whitespace-only header value should be considered invalid / non-matching
  16918. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16919. "Host: localhost\r\n"
  16920. "If-None-Match: \r\n"
  16921. "Connection: close\r\n"
  16922. "\r\n";
  16923. std::string out;
  16924. ASSERT_TRUE(send_request(5, raw_req, &out));
  16925. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16926. svr.stop();
  16927. t.join();
  16928. std::remove(fname);
  16929. }
  16930. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16931. using namespace httplib;
  16932. const char *fname = "ims_invalid_format.txt";
  16933. const char *content = "ims-bad-format";
  16934. {
  16935. std::ofstream ofs(fname);
  16936. ofs << content;
  16937. ASSERT_TRUE(ofs.good());
  16938. }
  16939. Server svr;
  16940. svr.set_mount_point("/static", ".");
  16941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16942. svr.wait_until_ready();
  16943. Client cli(HOST, PORT);
  16944. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16945. ASSERT_TRUE(res1);
  16946. ASSERT_EQ(200, res1->status);
  16947. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16948. // If-Modified-Since with invalid format should not result in 304
  16949. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16950. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16951. ASSERT_TRUE(res_bad);
  16952. EXPECT_EQ(200, res_bad->status);
  16953. // If-Range with invalid date format should be treated as mismatch -> full
  16954. // content (200)
  16955. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16956. {"If-Range", "invalid-date"}};
  16957. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16958. ASSERT_TRUE(res_ifrange);
  16959. EXPECT_EQ(200, res_ifrange->status);
  16960. svr.stop();
  16961. t.join();
  16962. std::remove(fname);
  16963. }
  16964. TEST(ETagTest, IfRangeWithMalformedETag) {
  16965. using namespace httplib;
  16966. const char *fname = "ifrange_malformed.txt";
  16967. const std::string content = "0123456789";
  16968. {
  16969. std::ofstream ofs(fname);
  16970. ofs << content;
  16971. ASSERT_TRUE(ofs.good());
  16972. }
  16973. Server svr;
  16974. svr.set_mount_point("/static", ".");
  16975. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16976. svr.wait_until_ready();
  16977. Client cli(HOST, PORT);
  16978. // First request: get ETag
  16979. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16980. ASSERT_TRUE(res1);
  16981. ASSERT_EQ(200, res1->status);
  16982. ASSERT_TRUE(res1->has_header("ETag"));
  16983. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16984. // full content (200)
  16985. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16986. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16987. ASSERT_TRUE(res2);
  16988. EXPECT_EQ(200, res2->status);
  16989. EXPECT_EQ(content, res2->body);
  16990. svr.stop();
  16991. t.join();
  16992. std::remove(fname);
  16993. }
  16994. TEST(ETagTest, ExtremeLargeDateValues) {
  16995. using namespace httplib;
  16996. const char *fname = "ims_extreme_date.txt";
  16997. const char *content = "ims-extreme-date";
  16998. {
  16999. std::ofstream ofs(fname);
  17000. ofs << content;
  17001. ASSERT_TRUE(ofs.good());
  17002. }
  17003. Server svr;
  17004. svr.set_mount_point("/static", ".");
  17005. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17006. svr.wait_until_ready();
  17007. Client cli(HOST, PORT);
  17008. auto res1 = cli.Get(std::string("/static/") + fname);
  17009. ASSERT_TRUE(res1);
  17010. ASSERT_EQ(200, res1->status);
  17011. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17012. // Extremely large year that may overflow date parsing routines.
  17013. Headers h_large_date = {
  17014. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17015. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17016. ASSERT_TRUE(res_bad);
  17017. // Expect server to treat this as invalid/mismatch and return full content
  17018. EXPECT_EQ(200, res_bad->status);
  17019. // If-Range with extremely large date should be treated as mismatch -> full
  17020. // content (200)
  17021. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17022. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17023. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17024. ASSERT_TRUE(res_ifrange);
  17025. EXPECT_EQ(200, res_ifrange->status);
  17026. svr.stop();
  17027. t.join();
  17028. std::remove(fname);
  17029. }
  17030. TEST(ETagTest, NegativeFileModificationTime) {
  17031. using namespace httplib;
  17032. const char *fname = "ims_negative_mtime.txt";
  17033. const std::string content = "negative-mtime";
  17034. {
  17035. std::ofstream ofs(fname);
  17036. ofs << content;
  17037. ASSERT_TRUE(ofs.good());
  17038. }
  17039. // Try to set file mtime to a negative value. This may fail on some
  17040. // platforms/filesystems; if it fails, the test will still verify server
  17041. // behaves safely by performing a regular conditional request.
  17042. #if defined(__APPLE__) || defined(__linux__)
  17043. bool set_negative = false;
  17044. do {
  17045. struct timeval times[2];
  17046. // access time: now
  17047. times[0].tv_sec = time(nullptr);
  17048. times[0].tv_usec = 0;
  17049. // modification time: negative (e.g., -1)
  17050. times[1].tv_sec = -1;
  17051. times[1].tv_usec = 0;
  17052. if (utimes(fname, times) == 0) { set_negative = true; }
  17053. } while (0);
  17054. #else
  17055. bool set_negative = false;
  17056. #endif
  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(std::string("/static/") + fname);
  17063. ASSERT_TRUE(res1);
  17064. ASSERT_EQ(200, res1->status);
  17065. bool has_last_modified = res1->has_header("Last-Modified");
  17066. std::string last_modified;
  17067. if (has_last_modified) {
  17068. last_modified = res1->get_header_value("Last-Modified");
  17069. }
  17070. if (set_negative) {
  17071. // If we successfully set a negative mtime, ensure server returns a
  17072. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17073. // with an old date and ensure server handles it without crash.
  17074. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17075. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17076. ASSERT_TRUE(res2);
  17077. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17078. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17079. } else {
  17080. // Could not set negative mtime on this platform; fall back to verifying
  17081. // that normal invalid/malformed dates are treated safely (non-304).
  17082. Headers h_bad_date = {
  17083. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17084. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17085. ASSERT_TRUE(res_bad);
  17086. EXPECT_EQ(200, res_bad->status);
  17087. }
  17088. svr.stop();
  17089. t.join();
  17090. std::remove(fname);
  17091. }
  17092. //==============================================================================
  17093. // SSE Parsing Tests
  17094. //==============================================================================
  17095. class SSEParsingTest : public ::testing::Test {
  17096. protected:
  17097. // Test helper that mimics SSE parsing behavior
  17098. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17099. int &retry_ms) {
  17100. // Blank line signals end of event
  17101. if (line.empty() || line == "\r") { return true; }
  17102. // Lines starting with ':' are comments (ignored)
  17103. if (!line.empty() && line[0] == ':') { return false; }
  17104. // Find the colon separator
  17105. auto colon_pos = line.find(':');
  17106. if (colon_pos == std::string::npos) {
  17107. // Line with no colon is treated as field name with empty value
  17108. return false;
  17109. }
  17110. std::string field = line.substr(0, colon_pos);
  17111. std::string value;
  17112. // Value starts after colon, skip optional single space
  17113. if (colon_pos + 1 < line.size()) {
  17114. size_t value_start = colon_pos + 1;
  17115. if (line[value_start] == ' ') { value_start++; }
  17116. value = line.substr(value_start);
  17117. // Remove trailing \r if present
  17118. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17119. }
  17120. // Handle known fields
  17121. if (field == "event") {
  17122. msg.event = value;
  17123. } else if (field == "data") {
  17124. // Multiple data lines are concatenated with newlines
  17125. if (!msg.data.empty()) { msg.data += "\n"; }
  17126. msg.data += value;
  17127. } else if (field == "id") {
  17128. // Empty id is valid (clears the last event ID)
  17129. msg.id = value;
  17130. } else if (field == "retry") {
  17131. // Parse retry interval in milliseconds
  17132. {
  17133. int v = 0;
  17134. auto res =
  17135. detail::from_chars(value.data(), value.data() + value.size(), v);
  17136. if (res.ec == std::errc{}) { retry_ms = v; }
  17137. }
  17138. }
  17139. // Unknown fields are ignored per SSE spec
  17140. return false;
  17141. }
  17142. };
  17143. // Test: Single-line data
  17144. TEST_F(SSEParsingTest, SingleLineData) {
  17145. sse::SSEMessage msg;
  17146. int retry_ms = 3000;
  17147. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17148. EXPECT_EQ(msg.data, "hello");
  17149. EXPECT_EQ(msg.event, "message");
  17150. // Blank line ends event
  17151. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17152. }
  17153. // Test: Multi-line data
  17154. TEST_F(SSEParsingTest, MultiLineData) {
  17155. sse::SSEMessage msg;
  17156. int retry_ms = 3000;
  17157. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17158. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17159. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17160. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17161. }
  17162. // Test: Custom event types
  17163. TEST_F(SSEParsingTest, CustomEventType) {
  17164. sse::SSEMessage msg;
  17165. int retry_ms = 3000;
  17166. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17167. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17168. EXPECT_EQ(msg.event, "update");
  17169. EXPECT_EQ(msg.data, "payload");
  17170. }
  17171. // Test: Event ID handling
  17172. TEST_F(SSEParsingTest, EventIdHandling) {
  17173. sse::SSEMessage msg;
  17174. int retry_ms = 3000;
  17175. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17176. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17177. EXPECT_EQ(msg.id, "12345");
  17178. }
  17179. // Test: Empty event ID (clears last event ID)
  17180. TEST_F(SSEParsingTest, EmptyEventId) {
  17181. sse::SSEMessage msg;
  17182. msg.id = "previous";
  17183. int retry_ms = 3000;
  17184. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17185. EXPECT_EQ(msg.id, "");
  17186. }
  17187. // Test: Retry field parsing
  17188. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17189. sse::SSEMessage msg;
  17190. int retry_ms = 3000;
  17191. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17192. EXPECT_EQ(retry_ms, 5000);
  17193. }
  17194. // Test: Invalid retry value
  17195. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17196. sse::SSEMessage msg;
  17197. int retry_ms = 3000;
  17198. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17199. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17200. }
  17201. // Test: Comments (lines starting with :)
  17202. TEST_F(SSEParsingTest, CommentsIgnored) {
  17203. sse::SSEMessage msg;
  17204. int retry_ms = 3000;
  17205. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17206. EXPECT_EQ(msg.data, "");
  17207. EXPECT_EQ(msg.event, "message");
  17208. }
  17209. // Test: Colon in value
  17210. TEST_F(SSEParsingTest, ColonInValue) {
  17211. sse::SSEMessage msg;
  17212. int retry_ms = 3000;
  17213. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17214. EXPECT_EQ(msg.data, "hello:world:test");
  17215. }
  17216. // Test: Line with no colon (field name only)
  17217. TEST_F(SSEParsingTest, FieldNameOnly) {
  17218. sse::SSEMessage msg;
  17219. int retry_ms = 3000;
  17220. // According to SSE spec, this is treated as field name with empty value
  17221. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17222. // Since we don't recognize "data" without colon, data should be empty
  17223. EXPECT_EQ(msg.data, "");
  17224. }
  17225. // Test: Trailing \r handling
  17226. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17227. sse::SSEMessage msg;
  17228. int retry_ms = 3000;
  17229. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17230. EXPECT_EQ(msg.data, "hello");
  17231. }
  17232. // Test: Unknown fields ignored
  17233. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17234. sse::SSEMessage msg;
  17235. int retry_ms = 3000;
  17236. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17237. EXPECT_EQ(msg.data, "");
  17238. EXPECT_EQ(msg.event, "message");
  17239. }
  17240. // Test: Space after colon is optional
  17241. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17242. sse::SSEMessage msg1, msg2;
  17243. int retry_ms = 3000;
  17244. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17245. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17246. EXPECT_EQ(msg1.data, "hello");
  17247. EXPECT_EQ(msg2.data, "hello");
  17248. }
  17249. // Test: SSEMessage clear
  17250. TEST_F(SSEParsingTest, MessageClear) {
  17251. sse::SSEMessage msg;
  17252. msg.event = "custom";
  17253. msg.data = "some data";
  17254. msg.id = "123";
  17255. msg.clear();
  17256. EXPECT_EQ(msg.event, "message");
  17257. EXPECT_EQ(msg.data, "");
  17258. EXPECT_EQ(msg.id, "");
  17259. }
  17260. // Test: Complete event parsing
  17261. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17262. sse::SSEMessage msg;
  17263. int retry_ms = 3000;
  17264. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17265. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17266. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17267. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17268. // Blank line ends event
  17269. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17270. EXPECT_EQ(msg.event, "notification");
  17271. EXPECT_EQ(msg.id, "evt-42");
  17272. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17273. EXPECT_EQ(retry_ms, 1000);
  17274. }
  17275. //==============================================================================
  17276. // Integration Tests with Server
  17277. //==============================================================================
  17278. class SSEIntegrationTest : public ::testing::Test {
  17279. protected:
  17280. void SetUp() override {
  17281. stop_server_.store(false);
  17282. events_.clear();
  17283. server_ = httplib::detail::make_unique<Server>();
  17284. setup_server();
  17285. start_server();
  17286. }
  17287. void TearDown() override {
  17288. stop_server_.store(true);
  17289. event_cv_.notify_all();
  17290. server_->stop();
  17291. if (server_thread_.joinable()) { server_thread_.join(); }
  17292. }
  17293. void setup_server() {
  17294. // Simple SSE endpoint
  17295. server_->Get("/events", [this](const Request &req, Response &res) {
  17296. auto last_id = req.get_header_value("Last-Event-ID");
  17297. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17298. res.set_chunked_content_provider(
  17299. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17300. std::unique_lock<std::mutex> lock(event_mutex_);
  17301. if (event_cv_.wait_for(
  17302. lock, std::chrono::milliseconds(200), [this] {
  17303. return !events_.empty() || stop_server_.load();
  17304. })) {
  17305. if (stop_server_.load()) { return false; }
  17306. if (!events_.empty()) {
  17307. std::string event = events_.front();
  17308. events_.erase(events_.begin());
  17309. sink.write(event.data(), event.size());
  17310. return true;
  17311. }
  17312. }
  17313. return !stop_server_.load();
  17314. });
  17315. });
  17316. // Endpoint that returns error
  17317. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17318. res.status = 500;
  17319. res.set_content("Internal Server Error", "text/plain");
  17320. });
  17321. // Endpoint for custom event types
  17322. server_->Get("/custom-events", [](const Request &, Response &res) {
  17323. res.set_chunked_content_provider(
  17324. "text/event-stream", [](size_t offset, DataSink &sink) {
  17325. if (offset == 0) {
  17326. std::string event = "event: update\ndata: updated\n\n"
  17327. "event: delete\ndata: deleted\n\n";
  17328. sink.write(event.data(), event.size());
  17329. }
  17330. return false; // End stream after sending
  17331. });
  17332. });
  17333. }
  17334. void start_server() {
  17335. port_ = server_->bind_to_any_port(HOST);
  17336. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17337. // Wait for server to start
  17338. while (!server_->is_running()) {
  17339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17340. }
  17341. }
  17342. int get_port() const { return port_; }
  17343. void send_event(const std::string &event) {
  17344. std::lock_guard<std::mutex> lock(event_mutex_);
  17345. events_.push_back(event);
  17346. event_cv_.notify_all();
  17347. }
  17348. std::unique_ptr<Server> server_;
  17349. std::thread server_thread_;
  17350. std::mutex event_mutex_;
  17351. std::condition_variable event_cv_;
  17352. std::vector<std::string> events_;
  17353. std::atomic<bool> stop_server_{false};
  17354. std::string last_received_event_id_;
  17355. int port_ = 0;
  17356. };
  17357. // Test: Successful connection and on_open callback
  17358. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17359. // Add a simple endpoint that sends one event and closes
  17360. server_->Get("/simple-event", [](const Request &, Response &res) {
  17361. res.set_chunked_content_provider(
  17362. "text/event-stream", [](size_t offset, DataSink &sink) {
  17363. if (offset == 0) {
  17364. std::string event = "data: hello\n\n";
  17365. sink.write(event.data(), event.size());
  17366. }
  17367. return false; // Close stream after sending
  17368. });
  17369. });
  17370. Client client("localhost", get_port());
  17371. sse::SSEClient sse(client, "/simple-event");
  17372. std::atomic<bool> open_called{false};
  17373. std::atomic<bool> message_received{false};
  17374. sse.on_open([&open_called]() { open_called.store(true); });
  17375. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17376. if (msg.data == "hello") { message_received.store(true); }
  17377. });
  17378. sse.set_reconnect_interval(100);
  17379. sse.set_max_reconnect_attempts(1);
  17380. // Start async
  17381. sse.start_async();
  17382. // Wait for message to be processed
  17383. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17384. sse.stop();
  17385. EXPECT_TRUE(open_called.load());
  17386. EXPECT_TRUE(message_received.load());
  17387. }
  17388. // Test: on_message callback
  17389. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17390. // Endpoint that sends multiple events then closes
  17391. server_->Get("/multi-event", [](const Request &, Response &res) {
  17392. res.set_chunked_content_provider(
  17393. "text/event-stream", [](size_t offset, DataSink &sink) {
  17394. if (offset == 0) {
  17395. std::string events = "data: message1\n\ndata: message2\n\n";
  17396. sink.write(events.data(), events.size());
  17397. }
  17398. return false;
  17399. });
  17400. });
  17401. Client client("localhost", get_port());
  17402. sse::SSEClient sse(client, "/multi-event");
  17403. std::vector<std::string> received_messages;
  17404. std::mutex messages_mutex;
  17405. sse.on_message([&](const sse::SSEMessage &msg) {
  17406. std::lock_guard<std::mutex> lock(messages_mutex);
  17407. received_messages.push_back(msg.data);
  17408. });
  17409. sse.set_reconnect_interval(100);
  17410. sse.set_max_reconnect_attempts(1);
  17411. sse.start_async();
  17412. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17413. sse.stop();
  17414. std::lock_guard<std::mutex> lock(messages_mutex);
  17415. EXPECT_GE(received_messages.size(), 2u);
  17416. if (received_messages.size() >= 2) {
  17417. EXPECT_EQ(received_messages[0], "message1");
  17418. EXPECT_EQ(received_messages[1], "message2");
  17419. }
  17420. }
  17421. // Test: on_event for specific types
  17422. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17423. Client client("localhost", get_port());
  17424. sse::SSEClient sse(client, "/custom-events");
  17425. std::atomic<bool> update_received{false};
  17426. std::atomic<bool> delete_received{false};
  17427. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17428. if (msg.data == "updated") { update_received.store(true); }
  17429. });
  17430. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17431. if (msg.data == "deleted") { delete_received.store(true); }
  17432. });
  17433. sse.set_max_reconnect_attempts(1);
  17434. sse.start_async();
  17435. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17436. sse.stop();
  17437. EXPECT_TRUE(update_received.load());
  17438. EXPECT_TRUE(delete_received.load());
  17439. }
  17440. // Test: on_error callback on connection failure
  17441. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17442. // Connect to a non-existent port
  17443. Client client("localhost", 59999);
  17444. sse::SSEClient sse(client, "/events");
  17445. std::atomic<bool> error_called{false};
  17446. Error received_error = Error::Success;
  17447. sse.on_error([&](Error err) {
  17448. error_called.store(true);
  17449. received_error = err;
  17450. });
  17451. sse.set_reconnect_interval(50);
  17452. sse.set_max_reconnect_attempts(1);
  17453. sse.start_async();
  17454. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17455. sse.stop();
  17456. EXPECT_TRUE(error_called.load());
  17457. EXPECT_NE(received_error, Error::Success);
  17458. }
  17459. // Test: Last-Event-ID header sent on reconnect
  17460. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17461. // Endpoint that sends event with ID
  17462. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17463. res.set_chunked_content_provider(
  17464. "text/event-stream", [](size_t offset, DataSink &sink) {
  17465. if (offset == 0) {
  17466. std::string event = "id: evt-123\ndata: test\n\n";
  17467. sink.write(event.data(), event.size());
  17468. }
  17469. return false;
  17470. });
  17471. });
  17472. Client client("localhost", get_port());
  17473. sse::SSEClient sse(client, "/event-with-id");
  17474. std::atomic<bool> id_received{false};
  17475. sse.on_message([&](const sse::SSEMessage &msg) {
  17476. if (!msg.id.empty()) { id_received.store(true); }
  17477. });
  17478. sse.set_reconnect_interval(100);
  17479. sse.set_max_reconnect_attempts(1);
  17480. sse.start_async();
  17481. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17482. sse.stop();
  17483. EXPECT_TRUE(id_received.load());
  17484. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17485. }
  17486. // Test: Manual stop
  17487. TEST_F(SSEIntegrationTest, ManualStop) {
  17488. // Endpoint that sends one event and stays open briefly
  17489. std::atomic<bool> handler_running{true};
  17490. server_->Get("/stay-open", [&handler_running](const Request &,
  17491. Response &res) {
  17492. res.set_chunked_content_provider(
  17493. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17494. if (offset == 0) {
  17495. std::string event = "data: connected\n\n";
  17496. sink.write(event.data(), event.size());
  17497. }
  17498. // Keep connection open while handler_running is true
  17499. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17500. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17501. }
  17502. return false;
  17503. });
  17504. });
  17505. Client client("localhost", get_port());
  17506. sse::SSEClient sse(client, "/stay-open");
  17507. std::atomic<bool> connected{false};
  17508. sse.on_open([&connected]() { connected.store(true); });
  17509. sse.set_reconnect_interval(100);
  17510. sse.set_max_reconnect_attempts(1);
  17511. sse.start_async();
  17512. // Wait for connection to establish
  17513. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17514. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17515. }
  17516. EXPECT_TRUE(connected.load());
  17517. EXPECT_TRUE(sse.is_connected());
  17518. // Signal handler to stop
  17519. handler_running.store(false);
  17520. // Stop SSE client
  17521. sse.stop();
  17522. EXPECT_FALSE(sse.is_connected());
  17523. }
  17524. // Test: SSEClient with custom headers
  17525. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17526. // Setup a server endpoint that checks for custom header
  17527. std::atomic<bool> header_received{false};
  17528. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17529. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17530. header_received.store(true);
  17531. }
  17532. res.set_chunked_content_provider("text/event-stream",
  17533. [](size_t, DataSink &) { return false; });
  17534. });
  17535. Client client("localhost", get_port());
  17536. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17537. sse::SSEClient sse(client, "/header-check", headers);
  17538. sse.set_max_reconnect_attempts(1);
  17539. sse.start_async();
  17540. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17541. sse.stop();
  17542. EXPECT_TRUE(header_received.load());
  17543. }
  17544. // Test: Reconnect interval configuration
  17545. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17546. Client client("localhost", get_port());
  17547. sse::SSEClient sse(client, "/events");
  17548. auto &result = sse.set_reconnect_interval(500);
  17549. // Builder pattern should return reference to self
  17550. EXPECT_EQ(&result, &sse);
  17551. }
  17552. // Test: Max reconnect attempts
  17553. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17554. // Connect to non-existent port to force reconnects
  17555. Client client("localhost", 59998);
  17556. sse::SSEClient sse(client, "/events");
  17557. std::atomic<int> error_count{0};
  17558. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17559. sse.set_reconnect_interval(50);
  17560. sse.set_max_reconnect_attempts(2);
  17561. auto start = std::chrono::steady_clock::now();
  17562. sse.start(); // Blocking call
  17563. auto end = std::chrono::steady_clock::now();
  17564. // Should have stopped after 2 failed attempts
  17565. EXPECT_GE(error_count.load(), 2);
  17566. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17567. auto duration =
  17568. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17569. #ifdef _WIN32
  17570. // Windows is much slower for socket connection failures
  17571. EXPECT_LT(duration.count(), 7000);
  17572. #else
  17573. EXPECT_LT(duration.count(), 1000);
  17574. #endif
  17575. }
  17576. // Test: Multi-line data in integration
  17577. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17578. // Endpoint with multi-line data
  17579. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17580. res.set_chunked_content_provider(
  17581. "text/event-stream", [](size_t offset, DataSink &sink) {
  17582. if (offset == 0) {
  17583. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17584. sink.write(event.data(), event.size());
  17585. }
  17586. return false;
  17587. });
  17588. });
  17589. Client client("localhost", get_port());
  17590. sse::SSEClient sse(client, "/multiline-data");
  17591. std::string received_data;
  17592. std::mutex data_mutex;
  17593. sse.on_message([&](const sse::SSEMessage &msg) {
  17594. std::lock_guard<std::mutex> lock(data_mutex);
  17595. received_data = msg.data;
  17596. });
  17597. sse.set_reconnect_interval(100);
  17598. sse.set_max_reconnect_attempts(1);
  17599. sse.start_async();
  17600. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17601. sse.stop();
  17602. std::lock_guard<std::mutex> lock(data_mutex);
  17603. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17604. }
  17605. // Test: Auto-reconnect after server disconnection
  17606. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17607. std::atomic<int> connection_count{0};
  17608. std::atomic<int> message_count{0};
  17609. // Endpoint that sends one event and closes, forcing reconnect
  17610. server_->Get("/reconnect-test",
  17611. [&connection_count](const Request &, Response &res) {
  17612. connection_count.fetch_add(1);
  17613. res.set_chunked_content_provider(
  17614. "text/event-stream", [](size_t offset, DataSink &sink) {
  17615. if (offset == 0) {
  17616. std::string event = "data: hello\n\n";
  17617. sink.write(event.data(), event.size());
  17618. }
  17619. return false; // Close connection after sending
  17620. });
  17621. });
  17622. Client client("localhost", get_port());
  17623. sse::SSEClient sse(client, "/reconnect-test");
  17624. sse.on_message([&message_count](const sse::SSEMessage &) {
  17625. message_count.fetch_add(1);
  17626. });
  17627. sse.set_reconnect_interval(100);
  17628. sse.set_max_reconnect_attempts(3);
  17629. sse.start_async();
  17630. // Wait long enough for multiple reconnects
  17631. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17632. sse.stop();
  17633. // Should have connected multiple times (initial + reconnects)
  17634. EXPECT_GE(connection_count.load(), 2);
  17635. // Should have received messages from multiple connections
  17636. EXPECT_GE(message_count.load(), 2);
  17637. }
  17638. // Test: Last-Event-ID sent on reconnect
  17639. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17640. std::atomic<int> connection_count{0};
  17641. std::vector<std::string> received_last_event_ids;
  17642. std::mutex id_mutex;
  17643. // Endpoint that checks Last-Event-ID header and sends event with ID
  17644. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17645. int conn = connection_count.fetch_add(1);
  17646. // Capture the Last-Event-ID header from each connection
  17647. {
  17648. std::lock_guard<std::mutex> lock(id_mutex);
  17649. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17650. }
  17651. res.set_chunked_content_provider(
  17652. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17653. if (offset == 0) {
  17654. std::string event =
  17655. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17656. sink.write(event.data(), event.size());
  17657. }
  17658. return false;
  17659. });
  17660. });
  17661. Client client("localhost", get_port());
  17662. sse::SSEClient sse(client, "/reconnect-with-id");
  17663. sse.set_reconnect_interval(100);
  17664. sse.set_max_reconnect_attempts(3);
  17665. sse.start_async();
  17666. // Wait for at least 2 connections
  17667. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17668. sse.stop();
  17669. // Verify behavior
  17670. std::lock_guard<std::mutex> lock(id_mutex);
  17671. EXPECT_GE(received_last_event_ids.size(), 2u);
  17672. // First connection should have no Last-Event-ID
  17673. if (!received_last_event_ids.empty()) {
  17674. EXPECT_EQ(received_last_event_ids[0], "");
  17675. }
  17676. // Second connection should have Last-Event-ID from first connection
  17677. if (received_last_event_ids.size() >= 2) {
  17678. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17679. }
  17680. }
  17681. // Test: set_headers updates headers used on reconnect
  17682. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17683. std::vector<std::string> received_tokens;
  17684. std::mutex token_mutex;
  17685. // Endpoint that captures Authorization header
  17686. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17687. {
  17688. std::lock_guard<std::mutex> lock(token_mutex);
  17689. received_tokens.push_back(req.get_header_value("Authorization"));
  17690. }
  17691. res.set_chunked_content_provider(
  17692. "text/event-stream", [](size_t offset, DataSink &sink) {
  17693. if (offset == 0) {
  17694. std::string event = "data: hello\n\n";
  17695. sink.write(event.data(), event.size());
  17696. }
  17697. return false; // Close connection to trigger reconnect
  17698. });
  17699. });
  17700. Client client("localhost", get_port());
  17701. Headers headers = {{"Authorization", "Bearer old-token"}};
  17702. sse::SSEClient sse(client, "/auth-check", headers);
  17703. // Update headers on each successful connection
  17704. sse.on_open(
  17705. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17706. sse.set_reconnect_interval(100);
  17707. sse.set_max_reconnect_attempts(3);
  17708. sse.start_async();
  17709. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17710. sse.stop();
  17711. std::lock_guard<std::mutex> lock(token_mutex);
  17712. ASSERT_GE(received_tokens.size(), 2u);
  17713. // First connection uses original header
  17714. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17715. // Second connection uses updated header from set_headers
  17716. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17717. }
  17718. // Test: 401 allows reconnection (so on_error can refresh headers)
  17719. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17720. std::atomic<int> connection_count{0};
  17721. // Endpoint: returns 401 on first attempt, 200 on second
  17722. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17723. int conn = connection_count.fetch_add(1);
  17724. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17725. res.status = StatusCode::Unauthorized_401;
  17726. res.set_content("Unauthorized", "text/plain");
  17727. return;
  17728. }
  17729. res.set_chunked_content_provider(
  17730. "text/event-stream", [](size_t offset, DataSink &sink) {
  17731. if (offset == 0) {
  17732. std::string event = "data: authenticated\n\n";
  17733. sink.write(event.data(), event.size());
  17734. }
  17735. return false;
  17736. });
  17737. });
  17738. Client client("localhost", get_port());
  17739. Headers headers = {{"Authorization", "Bearer expired"}};
  17740. sse::SSEClient sse(client, "/auth-retry", headers);
  17741. std::atomic<bool> message_received{false};
  17742. // Refresh token on error
  17743. sse.on_error(
  17744. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17745. sse.on_message([&](const sse::SSEMessage &msg) {
  17746. if (msg.data == "authenticated") { message_received.store(true); }
  17747. });
  17748. sse.set_reconnect_interval(100);
  17749. sse.set_max_reconnect_attempts(3);
  17750. sse.start_async();
  17751. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17752. sse.stop();
  17753. // Should have reconnected after 401 and succeeded with new token
  17754. EXPECT_GE(connection_count.load(), 2);
  17755. EXPECT_TRUE(message_received.load());
  17756. }
  17757. TEST(Issue2318Test, EmptyHostString) {
  17758. {
  17759. httplib::Client cli_empty("", PORT);
  17760. auto res = cli_empty.Get("/");
  17761. ASSERT_FALSE(res);
  17762. EXPECT_EQ(httplib::Error::Connection, res.error());
  17763. }
  17764. {
  17765. httplib::Client cli(" ", PORT);
  17766. auto res = cli.Get("/");
  17767. ASSERT_FALSE(res);
  17768. EXPECT_EQ(httplib::Error::Connection, res.error());
  17769. }
  17770. }
  17771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17772. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17773. Server svr;
  17774. // Set a small payload limit (1KB)
  17775. svr.set_payload_max_length(1024);
  17776. svr.Post("/test", [&](const Request &req, Response &res) {
  17777. res.set_content("Body size: " + std::to_string(req.body.size()),
  17778. "text/plain");
  17779. });
  17780. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17781. auto se = detail::scope_exit([&] {
  17782. svr.stop();
  17783. listen_thread.join();
  17784. });
  17785. svr.wait_until_ready();
  17786. // Create data that compresses well but exceeds limit when decompressed
  17787. // 8KB of repeated null bytes compresses to a very small size
  17788. std::string original_data(8 * 1024, '\0');
  17789. // Compress the data using gzip
  17790. std::string compressed_data;
  17791. detail::gzip_compressor compressor;
  17792. compressor.compress(original_data.data(), original_data.size(), true,
  17793. [&](const char *data, size_t size) {
  17794. compressed_data.append(data, size);
  17795. return true;
  17796. });
  17797. // Verify compression worked (compressed should be much smaller)
  17798. ASSERT_LT(compressed_data.size(), original_data.size());
  17799. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17800. // Send compressed data with Content-Encoding: gzip
  17801. Client cli(HOST, PORT);
  17802. Headers headers = {{"Content-Encoding", "gzip"}};
  17803. auto res =
  17804. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17805. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17808. }
  17809. #endif
  17810. // ============================================================================
  17811. // OpenSSL-Specific Tests
  17812. // ============================================================================
  17813. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17814. X509 *readCertificate(const std::string &strFileName) {
  17815. std::ifstream inStream(strFileName);
  17816. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17817. std::istreambuf_iterator<char>());
  17818. if (strCertPEM.empty()) return (nullptr);
  17819. BIO *pbCert = BIO_new(BIO_s_mem());
  17820. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17821. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17822. BIO_free(pbCert);
  17823. return (pCert);
  17824. }
  17825. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17826. std::ifstream inStream(strFileName);
  17827. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17828. std::istreambuf_iterator<char>());
  17829. if (strPrivateKeyPEM.empty()) return (nullptr);
  17830. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17831. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17832. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17833. BIO_free(pbPrivKey);
  17834. return (pPrivateKey);
  17835. }
  17836. TEST(BindServerTest, UpdateCerts) {
  17837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17838. int port = svr.bind_to_any_port("0.0.0.0");
  17839. ASSERT_TRUE(svr.is_valid());
  17840. ASSERT_TRUE(port > 0);
  17841. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17842. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17843. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17844. ASSERT_TRUE(cert != nullptr);
  17845. ASSERT_TRUE(ca_cert != nullptr);
  17846. ASSERT_TRUE(key != nullptr);
  17847. X509_STORE *cert_store = X509_STORE_new();
  17848. X509_STORE_add_cert(cert_store, ca_cert);
  17849. // svr.update_certs(cert, key, cert_store); // deprecated
  17850. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17851. CLIENT_CA_CERT_FILE);
  17852. ASSERT_TRUE(svr.is_valid());
  17853. svr.stop();
  17854. X509_STORE_free(cert_store);
  17855. X509_free(cert);
  17856. X509_free(ca_cert);
  17857. EVP_PKEY_free(key);
  17858. }
  17859. // Test that update_certs() updates client CA list correctly
  17860. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17861. // Start with file-based constructor
  17862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17863. ASSERT_TRUE(svr.is_valid());
  17864. // Initially no client CA list should be set
  17865. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17866. ASSERT_TRUE(ssl_ctx != nullptr);
  17867. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17868. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17869. EXPECT_EQ(0, count_before);
  17870. // Now update with client CA (PEM string)
  17871. std::string cert_pem, key_pem, ca_pem;
  17872. read_file(SERVER_CERT_FILE, cert_pem);
  17873. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17874. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17875. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17876. ASSERT_TRUE(svr.is_valid());
  17877. // Now client CA list should be set
  17878. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17879. ASSERT_TRUE(ca_list_after != nullptr);
  17880. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17881. }
  17882. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17883. // Test that the file-path SSLServer constructor properly sets the client CA
  17884. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17886. ASSERT_TRUE(svr.is_valid());
  17887. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17888. ASSERT_TRUE(ssl_ctx != nullptr);
  17889. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17890. ASSERT_TRUE(ca_list != nullptr);
  17891. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17892. }
  17893. #endif
  17894. // ============================================================================
  17895. // MbedTLS-Specific Tests
  17896. // ============================================================================
  17897. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17898. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17899. using namespace httplib::tls;
  17900. // Track if callback was invoked
  17901. bool callback_invoked = false;
  17902. // The callback receives void* ctx which is actually MbedTlsContext*
  17903. // We can access the mbedtls_ssl_config via the context
  17904. auto setup_callback = [&callback_invoked](void *ctx) {
  17905. callback_invoked = true;
  17906. // Cast to MbedTlsContext* to access the ssl config
  17907. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17908. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17909. // Use static variables to hold certificate data (simplified for test)
  17910. static mbedtls_x509_crt own_cert;
  17911. static mbedtls_pk_context own_key;
  17912. static mbedtls_x509_crt ca_chain;
  17913. static bool initialized = false;
  17914. if (!initialized) {
  17915. mbedtls_x509_crt_init(&own_cert);
  17916. mbedtls_pk_init(&own_key);
  17917. mbedtls_x509_crt_init(&ca_chain);
  17918. // Load server certificate
  17919. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17920. return false;
  17921. }
  17922. // Load server private key.
  17923. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17924. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17925. #if MBEDTLS_VERSION_MAJOR == 3
  17926. ,
  17927. mbedtls_ctr_drbg_random, nullptr
  17928. #endif
  17929. ) != 0) {
  17930. return false;
  17931. }
  17932. // Load CA chain for client verification
  17933. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17934. return false;
  17935. }
  17936. initialized = true;
  17937. }
  17938. // Configure the SSL config
  17939. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17940. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17941. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17942. // Set minimum TLS version using mbedTLS native API
  17943. #if MBEDTLS_VERSION_MAJOR >= 3
  17944. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17945. #else
  17946. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17947. MBEDTLS_SSL_MINOR_VERSION_3);
  17948. #endif
  17949. return true;
  17950. };
  17951. SSLServer svr(setup_callback);
  17952. ASSERT_TRUE(svr.is_valid());
  17953. ASSERT_TRUE(callback_invoked);
  17954. svr.Get("/test", [&](const Request &req, Response &res) {
  17955. res.set_content("test", "text/plain");
  17956. auto cert = req.peer_cert();
  17957. ASSERT_TRUE(static_cast<bool>(cert));
  17958. auto common_name = cert.subject_cn();
  17959. EXPECT_EQ("Common Name", common_name);
  17960. });
  17961. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17962. auto se = detail::scope_exit([&] {
  17963. svr.stop();
  17964. t.join();
  17965. ASSERT_FALSE(svr.is_running());
  17966. });
  17967. svr.wait_until_ready();
  17968. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17969. cli.enable_server_certificate_verification(false);
  17970. cli.set_connection_timeout(30);
  17971. auto res = cli.Get("/test");
  17972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17973. ASSERT_EQ(StatusCode::OK_200, res->status);
  17974. }
  17975. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17976. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17977. // keep-alive SSL session, which reads through that config in
  17978. // mbedtls_ssl_close_notify.
  17979. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17981. ASSERT_TRUE(svr.is_valid());
  17982. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17983. res.set_content("test", "text/plain");
  17984. });
  17985. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17986. auto se = detail::scope_exit([&] {
  17987. svr.stop();
  17988. t.join();
  17989. ASSERT_FALSE(svr.is_running());
  17990. });
  17991. svr.wait_until_ready();
  17992. {
  17993. SSLClient cli(HOST, PORT);
  17994. cli.enable_server_certificate_verification(false);
  17995. cli.set_keep_alive(true);
  17996. auto res = cli.Get("/test");
  17997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17998. ASSERT_EQ(StatusCode::OK_200, res->status);
  17999. // cli is destructed here with the keep-alive SSL session still open.
  18000. }
  18001. }
  18002. #endif
  18003. // WebSocket Tests
  18004. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18005. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18006. // defining the meaning of these bits has been negotiated.
  18007. auto make_frame = [](uint8_t first_byte) {
  18008. std::string frame;
  18009. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18010. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18011. frame += "Hello";
  18012. return frame;
  18013. };
  18014. // RSV1 set (0x40)
  18015. {
  18016. detail::BufferStream strm;
  18017. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18018. ws::Opcode opcode;
  18019. std::string payload;
  18020. bool fin;
  18021. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18022. false, 1024));
  18023. }
  18024. // RSV2 set (0x20)
  18025. {
  18026. detail::BufferStream strm;
  18027. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18028. ws::Opcode opcode;
  18029. std::string payload;
  18030. bool fin;
  18031. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18032. false, 1024));
  18033. }
  18034. // RSV3 set (0x10)
  18035. {
  18036. detail::BufferStream strm;
  18037. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18038. ws::Opcode opcode;
  18039. std::string payload;
  18040. bool fin;
  18041. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18042. false, 1024));
  18043. }
  18044. // No RSV bits set - should succeed
  18045. {
  18046. detail::BufferStream strm;
  18047. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18048. ws::Opcode opcode;
  18049. std::string payload;
  18050. bool fin;
  18051. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18052. false, 1024));
  18053. EXPECT_EQ(ws::Opcode::Text, opcode);
  18054. EXPECT_EQ("Hello", payload);
  18055. EXPECT_TRUE(fin);
  18056. }
  18057. }
  18058. TEST(WebSocketTest, ControlFrameValidation) {
  18059. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18060. // payload length <= 125.
  18061. // Ping with FIN=0 - must be rejected
  18062. {
  18063. detail::BufferStream strm;
  18064. std::string frame;
  18065. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18066. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18067. strm.write(frame.data(), frame.size());
  18068. ws::Opcode opcode;
  18069. std::string payload;
  18070. bool fin;
  18071. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18072. false, 1024));
  18073. }
  18074. // Close with FIN=0 - must be rejected
  18075. {
  18076. detail::BufferStream strm;
  18077. std::string frame;
  18078. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18079. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18080. strm.write(frame.data(), frame.size());
  18081. ws::Opcode opcode;
  18082. std::string payload;
  18083. bool fin;
  18084. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18085. false, 1024));
  18086. }
  18087. // Ping with payload_len=126 (extended length) - must be rejected
  18088. {
  18089. detail::BufferStream strm;
  18090. std::string frame;
  18091. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18092. frame += static_cast<char>(126); // payload_len=126 (>125)
  18093. frame += static_cast<char>(0x00); // extended length high byte
  18094. frame += static_cast<char>(126); // extended length low byte
  18095. frame += std::string(126, 'x');
  18096. strm.write(frame.data(), frame.size());
  18097. ws::Opcode opcode;
  18098. std::string payload;
  18099. bool fin;
  18100. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18101. false, 1024));
  18102. }
  18103. // Ping with FIN=1 and payload_len=125 - should succeed
  18104. {
  18105. detail::BufferStream strm;
  18106. std::string frame;
  18107. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18108. frame += static_cast<char>(125); // payload_len=125
  18109. frame += std::string(125, 'x');
  18110. strm.write(frame.data(), frame.size());
  18111. ws::Opcode opcode;
  18112. std::string payload;
  18113. bool fin;
  18114. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18115. false, 1024));
  18116. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18117. EXPECT_EQ(125u, payload.size());
  18118. EXPECT_TRUE(fin);
  18119. }
  18120. }
  18121. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18122. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18123. // length MUST be 0.
  18124. // MSB set - must be rejected
  18125. {
  18126. detail::BufferStream strm;
  18127. std::string frame;
  18128. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18129. frame += static_cast<char>(127); // 64-bit extended length
  18130. frame += static_cast<char>(0x80); // MSB set (invalid)
  18131. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18132. strm.write(frame.data(), frame.size());
  18133. ws::Opcode opcode;
  18134. std::string payload;
  18135. bool fin;
  18136. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18137. false, 1024));
  18138. }
  18139. // MSB clear - should pass length parsing (will be rejected by max_len,
  18140. // but that's a different check; use a small length to verify)
  18141. {
  18142. detail::BufferStream strm;
  18143. std::string frame;
  18144. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18145. frame += static_cast<char>(127); // 64-bit extended length
  18146. frame += std::string(7, '\0'); // high bytes = 0
  18147. frame += static_cast<char>(0x03); // length = 3
  18148. frame += "abc";
  18149. strm.write(frame.data(), frame.size());
  18150. ws::Opcode opcode;
  18151. std::string payload;
  18152. bool fin;
  18153. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18154. false, 1024));
  18155. EXPECT_EQ(ws::Opcode::Text, opcode);
  18156. EXPECT_EQ("abc", payload);
  18157. }
  18158. }
  18159. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18160. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18161. // Valid UTF-8
  18162. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18163. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18164. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18165. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18166. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18167. // Invalid UTF-8
  18168. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18169. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18170. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18171. EXPECT_FALSE(
  18172. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18173. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18174. }
  18175. TEST(WebSocketTest, ConnectAndDisconnect) {
  18176. Server svr;
  18177. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18178. std::string msg;
  18179. while (ws.read(msg)) {}
  18180. });
  18181. auto port = svr.bind_to_any_port(HOST);
  18182. std::thread t([&]() { svr.listen_after_bind(); });
  18183. svr.wait_until_ready();
  18184. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18185. auto res = client.connect();
  18186. ASSERT_TRUE(res);
  18187. EXPECT_EQ(Error::Success, res.error());
  18188. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18189. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18190. EXPECT_TRUE(client.is_open());
  18191. client.close();
  18192. EXPECT_FALSE(client.is_open());
  18193. svr.stop();
  18194. t.join();
  18195. }
  18196. TEST(WebSocketTest, ValidURL) {
  18197. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18198. EXPECT_TRUE(ws1.is_valid());
  18199. ws::WebSocketClient ws2("ws://example.com/path");
  18200. EXPECT_TRUE(ws2.is_valid());
  18201. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18202. EXPECT_TRUE(ws3.is_valid());
  18203. #ifdef CPPHTTPLIB_SSL_ENABLED
  18204. ws::WebSocketClient wss1("wss://example.com/path");
  18205. EXPECT_TRUE(wss1.is_valid());
  18206. ws::WebSocketClient wss2("wss://example.com:443/path");
  18207. EXPECT_TRUE(wss2.is_valid());
  18208. #endif
  18209. }
  18210. TEST(WebSocketTest, InvalidURL) {
  18211. // No scheme
  18212. ws::WebSocketClient ws1("localhost:8080/path");
  18213. EXPECT_FALSE(ws1.is_valid());
  18214. // No path
  18215. ws::WebSocketClient ws2("ws://localhost:8080");
  18216. EXPECT_FALSE(ws2.is_valid());
  18217. // Empty string
  18218. ws::WebSocketClient ws3("");
  18219. EXPECT_FALSE(ws3.is_valid());
  18220. // Missing host
  18221. ws::WebSocketClient ws4("ws://:8080/path");
  18222. EXPECT_FALSE(ws4.is_valid());
  18223. // Port number overflow — should not crash
  18224. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18225. EXPECT_FALSE(ws5.is_valid());
  18226. // Port out of range
  18227. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18228. EXPECT_FALSE(ws6.is_valid());
  18229. }
  18230. TEST(WebSocketTest, UnsupportedScheme) {
  18231. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18232. ws::WebSocketClient ws1("http://localhost:8080/path");
  18233. EXPECT_FALSE(ws1.is_valid());
  18234. ws::WebSocketClient ws2("https://localhost:8080/path");
  18235. EXPECT_FALSE(ws2.is_valid());
  18236. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18237. EXPECT_FALSE(ws3.is_valid());
  18238. #else
  18239. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18240. std::invalid_argument);
  18241. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18242. std::invalid_argument);
  18243. #endif
  18244. }
  18245. TEST(WebSocketTest, ConnectWhenInvalid) {
  18246. ws::WebSocketClient ws("not a valid url");
  18247. EXPECT_FALSE(ws.is_valid());
  18248. auto res = ws.connect();
  18249. EXPECT_FALSE(res);
  18250. EXPECT_EQ(Error::Connection, res.error());
  18251. EXPECT_EQ(-1, res.status());
  18252. }
  18253. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18254. // Grab a port that is free, then close it again so nothing listens there
  18255. Server svr;
  18256. auto port = svr.bind_to_any_port(HOST);
  18257. svr.stop();
  18258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18259. auto res = client.connect();
  18260. ASSERT_FALSE(res);
  18261. EXPECT_EQ(Error::Connection, res.error());
  18262. EXPECT_EQ(-1, res.status());
  18263. }
  18264. TEST(WebSocketTest, DefaultPort) {
  18265. ws::WebSocketClient ws1("ws://example.com/path");
  18266. EXPECT_TRUE(ws1.is_valid());
  18267. // ws:// defaults to port 80 (verified by successful parse)
  18268. #ifdef CPPHTTPLIB_SSL_ENABLED
  18269. ws::WebSocketClient ws2("wss://example.com/path");
  18270. EXPECT_TRUE(ws2.is_valid());
  18271. // wss:// defaults to port 443 (verified by successful parse)
  18272. #endif
  18273. }
  18274. TEST(WebSocketTest, IPv6LiteralAddress) {
  18275. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18276. EXPECT_TRUE(ws1.is_valid());
  18277. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18278. EXPECT_TRUE(ws2.is_valid());
  18279. }
  18280. TEST(WebSocketTest, ComplexPath) {
  18281. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18282. EXPECT_TRUE(ws1.is_valid());
  18283. ws::WebSocketClient ws2("ws://localhost:8080/");
  18284. EXPECT_TRUE(ws2.is_valid());
  18285. }
  18286. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18287. Server svr;
  18288. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18289. std::string msg;
  18290. while (ws.read(msg)) {}
  18291. });
  18292. auto port = svr.bind_to_any_port(HOST);
  18293. std::thread t([&]() { svr.listen_after_bind(); });
  18294. svr.wait_until_ready();
  18295. auto another_host = "example.com";
  18296. auto wrong_ip = "192.0.2.1";
  18297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18298. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18299. ASSERT_TRUE(client.connect());
  18300. EXPECT_TRUE(client.is_open());
  18301. client.close();
  18302. svr.stop();
  18303. t.join();
  18304. }
  18305. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18306. Server svr;
  18307. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18308. std::string msg;
  18309. while (ws.read(msg)) {}
  18310. });
  18311. auto port = svr.bind_to_any_port(HOST);
  18312. std::thread t([&]() { svr.listen_after_bind(); });
  18313. svr.wait_until_ready();
  18314. auto wrong_ip = "192.0.2.1";
  18315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18316. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18317. client.set_connection_timeout(1);
  18318. client.set_read_timeout(1);
  18319. client.set_write_timeout(1);
  18320. EXPECT_FALSE(client.connect());
  18321. EXPECT_FALSE(client.is_open());
  18322. svr.stop();
  18323. t.join();
  18324. }
  18325. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18326. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18327. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18328. // (RFC 6761) is only a map key and the Host header value.
  18329. auto host = "target.invalid";
  18330. Server svr;
  18331. std::string received_host;
  18332. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18333. received_host = req.get_header_value("Host");
  18334. std::string msg;
  18335. while (ws.read(msg)) {}
  18336. });
  18337. auto port = svr.bind_to_any_port(HOST);
  18338. std::thread t([&]() { svr.listen_after_bind(); });
  18339. // ASSERT_* below returns from the test body, which would leave t joinable
  18340. // and make ~thread call std::terminate.
  18341. auto se = detail::scope_exit([&] {
  18342. svr.stop();
  18343. if (t.joinable()) { t.join(); }
  18344. });
  18345. svr.wait_until_ready();
  18346. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18347. std::to_string(port) + "/ws");
  18348. client.set_hostname_addr_map({{host, HOST}});
  18349. ASSERT_TRUE(client.connect());
  18350. EXPECT_TRUE(client.is_open());
  18351. client.close();
  18352. svr.stop();
  18353. t.join();
  18354. // The mapping only redirects the connection; the identity stays host_.
  18355. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18356. }
  18357. class WebSocketIntegrationTest : public ::testing::Test {
  18358. protected:
  18359. void SetUp() override {
  18360. server_ = httplib::detail::make_unique<Server>();
  18361. setup_server();
  18362. start_server();
  18363. }
  18364. void TearDown() override {
  18365. server_->stop();
  18366. if (server_thread_.joinable()) { server_thread_.join(); }
  18367. }
  18368. void setup_server() {
  18369. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18370. std::string msg;
  18371. ws::ReadResult ret;
  18372. while ((ret = ws.read(msg))) {
  18373. if (ret == ws::Binary) {
  18374. ws.send(msg.data(), msg.size());
  18375. } else {
  18376. ws.send(msg);
  18377. }
  18378. }
  18379. });
  18380. server_->WebSocket("/ws-echo-string",
  18381. [](const Request &, ws::WebSocket &ws) {
  18382. std::string msg;
  18383. while (ws.read(msg)) {
  18384. ws.send("echo: " + msg);
  18385. }
  18386. });
  18387. server_->WebSocket(
  18388. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18389. // Echo back request metadata
  18390. ws.send("path:" + req.path);
  18391. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18392. std::string msg;
  18393. while (ws.read(msg)) {}
  18394. });
  18395. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18396. std::string msg;
  18397. ws.read(msg); // wait for a message
  18398. ws.close();
  18399. });
  18400. server_->WebSocket("/ws-close-status",
  18401. [](const Request &, ws::WebSocket &ws) {
  18402. std::string msg;
  18403. ws.read(msg); // wait for a message
  18404. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18405. });
  18406. server_->WebSocket(
  18407. "/ws-subprotocol",
  18408. [](const Request &, ws::WebSocket &ws) {
  18409. std::string msg;
  18410. while (ws.read(msg)) {
  18411. ws.send(msg);
  18412. }
  18413. },
  18414. [](const std::vector<std::string> &protocols) -> std::string {
  18415. for (const auto &p : protocols) {
  18416. if (p == "graphql-ws") { return p; }
  18417. }
  18418. return "";
  18419. });
  18420. }
  18421. void start_server() {
  18422. port_ = server_->bind_to_any_port(HOST);
  18423. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18424. server_->wait_until_ready();
  18425. }
  18426. std::unique_ptr<Server> server_;
  18427. std::thread server_thread_;
  18428. int port_ = 0;
  18429. };
  18430. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18431. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18432. "/ws-echo");
  18433. ASSERT_TRUE(client.connect());
  18434. ASSERT_TRUE(client.is_open());
  18435. ASSERT_TRUE(client.send("Hello WebSocket"));
  18436. std::string msg;
  18437. EXPECT_EQ(ws::Text, client.read(msg));
  18438. EXPECT_EQ("Hello WebSocket", msg);
  18439. client.close();
  18440. }
  18441. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18443. "/ws-echo");
  18444. ASSERT_TRUE(client.connect());
  18445. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18446. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18447. std::string msg;
  18448. EXPECT_EQ(ws::Binary, client.read(msg));
  18449. EXPECT_EQ(binary_data, msg);
  18450. client.close();
  18451. }
  18452. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18453. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18454. "/ws-echo");
  18455. ASSERT_TRUE(client.connect());
  18456. for (int i = 0; i < 10; i++) {
  18457. auto text = "message " + std::to_string(i);
  18458. ASSERT_TRUE(client.send(text));
  18459. std::string msg;
  18460. ASSERT_TRUE(client.read(msg));
  18461. EXPECT_EQ(text, msg);
  18462. }
  18463. client.close();
  18464. }
  18465. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18467. "/ws-close");
  18468. ASSERT_TRUE(client.connect());
  18469. // Send a message to trigger the server to close
  18470. ASSERT_TRUE(client.send("trigger close"));
  18471. // The server will close, so read should return false
  18472. std::string msg;
  18473. EXPECT_FALSE(client.read(msg));
  18474. EXPECT_FALSE(client.is_open());
  18475. }
  18476. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18478. "/ws-echo");
  18479. ASSERT_TRUE(client.connect());
  18480. // 128KB message
  18481. std::string large_data(128 * 1024, 'X');
  18482. ASSERT_TRUE(client.send(large_data));
  18483. std::string msg;
  18484. ASSERT_TRUE(client.read(msg));
  18485. EXPECT_EQ(large_data, msg);
  18486. client.close();
  18487. }
  18488. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18490. "/ws-echo");
  18491. ASSERT_TRUE(client.connect());
  18492. const int num_threads = 4;
  18493. std::vector<std::thread> threads;
  18494. std::atomic<int> send_count{0};
  18495. for (int t = 0; t < num_threads; t++) {
  18496. threads.emplace_back([&client, &send_count, t]() {
  18497. for (int i = 0; i < 5; i++) {
  18498. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18499. if (client.send(text)) { send_count++; }
  18500. }
  18501. });
  18502. }
  18503. for (auto &th : threads) {
  18504. th.join();
  18505. }
  18506. int received = 0;
  18507. std::string msg;
  18508. while (received < send_count.load()) {
  18509. if (!client.read(msg)) { break; }
  18510. received++;
  18511. }
  18512. EXPECT_EQ(send_count.load(), received);
  18513. client.close();
  18514. }
  18515. TEST_F(WebSocketIntegrationTest, ReadString) {
  18516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18517. "/ws-echo-string");
  18518. ASSERT_TRUE(client.connect());
  18519. ASSERT_TRUE(client.send("hello"));
  18520. std::string msg;
  18521. ASSERT_TRUE(client.read(msg));
  18522. EXPECT_EQ("echo: hello", msg);
  18523. ASSERT_TRUE(client.send("world"));
  18524. ASSERT_TRUE(client.read(msg));
  18525. EXPECT_EQ("echo: world", msg);
  18526. client.close();
  18527. }
  18528. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18529. Headers headers = {{"X-Test-Header", "test-value"}};
  18530. ws::WebSocketClient client(
  18531. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18532. ASSERT_TRUE(client.connect());
  18533. std::string msg;
  18534. ASSERT_TRUE(client.read(msg));
  18535. EXPECT_EQ("path:/ws-request-info", msg);
  18536. ASSERT_TRUE(client.read(msg));
  18537. EXPECT_EQ("header:test-value", msg);
  18538. client.close();
  18539. }
  18540. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18541. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18542. "/ws-echo");
  18543. client.set_read_timeout(1, 0); // 1 second
  18544. ASSERT_TRUE(client.connect());
  18545. // Don't send anything — server echo handler waits for a message,
  18546. // so read() should time out and return false.
  18547. std::string msg;
  18548. EXPECT_FALSE(client.read(msg));
  18549. }
  18550. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18551. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18552. "/ws-echo");
  18553. client.set_read_timeout(5, 0);
  18554. ASSERT_TRUE(client.connect());
  18555. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18556. // The server should reject it and close the connection.
  18557. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18558. client.send(oversized);
  18559. // The server's read() should have failed due to payload limit,
  18560. // so our read() should return false (connection closed).
  18561. std::string msg;
  18562. EXPECT_FALSE(client.read(msg));
  18563. }
  18564. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18566. "/ws-echo");
  18567. client.set_read_timeout(10, 0);
  18568. ASSERT_TRUE(client.connect());
  18569. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18570. // This should succeed.
  18571. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18572. ASSERT_TRUE(client.send(at_limit));
  18573. std::string msg;
  18574. ASSERT_TRUE(client.read(msg));
  18575. EXPECT_EQ(at_limit.size(), msg.size());
  18576. client.close();
  18577. }
  18578. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18580. "/nonexistent");
  18581. auto res = client.connect();
  18582. EXPECT_FALSE(res);
  18583. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18584. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18585. EXPECT_FALSE(client.is_open());
  18586. }
  18587. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18588. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18589. "/ws-echo");
  18590. ASSERT_TRUE(client.connect());
  18591. ASSERT_TRUE(client.send(""));
  18592. std::string msg;
  18593. EXPECT_EQ(ws::Text, client.read(msg));
  18594. EXPECT_EQ("", msg);
  18595. client.close();
  18596. }
  18597. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18598. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18599. "/ws-echo");
  18600. // First connection
  18601. ASSERT_TRUE(client.connect());
  18602. ASSERT_TRUE(client.send("first"));
  18603. std::string msg;
  18604. ASSERT_TRUE(client.read(msg));
  18605. EXPECT_EQ("first", msg);
  18606. client.close();
  18607. EXPECT_FALSE(client.is_open());
  18608. // Reconnect using the same client object
  18609. ASSERT_TRUE(client.connect());
  18610. ASSERT_TRUE(client.is_open());
  18611. ASSERT_TRUE(client.send("second"));
  18612. ASSERT_TRUE(client.read(msg));
  18613. EXPECT_EQ("second", msg);
  18614. client.close();
  18615. }
  18616. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18617. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18618. "/ws-close-status");
  18619. ASSERT_TRUE(client.connect());
  18620. // Trigger the server to close with GoingAway status
  18621. ASSERT_TRUE(client.send("trigger"));
  18622. // read() should return false after receiving the close frame
  18623. std::string msg;
  18624. EXPECT_FALSE(client.read(msg));
  18625. EXPECT_FALSE(client.is_open());
  18626. }
  18627. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18628. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18629. "/ws-echo");
  18630. ASSERT_TRUE(client.connect());
  18631. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18632. EXPECT_FALSE(client.is_open());
  18633. }
  18634. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18635. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18636. ws::WebSocketClient client(
  18637. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18638. ASSERT_TRUE(client.connect());
  18639. // Server should have selected graphql-ws
  18640. EXPECT_EQ("graphql-ws", client.subprotocol());
  18641. client.close();
  18642. }
  18643. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18644. Headers headers;
  18645. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18646. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18647. ws::WebSocketClient client(
  18648. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18649. ASSERT_TRUE(client.connect());
  18650. // The offer on the second field line counts too, so graphql-ws is selected
  18651. EXPECT_EQ("graphql-ws", client.subprotocol());
  18652. client.close();
  18653. }
  18654. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18655. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18656. ws::WebSocketClient client(
  18657. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18658. ASSERT_TRUE(client.connect());
  18659. // Server should not have selected any subprotocol
  18660. EXPECT_TRUE(client.subprotocol().empty());
  18661. client.close();
  18662. }
  18663. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18664. // Connect without requesting any subprotocol
  18665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18666. "/ws-subprotocol");
  18667. ASSERT_TRUE(client.connect());
  18668. EXPECT_TRUE(client.subprotocol().empty());
  18669. client.close();
  18670. }
  18671. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18672. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18673. "/ws-echo");
  18674. client.set_tcp_nodelay(true);
  18675. client.set_connection_timeout(3, 0);
  18676. bool socket_options_called = false;
  18677. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18678. ASSERT_TRUE(client.connect());
  18679. ASSERT_TRUE(client.is_open());
  18680. EXPECT_TRUE(socket_options_called);
  18681. ASSERT_TRUE(client.send("hello"));
  18682. std::string msg;
  18683. auto result = client.read(msg);
  18684. EXPECT_EQ(result, ws::ReadResult::Text);
  18685. EXPECT_EQ(msg, "hello");
  18686. client.close();
  18687. }
  18688. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18690. "/ws-echo");
  18691. client.set_connection_timeout(std::chrono::seconds(3));
  18692. client.set_write_timeout(std::chrono::seconds(3));
  18693. // A sub-second remainder exercises the seconds/microseconds split.
  18694. client.set_read_timeout(std::chrono::milliseconds(1500));
  18695. ASSERT_TRUE(client.connect());
  18696. auto start = std::chrono::steady_clock::now();
  18697. std::string msg;
  18698. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18699. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18700. std::chrono::steady_clock::now() - start)
  18701. .count();
  18702. // Above 1s so that dropping the microseconds half of the split fails here,
  18703. // and well under the 300s default so that ignoring the setter fails too.
  18704. EXPECT_GE(elapsed, 1400);
  18705. EXPECT_LT(elapsed, 30000);
  18706. }
  18707. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18708. Server svr;
  18709. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18710. if (!req.has_header("Authorization")) {
  18711. res.status = StatusCode::Unauthorized_401;
  18712. res.set_content("Unauthorized", "text/plain");
  18713. return Server::HandlerResponse::Handled;
  18714. }
  18715. return Server::HandlerResponse::Unhandled;
  18716. });
  18717. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18718. std::string msg;
  18719. while (ws.read(msg)) {
  18720. ws.send(msg);
  18721. }
  18722. });
  18723. auto port = svr.bind_to_any_port("localhost");
  18724. std::thread t([&]() { svr.listen_after_bind(); });
  18725. svr.wait_until_ready();
  18726. // Without Authorization header - should be rejected before upgrade
  18727. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18728. EXPECT_FALSE(client1.connect());
  18729. // With Authorization header - should succeed
  18730. Headers headers = {{"Authorization", "Bearer token123"}};
  18731. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18732. headers);
  18733. ASSERT_TRUE(client2.connect());
  18734. ASSERT_TRUE(client2.send("hello"));
  18735. std::string msg;
  18736. ASSERT_TRUE(client2.read(msg));
  18737. EXPECT_EQ("hello", msg);
  18738. client2.close();
  18739. svr.stop();
  18740. t.join();
  18741. }
  18742. TEST(WebSocketTest, QueryStringInHandshake) {
  18743. Server svr;
  18744. std::mutex mtx;
  18745. std::string received_target;
  18746. std::string received_token;
  18747. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18748. {
  18749. std::lock_guard<std::mutex> lock(mtx);
  18750. received_target = req.target;
  18751. if (req.has_param("token")) {
  18752. received_token = req.get_param_value("token");
  18753. }
  18754. }
  18755. std::string msg;
  18756. while (ws.read(msg)) {
  18757. ws.send(msg);
  18758. }
  18759. });
  18760. auto port = svr.bind_to_any_port("localhost");
  18761. std::thread t([&]() { svr.listen_after_bind(); });
  18762. svr.wait_until_ready();
  18763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18764. "/ws?token=ABC&session=123");
  18765. ASSERT_TRUE(client.connect());
  18766. // Round-trip ensures the handler has run and captured the request.
  18767. ASSERT_TRUE(client.send("hello"));
  18768. std::string msg;
  18769. ASSERT_TRUE(client.read(msg));
  18770. EXPECT_EQ("hello", msg);
  18771. client.close();
  18772. {
  18773. std::lock_guard<std::mutex> lock(mtx);
  18774. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18775. EXPECT_EQ("ABC", received_token);
  18776. }
  18777. svr.stop();
  18778. t.join();
  18779. }
  18780. // Run a handshake against a throwaway server and hand the request the server
  18781. // received back to the caller, so tests can assert on the headers the client
  18782. // actually put on the wire.
  18783. static void capture_websocket_handshake_request(
  18784. const Headers &client_headers,
  18785. std::function<void(const Request &, int port)> verify) {
  18786. Server svr;
  18787. std::mutex mtx;
  18788. Request received;
  18789. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18790. {
  18791. std::lock_guard<std::mutex> lock(mtx);
  18792. received = req;
  18793. }
  18794. std::string msg;
  18795. while (ws.read(msg)) {
  18796. ws.send(msg);
  18797. }
  18798. });
  18799. auto port = svr.bind_to_any_port("localhost");
  18800. std::thread t([&]() { svr.listen_after_bind(); });
  18801. auto se = detail::scope_exit([&] {
  18802. svr.stop();
  18803. t.join();
  18804. });
  18805. svr.wait_until_ready();
  18806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18807. client_headers);
  18808. ASSERT_TRUE(client.connect());
  18809. ASSERT_TRUE(client.send("hello"));
  18810. std::string msg;
  18811. ASSERT_TRUE(client.read(msg));
  18812. client.close();
  18813. {
  18814. std::lock_guard<std::mutex> lock(mtx);
  18815. verify(received, port);
  18816. }
  18817. }
  18818. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18819. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18820. // Non-default port must be present in the Host header. Default ports
  18821. // (80/443) are omitted; that logic is covered by
  18822. // MakeHostAndPortStringTest.
  18823. EXPECT_EQ("localhost:" + std::to_string(port),
  18824. req.get_header_value("Host"));
  18825. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18826. req.get_header_value("User-Agent"));
  18827. EXPECT_FALSE(req.has_header("Accept"));
  18828. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18829. EXPECT_FALSE(req.has_header("Content-Length"));
  18830. });
  18831. }
  18832. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18833. capture_websocket_handshake_request(
  18834. {{"Host", "example.com"},
  18835. {"User-Agent", "custom-agent"},
  18836. {"X-Custom", "value"}},
  18837. [](const Request &req, int) {
  18838. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18839. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18840. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18841. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18842. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18843. });
  18844. }
  18845. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18846. capture_websocket_handshake_request(
  18847. {{"Upgrade", "bogus"},
  18848. {"Connection", "close"},
  18849. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18850. {"Sec-WebSocket-Version", "8"}},
  18851. [](const Request &req, int) {
  18852. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18853. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18854. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18855. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18856. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18857. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18858. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18859. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18860. req.get_header_value("Sec-WebSocket-Key"));
  18861. });
  18862. }
  18863. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18864. // A header the client refuses to send must abort the handshake before any
  18865. // part of it reaches the wire; a lone request line would otherwise sit in
  18866. // the peer's buffer as a truncated request.
  18867. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18868. ASSERT_NE(INVALID_SOCKET, srv);
  18869. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18870. sockaddr_in addr{};
  18871. addr.sin_family = AF_INET;
  18872. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18874. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18875. ASSERT_EQ(0, ::listen(srv, 1));
  18876. sockaddr_in bound{};
  18877. socklen_t bound_len = sizeof(bound);
  18878. ASSERT_EQ(
  18879. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18880. auto port = ntohs(bound.sin_port);
  18881. ssize_t received = -1;
  18882. std::thread t([&] {
  18883. // Bound every blocking call so a regression fails the test with a bad
  18884. // value instead of hanging the suite.
  18885. fd_set rfds;
  18886. FD_ZERO(&rfds);
  18887. FD_SET(srv, &rfds);
  18888. timeval tv{5, 0};
  18889. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18890. 0) {
  18891. return;
  18892. }
  18893. sockaddr_in cli_addr{};
  18894. socklen_t cli_len = sizeof(cli_addr);
  18895. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18896. if (cli == INVALID_SOCKET) { return; }
  18897. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18898. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18899. char buf[4096];
  18900. received = ::recv(cli, buf, sizeof(buf), 0);
  18901. });
  18902. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18903. // connect() has already shut the socket down by the time it returns false,
  18904. // so the peer sees EOF without waiting for the client to be destroyed.
  18905. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18906. {{"X-Bad", "a\r\nInjected: 1"}});
  18907. EXPECT_FALSE(client.connect());
  18908. t.join();
  18909. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18910. EXPECT_EQ(0, received);
  18911. }
  18912. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18913. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18914. // contains "upgrade" as a substring is a different token and must not
  18915. // start a WebSocket handshake.
  18916. auto make_request = [](const std::vector<std::string> &connection_values) {
  18917. Request req;
  18918. req.method = "GET";
  18919. req.headers.emplace("Upgrade", "websocket");
  18920. for (const auto &value : connection_values) {
  18921. req.headers.emplace("Connection", value);
  18922. }
  18923. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18924. req.headers.emplace("Sec-WebSocket-Version", "13");
  18925. return req;
  18926. };
  18927. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18928. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18929. EXPECT_TRUE(
  18930. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18931. EXPECT_TRUE(
  18932. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18933. EXPECT_TRUE(
  18934. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18935. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18936. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18937. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18938. EXPECT_FALSE(
  18939. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18940. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18941. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18942. }
  18943. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18944. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18945. // asks recipients to match each protocol-name case-insensitively, and RFC
  18946. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18947. // client naming websocket alongside another protocol, or on a second field
  18948. // line, is offering websocket; a value that merely contains "websocket" as a
  18949. // substring is a different protocol name and is not.
  18950. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18951. Request req;
  18952. req.method = "GET";
  18953. for (const auto &value : upgrade_values) {
  18954. req.headers.emplace("Upgrade", value);
  18955. }
  18956. req.headers.emplace("Connection", "Upgrade");
  18957. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18958. req.headers.emplace("Sec-WebSocket-Version", "13");
  18959. return req;
  18960. };
  18961. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18962. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18963. EXPECT_TRUE(
  18964. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18965. EXPECT_TRUE(
  18966. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18967. EXPECT_TRUE(
  18968. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18969. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18970. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18971. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18972. EXPECT_FALSE(
  18973. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18974. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18975. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18976. }
  18977. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18978. Server svr;
  18979. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18980. auto port = svr.bind_to_any_port("localhost");
  18981. std::thread t([&]() { svr.listen_after_bind(); });
  18982. auto se = detail::scope_exit([&] {
  18983. svr.stop();
  18984. t.join();
  18985. });
  18986. svr.wait_until_ready();
  18987. Headers headers = {{"Upgrade", "websocket"},
  18988. {"Connection", "notupgrade"},
  18989. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18990. {"Sec-WebSocket-Version", "13"}};
  18991. Client cli("localhost", port);
  18992. auto res = cli.Get("/ws", headers);
  18993. // The route exists only as a WebSocket route, so a request that fails the
  18994. // handshake check falls through to ordinary routing.
  18995. ASSERT_TRUE(res);
  18996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18997. }
  18998. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18999. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19000. // Connection value is the only thing left for the client to reject.
  19001. Server svr;
  19002. svr.Get("/ws", [](const Request &req, Response &res) {
  19003. res.status = StatusCode::SwitchingProtocol_101;
  19004. res.set_header("Upgrade", "websocket");
  19005. res.set_header("Connection", "notupgrade");
  19006. res.set_header("Sec-WebSocket-Accept",
  19007. detail::websocket_accept_key(
  19008. req.get_header_value("Sec-WebSocket-Key")));
  19009. });
  19010. auto port = svr.bind_to_any_port("localhost");
  19011. std::thread t([&]() { svr.listen_after_bind(); });
  19012. auto se = detail::scope_exit([&] {
  19013. svr.stop();
  19014. t.join();
  19015. });
  19016. svr.wait_until_ready();
  19017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19018. auto res = client.connect();
  19019. EXPECT_FALSE(res);
  19020. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19021. EXPECT_FALSE(client.is_open());
  19022. }
  19023. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19024. // The socket path doubles as the URL host, so it must not contain '/'.
  19025. const char *shard = getenv("GTEST_SHARD_INDEX");
  19026. const std::string sock_path =
  19027. shard ? std::string("httplib-ws-") + shard + ".sock"
  19028. : std::string("httplib-ws.sock");
  19029. std::remove(sock_path.c_str());
  19030. Server svr;
  19031. std::mutex mtx;
  19032. std::string received_host;
  19033. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19034. {
  19035. std::lock_guard<std::mutex> lock(mtx);
  19036. received_host = req.get_header_value("Host");
  19037. }
  19038. std::string msg;
  19039. while (ws.read(msg)) {
  19040. ws.send(msg);
  19041. }
  19042. });
  19043. svr.set_address_family(AF_UNIX);
  19044. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19045. auto se = detail::scope_exit([&] {
  19046. svr.stop();
  19047. t.join();
  19048. std::remove(sock_path.c_str());
  19049. });
  19050. svr.wait_until_ready();
  19051. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19052. client.set_address_family(AF_UNIX);
  19053. ASSERT_TRUE(client.connect());
  19054. ASSERT_TRUE(client.send("hello"));
  19055. std::string msg;
  19056. ASSERT_TRUE(client.read(msg));
  19057. client.close();
  19058. {
  19059. std::lock_guard<std::mutex> lock(mtx);
  19060. // There is no host:port for a Unix socket, so the same "localhost"
  19061. // placeholder the HTTP client uses is expected.
  19062. EXPECT_EQ("localhost", received_host);
  19063. }
  19064. }
  19065. // Two threads must never parse WebSocket frames from the same stream.
  19066. // close() used to read the peer's Close reply with its own frame read, so it
  19067. // raced a reader thread that was in the middle of a payload: the payload loop
  19068. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19069. // so bytes taken by close() were replaced with bytes from further along the
  19070. // stream. The message kept its length and silently changed content.
  19071. //
  19072. // The raw peer below sends a frame header plus part of the payload, waits for
  19073. // the handler to call close(), and only then sends the rest. Whichever thread
  19074. // would win the race for those bytes, the message must arrive intact, because
  19075. // close() must not touch the stream while read() owns it.
  19076. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19077. #ifndef _WIN32
  19078. signal(SIGPIPE, SIG_IGN);
  19079. #endif
  19080. const size_t payload_len = 120; // fits the 7-bit length field
  19081. const size_t prefix_len = 8;
  19082. const int attempts = 8;
  19083. std::string expected(payload_len, '\0');
  19084. for (size_t i = 0; i < payload_len; i++) {
  19085. expected[i] = static_cast<char>('a' + i % 26);
  19086. }
  19087. std::atomic<bool> peer_stalled{false};
  19088. std::atomic<bool> handler_done{false};
  19089. std::mutex received_mutex;
  19090. std::vector<std::string> received;
  19091. // Bound every wait, so a regression fails the test instead of hanging the
  19092. // suite.
  19093. auto wait_for = [](const std::atomic<bool> &flag) {
  19094. for (int i = 0; i < 500 && !flag; i++) {
  19095. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19096. }
  19097. };
  19098. Server svr;
  19099. svr.set_websocket_ping_interval(0);
  19100. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19101. std::thread reader([&]() {
  19102. std::string msg;
  19103. while (ws.read(msg)) {
  19104. std::lock_guard<std::mutex> guard(received_mutex);
  19105. received.push_back(msg);
  19106. }
  19107. });
  19108. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19109. // inside read_websocket_frame() when close() runs.
  19110. wait_for(peer_stalled);
  19111. ws.close();
  19112. reader.join();
  19113. handler_done = true;
  19114. });
  19115. auto port = svr.bind_to_any_port("127.0.0.1");
  19116. std::thread t([&]() { svr.listen_after_bind(); });
  19117. auto se = detail::scope_exit([&] {
  19118. svr.stop();
  19119. t.join();
  19120. });
  19121. svr.wait_until_ready();
  19122. auto send_bytes = [](socket_t s, const std::string &data) {
  19123. #ifdef _WIN32
  19124. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19125. #else
  19126. auto n = ::send(s, data.data(), data.size(), 0);
  19127. #endif
  19128. return n == static_cast<decltype(n)>(data.size());
  19129. };
  19130. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19131. // Every length used here fits the 7-bit length field.
  19132. auto masked_header = [](uint8_t first_byte, size_t len) {
  19133. std::string h;
  19134. h += static_cast<char>(first_byte);
  19135. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19136. h.append(4, '\0'); // mask key
  19137. return h;
  19138. };
  19139. for (int attempt = 0; attempt < attempts; attempt++) {
  19140. peer_stalled = false;
  19141. handler_done = false;
  19142. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19143. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19144. auto se_sock = detail::scope_exit([&] {
  19145. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19146. });
  19147. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19148. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19149. sockaddr_in addr{};
  19150. addr.sin_family = AF_INET;
  19151. addr.sin_port = htons(static_cast<uint16_t>(port));
  19152. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19153. ASSERT_EQ(
  19154. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19155. << "attempt " << attempt;
  19156. ASSERT_TRUE(send_bytes(sock,
  19157. "GET /ws HTTP/1.1\r\n"
  19158. "Host: 127.0.0.1\r\n"
  19159. "Upgrade: websocket\r\n"
  19160. "Connection: Upgrade\r\n"
  19161. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19162. "Sec-WebSocket-Version: 13\r\n"
  19163. "\r\n"))
  19164. << "attempt " << attempt;
  19165. std::string response;
  19166. while (response.find("\r\n\r\n") == std::string::npos) {
  19167. char buf[512];
  19168. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19169. if (n <= 0) { break; }
  19170. response.append(buf, static_cast<size_t>(n));
  19171. }
  19172. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19173. << "attempt " << attempt;
  19174. // Send the header of a Binary message but only the first prefix_len bytes
  19175. // of its payload, leaving the reader thread stalled inside the payload.
  19176. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19177. expected.substr(0, prefix_len)))
  19178. << "attempt " << attempt;
  19179. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19180. peer_stalled = true;
  19181. // Let close() send its Close frame and park in its own read before the
  19182. // rest of the payload arrives, so both threads are waiting for it.
  19183. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19184. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19185. close_frame += static_cast<char>(0x03); // status 1000
  19186. close_frame += static_cast<char>(0xE8);
  19187. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19188. << "attempt " << attempt;
  19189. // Closing the peer releases the reader thread even on the buggy path,
  19190. // where it waits for bytes another thread already consumed.
  19191. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19192. detail::close_socket(sock);
  19193. sock = INVALID_SOCKET;
  19194. wait_for(handler_done);
  19195. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19196. }
  19197. std::lock_guard<std::mutex> guard(received_mutex);
  19198. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19199. << "a message in flight when close() ran was dropped";
  19200. for (size_t i = 0; i < received.size(); i++) {
  19201. EXPECT_EQ(expected, received[i]) << "message " << i;
  19202. }
  19203. }
  19204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19205. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19206. protected:
  19207. void SetUp() override {
  19208. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19209. SERVER_PRIVATE_KEY_FILE);
  19210. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19211. std::string msg;
  19212. ws::ReadResult ret;
  19213. while ((ret = ws.read(msg))) {
  19214. if (ret == ws::Binary) {
  19215. ws.send(msg.data(), msg.size());
  19216. } else {
  19217. ws.send(msg);
  19218. }
  19219. }
  19220. });
  19221. port_ = server_->bind_to_any_port(HOST);
  19222. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19223. server_->wait_until_ready();
  19224. }
  19225. void TearDown() override {
  19226. server_->stop();
  19227. if (server_thread_.joinable()) { server_thread_.join(); }
  19228. }
  19229. std::unique_ptr<SSLServer> server_;
  19230. std::thread server_thread_;
  19231. int port_ = 0;
  19232. };
  19233. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19234. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19235. "/ws-echo");
  19236. client.enable_server_certificate_verification(false);
  19237. ASSERT_TRUE(client.connect());
  19238. ASSERT_TRUE(client.is_open());
  19239. ASSERT_TRUE(client.send("Hello WSS"));
  19240. std::string msg;
  19241. EXPECT_EQ(ws::Text, client.read(msg));
  19242. EXPECT_EQ("Hello WSS", msg);
  19243. client.close();
  19244. }
  19245. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19246. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19247. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19248. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19249. // client (without calling close() first) is the only path that runs
  19250. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19251. // bug exactly.
  19252. //
  19253. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19254. // when linked against an instrumented libssl; run under Valgrind to catch it
  19255. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19256. // suite (the freed session otherwise stalls on the close handshake) — this test
  19257. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19258. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19259. {
  19260. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19261. "/ws-echo");
  19262. client.enable_server_certificate_verification(false);
  19263. client.set_read_timeout(2, 0);
  19264. client.set_write_timeout(2, 0);
  19265. ASSERT_TRUE(client.connect());
  19266. ASSERT_TRUE(client.is_open());
  19267. ASSERT_TRUE(client.send("still open"));
  19268. // Intentionally do NOT call client.close(): leaving scope runs
  19269. // shutdown_and_close() with the WebSocket still open, which must send the
  19270. // close frame while the TLS session is still alive.
  19271. }
  19272. }
  19273. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19274. // shutdown_and_close() at the start of connect(), reproducing the same
  19275. // use-after-free within the test body rather than at scope exit. The second
  19276. // connect must succeed and echo, proving the close handshake ran over a live
  19277. // session. See the note above about memory-tool requirements.
  19278. TEST_F(WebSocketSSLIntegrationTest,
  19279. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19280. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19281. "/ws-echo");
  19282. client.enable_server_certificate_verification(false);
  19283. client.set_read_timeout(2, 0);
  19284. client.set_write_timeout(2, 0);
  19285. ASSERT_TRUE(client.connect());
  19286. ASSERT_TRUE(client.is_open());
  19287. ASSERT_TRUE(client.send("still open"));
  19288. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19289. // the still-open connection, which must not touch a freed TLS session.
  19290. ASSERT_TRUE(client.connect());
  19291. ASSERT_TRUE(client.is_open());
  19292. ASSERT_TRUE(client.send("after reconnect"));
  19293. std::string msg;
  19294. EXPECT_EQ(ws::Text, client.read(msg));
  19295. EXPECT_EQ("after reconnect", msg);
  19296. client.close();
  19297. }
  19298. #endif
  19299. #ifdef CPPHTTPLIB_SSL_ENABLED
  19300. class WebSocketSSLCATest : public ::testing::Test {
  19301. protected:
  19302. void SetUp() override {
  19303. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19304. SERVER_PRIVATE_KEY_FILE);
  19305. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19306. std::string msg;
  19307. while (ws.read(msg)) {
  19308. ws.send(msg);
  19309. }
  19310. });
  19311. port_ = server_->bind_to_any_port("127.0.0.1");
  19312. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19313. server_->wait_until_ready();
  19314. }
  19315. void TearDown() override {
  19316. server_->stop();
  19317. if (server_thread_.joinable()) { server_thread_.join(); }
  19318. }
  19319. std::string url() const {
  19320. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19321. }
  19322. std::unique_ptr<SSLServer> server_;
  19323. std::thread server_thread_;
  19324. int port_ = 0;
  19325. };
  19326. // A custom CA loaded as PEM verifies the server with full certificate
  19327. // verification enabled
  19328. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19329. ws::WebSocketClient client(url());
  19330. std::string cert;
  19331. read_file(SERVER_CERT2_FILE, cert);
  19332. client.load_ca_cert_store(cert.c_str(), cert.size());
  19333. ASSERT_TRUE(client.connect());
  19334. ASSERT_TRUE(client.send("hello"));
  19335. std::string msg;
  19336. EXPECT_EQ(ws::Text, client.read(msg));
  19337. EXPECT_EQ("hello", msg);
  19338. client.close();
  19339. }
  19340. // A custom CA that does not cover the server must fail verification (the
  19341. // custom CA is exclusive; system certs are not loaded alongside it)
  19342. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19343. ws::WebSocketClient client(url());
  19344. std::string cert;
  19345. read_file(CLIENT_CA_CERT_FILE, cert);
  19346. client.load_ca_cert_store(cert.c_str(), cert.size());
  19347. auto res = client.connect();
  19348. ASSERT_FALSE(res);
  19349. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19350. EXPECT_EQ(-1, res.status());
  19351. EXPECT_NE(0u, res.ssl_backend_error());
  19352. }
  19353. // The same CA as a file path rather than PEM in memory
  19354. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19355. ws::WebSocketClient client(url());
  19356. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19357. ASSERT_TRUE(client.connect());
  19358. ASSERT_TRUE(client.send("hello"));
  19359. std::string msg;
  19360. EXPECT_EQ(ws::Text, client.read(msg));
  19361. EXPECT_EQ("hello", msg);
  19362. client.close();
  19363. }
  19364. // ...and a CA file that does not cover the server still fails, so it is the
  19365. // path above that decides the outcome
  19366. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19367. ws::WebSocketClient client(url());
  19368. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19369. ASSERT_FALSE(client.connect());
  19370. }
  19371. // Regression test: reconnecting with a native custom CA store used to reuse
  19372. // a store handle the previous TLS context had already freed (use-after-free
  19373. // under the OpenSSL backend). The context now lives as long as the client.
  19374. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19375. ws::WebSocketClient client(url());
  19376. std::string cert;
  19377. read_file(SERVER_CERT2_FILE, cert);
  19378. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19379. ASSERT_TRUE(client.connect());
  19380. client.close();
  19381. ASSERT_TRUE(client.connect());
  19382. ASSERT_TRUE(client.send("again"));
  19383. std::string msg;
  19384. EXPECT_EQ(ws::Text, client.read(msg));
  19385. EXPECT_EQ("again", msg);
  19386. client.close();
  19387. }
  19388. // Regression test: a certificate with a trusted chain but no identity match
  19389. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19390. // verification entirely for IP hosts, so this connection succeeded there.
  19391. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19392. // chain verification while the identity check must still fail.
  19393. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19395. ASSERT_TRUE(svr.is_valid());
  19396. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19397. std::string msg;
  19398. while (ws.read(msg)) {
  19399. ws.send(msg);
  19400. }
  19401. });
  19402. auto port = svr.bind_to_any_port("127.0.0.1");
  19403. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19404. auto se = detail::scope_exit([&] {
  19405. svr.stop();
  19406. t.join();
  19407. });
  19408. svr.wait_until_ready();
  19409. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19410. "/echo");
  19411. std::string cert;
  19412. read_file(SERVER_CERT_FILE, cert);
  19413. client.load_ca_cert_store(cert.c_str(), cert.size());
  19414. ASSERT_FALSE(client.connect());
  19415. }
  19416. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19417. // SNI, so nothing binds the host name to the TLS session. These bind the
  19418. // server to "localhost" instead, the only shape that exercises the SNI and
  19419. // hostname-verification path with certificate verification left enabled.
  19420. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19421. protected:
  19422. void Start(const char *cert_file) {
  19423. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19424. SERVER_PRIVATE_KEY_FILE);
  19425. ASSERT_TRUE(server_->is_valid());
  19426. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19427. std::string msg;
  19428. while (ws.read(msg)) {
  19429. ws.send(msg);
  19430. }
  19431. });
  19432. port_ = server_->bind_to_any_port("localhost");
  19433. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19434. server_->wait_until_ready();
  19435. }
  19436. void TearDown() override {
  19437. if (server_) { server_->stop(); }
  19438. if (server_thread_.joinable()) { server_thread_.join(); }
  19439. }
  19440. std::string url() const {
  19441. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19442. }
  19443. std::unique_ptr<SSLServer> server_;
  19444. std::thread server_thread_;
  19445. int port_ = 0;
  19446. };
  19447. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19448. // out and the connection is usable
  19449. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19450. Start(SERVER_CERT2_FILE);
  19451. ws::WebSocketClient client(url());
  19452. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19453. ASSERT_TRUE(client.connect());
  19454. ASSERT_TRUE(client.send("hello"));
  19455. std::string msg;
  19456. EXPECT_EQ(ws::Text, client.read(msg));
  19457. EXPECT_EQ("hello", msg);
  19458. client.close();
  19459. }
  19460. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19461. // while the identity check must still reject "localhost"
  19462. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19463. Start(SERVER_CERT_FILE);
  19464. ws::WebSocketClient client(url());
  19465. client.set_ca_cert_path(SERVER_CERT_FILE);
  19466. auto res = client.connect();
  19467. ASSERT_FALSE(res);
  19468. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19469. EXPECT_EQ(-1, res.status());
  19470. }
  19471. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19472. // disabled: the chain is still checked, only the identity check is skipped
  19473. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19474. Start(SERVER_CERT_FILE);
  19475. ws::WebSocketClient client(url());
  19476. client.set_ca_cert_path(SERVER_CERT_FILE);
  19477. client.enable_server_hostname_verification(false);
  19478. ASSERT_TRUE(client.connect());
  19479. ASSERT_TRUE(client.send("hello"));
  19480. std::string msg;
  19481. EXPECT_EQ(ws::Text, client.read(msg));
  19482. EXPECT_EQ("hello", msg);
  19483. client.close();
  19484. }
  19485. // A CA that did not sign the server certificate fails the chain, even though
  19486. // the name would match
  19487. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19488. Start(SERVER_CERT2_FILE);
  19489. ws::WebSocketClient client(url());
  19490. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19491. ASSERT_FALSE(client.connect());
  19492. }
  19493. // With verification disabled, neither the chain nor the name is checked
  19494. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19495. Start(SERVER_CERT_FILE);
  19496. ws::WebSocketClient client(url());
  19497. client.enable_server_certificate_verification(false);
  19498. ASSERT_TRUE(client.connect());
  19499. ASSERT_TRUE(client.send("hello"));
  19500. std::string msg;
  19501. EXPECT_EQ(ws::Text, client.read(msg));
  19502. EXPECT_EQ("hello", msg);
  19503. client.close();
  19504. }
  19505. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19506. protected:
  19507. void SetUp() override {
  19508. server_ = httplib::detail::make_unique<SSLServer>(
  19509. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19510. ASSERT_TRUE(server_->is_valid());
  19511. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19512. std::string msg;
  19513. while (ws.read(msg)) {
  19514. ws.send(msg);
  19515. }
  19516. });
  19517. port_ = server_->bind_to_any_port("localhost");
  19518. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19519. server_->wait_until_ready();
  19520. }
  19521. void TearDown() override {
  19522. server_->stop();
  19523. if (server_thread_.joinable()) { server_thread_.join(); }
  19524. }
  19525. std::string url() const {
  19526. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19527. }
  19528. void ConnectWithClientCert(const std::string &client_cert_file,
  19529. const std::string &client_private_key_file,
  19530. const char *private_key_password) {
  19531. std::string cert_pem, key_pem;
  19532. read_file(client_cert_file, cert_pem);
  19533. read_file(client_private_key_file, key_pem);
  19534. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19535. key_pem.c_str(), key_pem.size(),
  19536. private_key_password};
  19537. ws::WebSocketClient client(url(), pem);
  19538. ASSERT_TRUE(client.is_valid());
  19539. client.enable_server_certificate_verification(false);
  19540. ASSERT_TRUE(client.connect());
  19541. ASSERT_TRUE(client.send("hello"));
  19542. std::string msg;
  19543. EXPECT_EQ(ws::Text, client.read(msg));
  19544. EXPECT_EQ("hello", msg);
  19545. client.close();
  19546. }
  19547. std::unique_ptr<SSLServer> server_;
  19548. std::thread server_thread_;
  19549. int port_ = 0;
  19550. };
  19551. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19552. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19553. }
  19554. // Control for the tests above: the fixture's server really does require a
  19555. // client certificate, so it is the PEM the constructor installed that decides
  19556. // the outcome.
  19557. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19558. ws::WebSocketClient client(url());
  19559. ASSERT_TRUE(client.is_valid());
  19560. client.enable_server_certificate_verification(false);
  19561. EXPECT_FALSE(client.connect());
  19562. }
  19563. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19564. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19565. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19566. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19567. }
  19568. #endif
  19569. #if !defined(_WIN32)
  19570. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19571. auto secret_dir = std::string("./symlink_test_secret");
  19572. auto served_dir = std::string("./symlink_test_served");
  19573. auto secret_file = secret_dir + "/secret.txt";
  19574. auto symlink_path = served_dir + "/escape";
  19575. // Setup: create directories and files
  19576. mkdir(secret_dir.c_str(), 0755);
  19577. mkdir(served_dir.c_str(), 0755);
  19578. {
  19579. std::ofstream ofs(secret_file);
  19580. ofs << "SECRET_DATA";
  19581. }
  19582. // Create symlink using absolute path so it resolves correctly
  19583. #ifdef PATH_MAX
  19584. char abs_secret[PATH_MAX];
  19585. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19586. #else
  19587. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19588. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19589. ASSERT_NE(nullptr, abs_secret);
  19590. #endif
  19591. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19592. auto se = detail::scope_exit([&] {
  19593. unlink(symlink_path.c_str());
  19594. unlink(secret_file.c_str());
  19595. rmdir(served_dir.c_str());
  19596. rmdir(secret_dir.c_str());
  19597. });
  19598. Server svr;
  19599. svr.set_mount_point("/", served_dir);
  19600. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19601. auto se2 = detail::scope_exit([&] {
  19602. svr.stop();
  19603. listen_thread.join();
  19604. });
  19605. svr.wait_until_ready();
  19606. Client cli("localhost", PORT);
  19607. // Symlink pointing outside base dir should be blocked
  19608. auto res = cli.Get("/escape/secret.txt");
  19609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19610. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19611. }
  19612. #endif
  19613. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19614. // A GET request with Content-Length to a static file handler must have its
  19615. // body drained before the keep-alive connection is reused. Otherwise the
  19616. // unread body bytes are interpreted as the next HTTP request.
  19617. //
  19618. // The body is sent AFTER receiving the first response (as in the original
  19619. // PoC) so that the stream_line_reader cannot buffer it together with the
  19620. // headers of the first request.
  19621. Server svr;
  19622. svr.set_mount_point("/", "./www");
  19623. std::atomic<int> smuggled_count(0);
  19624. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19625. smuggled_count++;
  19626. res.set_content("oops", "text/plain");
  19627. });
  19628. auto port = svr.bind_to_any_port("localhost");
  19629. thread t = thread([&] { svr.listen_after_bind(); });
  19630. auto se = detail::scope_exit([&] {
  19631. svr.stop();
  19632. t.join();
  19633. });
  19634. svr.wait_until_ready();
  19635. auto error = Error::Success;
  19636. auto sock = detail::create_client_socket(
  19637. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19638. /*connection_timeout_sec=*/2, 0,
  19639. /*read_timeout_sec=*/2, 0,
  19640. /*write_timeout_sec=*/2, 0, std::string(), error);
  19641. ASSERT_NE(INVALID_SOCKET, sock);
  19642. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19643. // The "smuggled" request will be sent as the body of the outer GET
  19644. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19645. "Host: localhost\r\n"
  19646. "Connection: close\r\n"
  19647. "\r\n";
  19648. // Step 1: Send only the outer request headers (no body yet)
  19649. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19650. "Host: localhost\r\n"
  19651. "Content-Length: " +
  19652. std::to_string(smuggled.size()) +
  19653. "\r\n"
  19654. "\r\n";
  19655. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19656. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19657. // Step 2: Read the first response (server serves file without reading body)
  19658. std::string first_response;
  19659. char buf[4096];
  19660. for (;;) {
  19661. auto n = recv(sock, buf, sizeof(buf), 0);
  19662. if (n <= 0) break;
  19663. first_response.append(buf, static_cast<size_t>(n));
  19664. // Stop once we have a complete response (headers + body)
  19665. auto hdr_end = first_response.find("\r\n\r\n");
  19666. if (hdr_end != std::string::npos) {
  19667. // Check for Content-Length to know when the body is complete
  19668. auto cl_pos = first_response.find("Content-Length:");
  19669. if (cl_pos != std::string::npos) {
  19670. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19671. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19672. auto cl = std::stoul(
  19673. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19674. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19675. } else {
  19676. break; // No Content-Length, assume headers-only response
  19677. }
  19678. }
  19679. }
  19680. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19681. // Step 3: Now send the body, which looks like a new HTTP request.
  19682. // On a vulnerable server the keep-alive loop reads this as a second request.
  19683. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19684. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19685. // Step 4: Try to read a second response (should NOT exist after fix)
  19686. std::string second_response;
  19687. for (;;) {
  19688. auto n = recv(sock, buf, sizeof(buf), 0);
  19689. if (n <= 0) break;
  19690. second_response.append(buf, static_cast<size_t>(n));
  19691. }
  19692. // The smuggled request must NOT have been processed
  19693. EXPECT_EQ(0, smuggled_count.load());
  19694. }
  19695. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19696. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19697. // must be rejected with 400 Bad Request.
  19698. Server svr;
  19699. svr.Post("/test", [&](const Request &, Response &res) {
  19700. res.set_content("ok", "text/plain");
  19701. });
  19702. thread t = thread([&] { svr.listen(HOST, PORT); });
  19703. auto se = detail::scope_exit([&] {
  19704. svr.stop();
  19705. t.join();
  19706. ASSERT_FALSE(svr.is_running());
  19707. });
  19708. svr.wait_until_ready();
  19709. // Exact "chunked"
  19710. {
  19711. auto req = "POST /test HTTP/1.1\r\n"
  19712. "Host: localhost\r\n"
  19713. "Content-Length: 5\r\n"
  19714. "Transfer-Encoding: chunked\r\n"
  19715. "Connection: close\r\n"
  19716. "\r\n"
  19717. "hello";
  19718. std::string response;
  19719. ASSERT_TRUE(send_request(1, req, &response));
  19720. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19721. response.substr(0, response.find("\r\n")));
  19722. }
  19723. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19724. {
  19725. auto req = "POST /test HTTP/1.1\r\n"
  19726. "Host: localhost\r\n"
  19727. "Content-Length: 5\r\n"
  19728. "Transfer-Encoding: gzip, chunked\r\n"
  19729. "Connection: close\r\n"
  19730. "\r\n"
  19731. "hello";
  19732. std::string response;
  19733. ASSERT_TRUE(send_request(1, req, &response));
  19734. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19735. response.substr(0, response.find("\r\n")));
  19736. }
  19737. }
  19738. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19739. Server svr;
  19740. svr.Post("/test", [&](const Request &, Response &res) {
  19741. res.set_content("ok", "text/plain");
  19742. });
  19743. thread t = thread([&] { svr.listen(HOST, PORT); });
  19744. auto se = detail::scope_exit([&] {
  19745. svr.stop();
  19746. t.join();
  19747. ASSERT_FALSE(svr.is_running());
  19748. });
  19749. svr.wait_until_ready();
  19750. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19751. // length cannot be determined, so the server must answer 400 and close
  19752. // rather than treat the request as bodyless and leave the body in the
  19753. // socket for the next request to pick up.
  19754. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19755. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19756. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19757. std::string response;
  19758. ASSERT_TRUE(send_request(1, req, &response));
  19759. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19760. response.substr(0, response.find("\r\n")))
  19761. << transfer_encoding;
  19762. }
  19763. // RFC 9110 5.3: the codings may also be split across several
  19764. // Transfer-Encoding lines, which combine in the order they were received.
  19765. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19766. // just like the single-line "chunked, gzip" above.
  19767. {
  19768. auto req = "POST /test HTTP/1.1\r\n"
  19769. "Host: localhost\r\n"
  19770. "Transfer-Encoding: chunked\r\n"
  19771. "Transfer-Encoding: gzip\r\n"
  19772. "\r\n"
  19773. "0\r\n\r\n";
  19774. std::string response;
  19775. ASSERT_TRUE(send_request(1, req, &response));
  19776. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19777. response.substr(0, response.find("\r\n")));
  19778. }
  19779. // A sequence ending in chunked stays valid.
  19780. auto req = "POST /test HTTP/1.1\r\n"
  19781. "Host: localhost\r\n"
  19782. "Transfer-Encoding: gzip, chunked\r\n"
  19783. "Connection: close\r\n"
  19784. "\r\n"
  19785. "0\r\n\r\n";
  19786. std::string response;
  19787. ASSERT_TRUE(send_request(1, req, &response));
  19788. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19789. // ...including when it is spread over several lines.
  19790. auto split_req = "POST /test HTTP/1.1\r\n"
  19791. "Host: localhost\r\n"
  19792. "Transfer-Encoding: gzip\r\n"
  19793. "Transfer-Encoding: chunked\r\n"
  19794. "Connection: close\r\n"
  19795. "\r\n"
  19796. "0\r\n\r\n";
  19797. std::string split_response;
  19798. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19799. EXPECT_EQ("HTTP/1.1 200 OK",
  19800. split_response.substr(0, split_response.find("\r\n")));
  19801. }
  19802. // Regression for issue #2450: a DELETE without Content-Length on a
  19803. // keep-alive connection must not let the post-response drain consume the
  19804. // next request's bytes.
  19805. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19806. Server svr;
  19807. std::atomic<int> delete_count(0);
  19808. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19809. delete_count++;
  19810. res.status = StatusCode::NoContent_204;
  19811. });
  19812. auto port = svr.bind_to_any_port(HOST);
  19813. thread t = thread([&] { svr.listen_after_bind(); });
  19814. auto se = detail::scope_exit([&] {
  19815. svr.stop();
  19816. t.join();
  19817. });
  19818. svr.wait_until_ready();
  19819. auto error = Error::Success;
  19820. auto sock = detail::create_client_socket(
  19821. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19822. /*connection_timeout_sec=*/2, 0,
  19823. /*read_timeout_sec=*/2, 0,
  19824. /*write_timeout_sec=*/2, 0, std::string(), error);
  19825. ASSERT_NE(INVALID_SOCKET, sock);
  19826. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19827. auto send_request_and_read_response = [&](const std::string &req,
  19828. std::string &out) -> bool {
  19829. auto sent = send(sock, req.data(), req.size(), 0);
  19830. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19831. char buf[4096];
  19832. for (;;) {
  19833. auto n = recv(sock, buf, sizeof(buf), 0);
  19834. if (n <= 0) { return !out.empty(); }
  19835. out.append(buf, static_cast<size_t>(n));
  19836. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19837. }
  19838. };
  19839. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19840. "Host: localhost\r\n"
  19841. "\r\n";
  19842. std::string resp1;
  19843. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19844. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19845. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19846. "Host: localhost\r\n"
  19847. "Connection: close\r\n"
  19848. "\r\n";
  19849. std::string resp2;
  19850. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19851. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19852. EXPECT_EQ(2, delete_count.load());
  19853. }
  19854. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19855. Server svr;
  19856. svr.Post("/ingest", [&](const Request &, Response &res,
  19857. const ContentReader &content_reader) {
  19858. auto consumed = content_reader([](const char *, size_t) { return false; });
  19859. EXPECT_FALSE(consumed);
  19860. res.status = StatusCode::Conflict_409;
  19861. res.set_header("Connection", "close");
  19862. });
  19863. auto port = svr.bind_to_any_port(HOST);
  19864. thread t = thread([&] { svr.listen_after_bind(); });
  19865. auto se = detail::scope_exit([&] {
  19866. svr.stop();
  19867. t.join();
  19868. });
  19869. svr.wait_until_ready();
  19870. auto error = Error::Success;
  19871. auto sock = detail::create_client_socket(
  19872. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19873. /*connection_timeout_sec=*/2, 0,
  19874. /*read_timeout_sec=*/1, 0,
  19875. /*write_timeout_sec=*/2, 0, std::string(), error);
  19876. ASSERT_NE(INVALID_SOCKET, sock);
  19877. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19878. std::string request = "POST /ingest HTTP/1.1\r\n"
  19879. "Host: localhost\r\n"
  19880. "Transfer-Encoding: chunked\r\n"
  19881. "\r\n"
  19882. "4\r\n"
  19883. "data\r\n";
  19884. auto sent = send(sock, request.data(), request.size(), 0);
  19885. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19886. std::string response;
  19887. ssize_t received = 0;
  19888. do {
  19889. char buf[4096];
  19890. received = recv(sock, buf, sizeof(buf), 0);
  19891. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19892. } while (received > 0);
  19893. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19894. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19895. EXPECT_EQ(0, received);
  19896. }
  19897. namespace no_proxy_test {
  19898. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19899. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19900. // calling listen().
  19901. class ScopedServer {
  19902. public:
  19903. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19904. ~ScopedServer() {
  19905. svr_.stop();
  19906. if (th_.joinable()) { th_.join(); }
  19907. }
  19908. Server &svr() { return svr_; }
  19909. int port() const { return port_; }
  19910. void listen() {
  19911. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19912. svr_.wait_until_ready();
  19913. }
  19914. private:
  19915. Server svr_;
  19916. std::thread th_;
  19917. int port_ = 0;
  19918. };
  19919. class ProxyAndTargetServers {
  19920. public:
  19921. ProxyAndTargetServers() {
  19922. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19923. proxy_hits_++;
  19924. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19925. res.set_content("via-proxy", "text/plain");
  19926. });
  19927. target_.Get(".*", [this](const Request &req, Response &res) {
  19928. target_hits_++;
  19929. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19930. res.set_content("direct", "text/plain");
  19931. });
  19932. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19933. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19934. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19935. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19936. proxy_mock_.wait_until_ready();
  19937. target_.wait_until_ready();
  19938. }
  19939. ~ProxyAndTargetServers() {
  19940. proxy_mock_.stop();
  19941. target_.stop();
  19942. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19943. if (target_thread_.joinable()) { target_thread_.join(); }
  19944. }
  19945. Server &proxy_mock() { return proxy_mock_; }
  19946. Server &target() { return target_; }
  19947. int proxy_port() const { return proxy_port_; }
  19948. int target_port() const { return target_port_; }
  19949. int proxy_hits() const { return proxy_hits_.load(); }
  19950. int target_hits() const { return target_hits_.load(); }
  19951. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19952. void reset_counters() {
  19953. proxy_hits_ = 0;
  19954. target_hits_ = 0;
  19955. last_had_proxy_authz_ = false;
  19956. }
  19957. private:
  19958. Server proxy_mock_;
  19959. Server target_;
  19960. std::thread proxy_thread_;
  19961. std::thread target_thread_;
  19962. int proxy_port_ = 0;
  19963. int target_port_ = 0;
  19964. std::atomic<int> proxy_hits_{0};
  19965. std::atomic<int> target_hits_{0};
  19966. std::atomic<bool> last_had_proxy_authz_{false};
  19967. };
  19968. inline std::unique_ptr<Client> make_client(const std::string &host,
  19969. ProxyAndTargetServers &s) {
  19970. auto cli = detail::make_unique<Client>(host, s.target_port());
  19971. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19972. cli->set_proxy("127.0.0.1", s.proxy_port());
  19973. return cli;
  19974. }
  19975. } // namespace no_proxy_test
  19976. using no_proxy_test::make_client;
  19977. using no_proxy_test::ProxyAndTargetServers;
  19978. TEST(NoProxyTest, ExactHostnameBypasses) {
  19979. ProxyAndTargetServers s;
  19980. auto cli = make_client("example.com", s);
  19981. cli->set_no_proxy({"example.com"});
  19982. auto res = cli->Get("/");
  19983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19984. EXPECT_EQ(0, s.proxy_hits());
  19985. EXPECT_EQ(1, s.target_hits());
  19986. }
  19987. TEST(NoProxyTest, SubdomainBypasses) {
  19988. ProxyAndTargetServers s;
  19989. auto cli = make_client("foo.example.com", s);
  19990. cli->set_no_proxy({"example.com"});
  19991. auto res = cli->Get("/");
  19992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19993. EXPECT_EQ(0, s.proxy_hits());
  19994. EXPECT_EQ(1, s.target_hits());
  19995. }
  19996. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19997. // Regression guard: "evilexample.com" must not be considered a subdomain
  19998. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19999. // check would let traffic bypass the proxy and leak credentials direct
  20000. // to the attacker host.
  20001. ProxyAndTargetServers s;
  20002. auto cli = make_client("evilexample.com", s);
  20003. cli->set_no_proxy({"example.com"});
  20004. auto res = cli->Get("/");
  20005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20006. EXPECT_GE(s.proxy_hits(), 1);
  20007. EXPECT_EQ(0, s.target_hits());
  20008. }
  20009. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20010. ProxyAndTargetServers s;
  20011. auto cli = make_client("example.com.evil.com", s);
  20012. cli->set_no_proxy({"example.com"});
  20013. auto res = cli->Get("/");
  20014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20015. EXPECT_GE(s.proxy_hits(), 1);
  20016. EXPECT_EQ(0, s.target_hits());
  20017. }
  20018. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20019. ProxyAndTargetServers s;
  20020. auto cli = make_client("example.com", s);
  20021. cli->set_no_proxy({".example.com"});
  20022. auto res = cli->Get("/");
  20023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20024. EXPECT_EQ(0, s.proxy_hits());
  20025. EXPECT_EQ(1, s.target_hits());
  20026. }
  20027. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20028. ProxyAndTargetServers s;
  20029. auto cli = make_client("Example.COM", s);
  20030. cli->set_no_proxy({"EXAMPLE.com"});
  20031. auto res = cli->Get("/");
  20032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20033. EXPECT_EQ(0, s.proxy_hits());
  20034. EXPECT_EQ(1, s.target_hits());
  20035. }
  20036. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20037. ProxyAndTargetServers s;
  20038. auto cli = make_client("example.com.", s);
  20039. cli->set_no_proxy({"example.com"});
  20040. auto res = cli->Get("/");
  20041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20042. EXPECT_EQ(0, s.proxy_hits());
  20043. EXPECT_EQ(1, s.target_hits());
  20044. }
  20045. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20046. // Trailing dots must be normalized on BOTH sides — host and entry.
  20047. // An implementation that only strips the host-side trailing dot would
  20048. // fail to match host "example.com" against entry "example.com." because
  20049. // a literal substring search would compare 11 chars against 12.
  20050. ProxyAndTargetServers s;
  20051. auto cli = make_client("example.com", s);
  20052. cli->set_no_proxy({"example.com."});
  20053. auto res = cli->Get("/");
  20054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20055. EXPECT_EQ(0, s.proxy_hits());
  20056. EXPECT_EQ(1, s.target_hits());
  20057. }
  20058. TEST(NoProxyTest, WildcardBypassesEverything) {
  20059. ProxyAndTargetServers s;
  20060. auto cli = make_client("anything.invalid.test", s);
  20061. cli->set_no_proxy({"*"});
  20062. auto res = cli->Get("/");
  20063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20064. EXPECT_EQ(0, s.proxy_hits());
  20065. EXPECT_EQ(1, s.target_hits());
  20066. }
  20067. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20068. ProxyAndTargetServers s;
  20069. Client cli("127.0.0.1", s.target_port());
  20070. cli.set_proxy("127.0.0.1", s.proxy_port());
  20071. cli.set_no_proxy({"127.0.0.1"});
  20072. auto res = cli.Get("/");
  20073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20074. EXPECT_EQ(0, s.proxy_hits());
  20075. EXPECT_EQ(1, s.target_hits());
  20076. }
  20077. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20078. ProxyAndTargetServers s;
  20079. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20080. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20081. cli.set_proxy("127.0.0.1", s.proxy_port());
  20082. cli.set_no_proxy({"::1"});
  20083. auto res = cli.Get("/");
  20084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20085. EXPECT_EQ(0, s.proxy_hits());
  20086. EXPECT_EQ(1, s.target_hits());
  20087. }
  20088. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20089. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20090. // must still be recognized as IPv6 for CIDR matching. Implementations
  20091. // that detect IPv6 only when the host begins with '[' would parse the
  20092. // host as a hostname and miss the match.
  20093. ProxyAndTargetServers s;
  20094. Client cli("fe80::1", s.target_port());
  20095. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20096. cli.set_proxy("127.0.0.1", s.proxy_port());
  20097. cli.set_no_proxy({"fe80::/10"});
  20098. auto res = cli.Get("/");
  20099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20100. EXPECT_EQ(0, s.proxy_hits());
  20101. EXPECT_EQ(1, s.target_hits());
  20102. }
  20103. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20104. ProxyAndTargetServers s;
  20105. Client cli("::1", s.target_port());
  20106. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20107. cli.set_proxy("127.0.0.1", s.proxy_port());
  20108. cli.set_no_proxy({"[::1]"});
  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, BracketedIPv6CidrEntryAccepted) {
  20115. ProxyAndTargetServers s;
  20116. Client cli("fe80::1", s.target_port());
  20117. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20118. cli.set_proxy("127.0.0.1", s.proxy_port());
  20119. cli.set_no_proxy({"[fe80::]/10"});
  20120. auto res = cli.Get("/");
  20121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20122. EXPECT_EQ(0, s.proxy_hits());
  20123. EXPECT_EQ(1, s.target_hits());
  20124. }
  20125. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20126. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20127. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20128. // tricks via address-family conversion.
  20129. ProxyAndTargetServers s;
  20130. Client cli("::ffff:127.0.0.1", s.target_port());
  20131. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20132. cli.set_proxy("127.0.0.1", s.proxy_port());
  20133. cli.set_no_proxy({"127.0.0.1"});
  20134. auto res = cli.Get("/");
  20135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20136. EXPECT_GE(s.proxy_hits(), 1);
  20137. EXPECT_EQ(0, s.target_hits());
  20138. }
  20139. TEST(NoProxyTest, IPv4CidrMatch) {
  20140. ProxyAndTargetServers s;
  20141. Client cli("127.0.0.1", s.target_port());
  20142. cli.set_proxy("127.0.0.1", s.proxy_port());
  20143. cli.set_no_proxy({"127.0.0.0/8"});
  20144. auto res = cli.Get("/");
  20145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20146. EXPECT_EQ(0, s.proxy_hits());
  20147. EXPECT_EQ(1, s.target_hits());
  20148. }
  20149. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20150. ProxyAndTargetServers s;
  20151. Client cli("127.0.0.1", s.target_port());
  20152. cli.set_proxy("127.0.0.1", s.proxy_port());
  20153. cli.set_no_proxy({"10.0.0.0/8"});
  20154. auto res = cli.Get("/");
  20155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20156. EXPECT_GE(s.proxy_hits(), 1);
  20157. EXPECT_EQ(0, s.target_hits());
  20158. }
  20159. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20160. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20161. // IPv4 target matches.
  20162. ProxyAndTargetServers s;
  20163. Client cli("127.0.0.1", s.target_port());
  20164. cli.set_proxy("127.0.0.1", s.proxy_port());
  20165. cli.set_no_proxy({"0.0.0.0/0"});
  20166. auto res = cli.Get("/");
  20167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20168. EXPECT_EQ(0, s.proxy_hits());
  20169. EXPECT_EQ(1, s.target_hits());
  20170. }
  20171. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20172. ProxyAndTargetServers s;
  20173. Client cli("127.0.0.1", s.target_port());
  20174. cli.set_proxy("127.0.0.1", s.proxy_port());
  20175. cli.set_no_proxy({"127.0.0.1"});
  20176. auto res = cli.Get("/");
  20177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20178. EXPECT_EQ(0, s.proxy_hits());
  20179. EXPECT_EQ(1, s.target_hits());
  20180. }
  20181. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20182. ProxyAndTargetServers s;
  20183. Client cli("127.0.0.1", s.target_port());
  20184. cli.set_proxy("127.0.0.1", s.proxy_port());
  20185. cli.set_no_proxy({"127.0.0.0/33"});
  20186. auto res = cli.Get("/");
  20187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20188. EXPECT_GE(s.proxy_hits(), 1);
  20189. EXPECT_EQ(0, s.target_hits());
  20190. }
  20191. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20192. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20193. ProxyAndTargetServers s;
  20194. Client cli("127.0.0.1", s.target_port());
  20195. cli.set_proxy("127.0.0.1", s.proxy_port());
  20196. cli.set_no_proxy({"127.0.0.1/"});
  20197. auto res = cli.Get("/");
  20198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20199. EXPECT_GE(s.proxy_hits(), 1);
  20200. EXPECT_EQ(0, s.target_hits());
  20201. }
  20202. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20203. ProxyAndTargetServers s;
  20204. auto cli = make_client("internal.corp", s);
  20205. cli->set_proxy_basic_auth("u", "p");
  20206. cli->set_no_proxy({"internal.corp"});
  20207. auto res = cli->Get("/");
  20208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20209. EXPECT_EQ(1, s.target_hits());
  20210. EXPECT_EQ(0, s.proxy_hits());
  20211. EXPECT_FALSE(s.last_had_proxy_authz())
  20212. << "Proxy-Authorization must not be sent direct to the target";
  20213. }
  20214. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20215. ProxyAndTargetServers s;
  20216. auto cli = make_client("public.example", s);
  20217. cli->set_proxy_basic_auth("u", "p");
  20218. cli->set_no_proxy({"internal.corp"}); // does not match
  20219. auto res = cli->Get("/");
  20220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20221. EXPECT_GE(s.proxy_hits(), 1);
  20222. EXPECT_TRUE(s.last_had_proxy_authz());
  20223. }
  20224. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20225. ProxyAndTargetServers s;
  20226. auto cli = make_client("anything.test", s);
  20227. auto res = cli->Get("/");
  20228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20229. EXPECT_GE(s.proxy_hits(), 1);
  20230. EXPECT_EQ(0, s.target_hits());
  20231. }
  20232. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20233. ProxyAndTargetServers s;
  20234. auto cli = make_client("example.com", s);
  20235. cli->set_no_proxy({"example.com:8080"});
  20236. auto res = cli->Get("/");
  20237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20238. EXPECT_GE(s.proxy_hits(), 1);
  20239. EXPECT_EQ(0, s.target_hits());
  20240. }
  20241. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20242. ProxyAndTargetServers s;
  20243. auto cli = make_client("anything.test", s);
  20244. cli->set_no_proxy({"", " ", "\t"});
  20245. auto res = cli->Get("/");
  20246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20247. EXPECT_GE(s.proxy_hits(), 1);
  20248. EXPECT_EQ(0, s.target_hits());
  20249. }
  20250. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20251. // An entry with leading/trailing whitespace must still match — env-style
  20252. // values are commonly pasted with stray spaces and an implementation
  20253. // that feeds the raw token directly to inet_pton would fail to match
  20254. // valid CIDRs because of the spaces.
  20255. ProxyAndTargetServers s;
  20256. Client cli("127.0.0.1", s.target_port());
  20257. cli.set_proxy("127.0.0.1", s.proxy_port());
  20258. cli.set_no_proxy({" 127.0.0.0/8 "});
  20259. auto res = cli.Get("/");
  20260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20261. EXPECT_EQ(0, s.proxy_hits());
  20262. EXPECT_EQ(1, s.target_hits());
  20263. }
  20264. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20265. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20266. // go direct and must NOT carry Proxy-Authorization.
  20267. std::atomic<int> proxy_hits{0};
  20268. std::atomic<int> target_hits{0};
  20269. std::atomic<bool> target_saw_authz{false};
  20270. no_proxy_test::ScopedServer proxy_mock, target;
  20271. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20272. proxy_hits++;
  20273. res.status = 302;
  20274. res.set_header("Location", "http://127.0.0.1:" +
  20275. std::to_string(target.port()) + "/landed");
  20276. });
  20277. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20278. target_hits++;
  20279. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20280. res.set_content("direct", "text/plain");
  20281. });
  20282. proxy_mock.listen();
  20283. target.listen();
  20284. Client cli("public.example", target.port());
  20285. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20286. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20287. cli.set_proxy_basic_auth("u", "p");
  20288. cli.set_no_proxy({"127.0.0.1"});
  20289. cli.set_follow_location(true);
  20290. auto res = cli.Get("/redir");
  20291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20292. EXPECT_GE(proxy_hits.load(), 1);
  20293. EXPECT_GE(target_hits.load(), 1);
  20294. EXPECT_FALSE(target_saw_authz.load());
  20295. }
  20296. #ifdef CPPHTTPLIB_SSL_ENABLED
  20297. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20298. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20299. // proxy creds would be sent to the (possibly hostile) origin.
  20300. std::atomic<int> target_hits{0};
  20301. std::atomic<bool> target_saw_proxy_authz{false};
  20302. no_proxy_test::ScopedServer target;
  20303. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20304. target_hits++;
  20305. if (req.has_header("Proxy-Authorization")) {
  20306. target_saw_proxy_authz = true;
  20307. }
  20308. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20309. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20310. "nonce=\"abc\", algorithm=MD5");
  20311. });
  20312. target.listen();
  20313. // The proxy address is set to the target's port: the bypass MUST kick in;
  20314. // if it doesn't, the test still routes "via proxy" to the same server and
  20315. // the Proxy-Authorization assertion below catches the leak.
  20316. Client cli("evil.example", target.port());
  20317. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20318. cli.set_proxy("127.0.0.1", target.port());
  20319. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20320. cli.set_no_proxy({"evil.example"});
  20321. auto res = cli.Get("/x");
  20322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20323. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20324. EXPECT_EQ(1, target_hits.load());
  20325. EXPECT_FALSE(target_saw_proxy_authz.load());
  20326. }
  20327. #endif
  20328. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20329. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20330. std::atomic<int> proxy_hits{0};
  20331. std::atomic<int> bypass_hits{0};
  20332. std::atomic<bool> proxy_saw_c_url{false};
  20333. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20334. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20335. proxy_hits++;
  20336. if (req.path.find("/start") != std::string::npos) {
  20337. res.status = 302;
  20338. res.set_header("Location", "http://127.0.0.1:" +
  20339. std::to_string(bypass_server.port()) +
  20340. "/middle");
  20341. return;
  20342. }
  20343. if (req.path.find("/end") != std::string::npos) {
  20344. proxy_saw_c_url = true;
  20345. res.set_content("c-via-proxy", "text/plain");
  20346. return;
  20347. }
  20348. res.set_content("unexpected", "text/plain");
  20349. });
  20350. // public.example's "advertised" port is arbitrary (the request never lands
  20351. // there — it goes through the proxy), but use a dynamic value to stay
  20352. // friendly with sharded parallel runs.
  20353. int public_port = bypass_server.port();
  20354. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20355. bypass_hits++;
  20356. res.status = 302;
  20357. res.set_header("Location", "http://public.example:" +
  20358. std::to_string(public_port) + "/end");
  20359. });
  20360. proxy_mock.listen();
  20361. bypass_server.listen();
  20362. Client cli("public.example", public_port);
  20363. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20364. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20365. cli.set_no_proxy({"127.0.0.1"});
  20366. cli.set_follow_location(true);
  20367. auto res = cli.Get("/start");
  20368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20369. EXPECT_EQ(StatusCode::OK_200, res->status);
  20370. EXPECT_EQ("c-via-proxy", res->body);
  20371. EXPECT_GE(proxy_hits.load(), 2);
  20372. EXPECT_GE(bypass_hits.load(), 1);
  20373. EXPECT_TRUE(proxy_saw_c_url.load());
  20374. }
  20375. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20376. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20377. // request reconnects to the correct endpoint.
  20378. std::atomic<int> proxy_hits{0};
  20379. std::atomic<int> target_hits{0};
  20380. no_proxy_test::ScopedServer proxy_mock, target;
  20381. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20382. proxy_hits++;
  20383. res.set_content("via-proxy", "text/plain");
  20384. });
  20385. target.svr().Get(".*", [&](const Request &, Response &res) {
  20386. target_hits++;
  20387. res.set_content("direct", "text/plain");
  20388. });
  20389. proxy_mock.listen();
  20390. target.listen();
  20391. Client cli("public.example", target.port());
  20392. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20393. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20394. cli.set_keep_alive(true);
  20395. auto res1 = cli.Get("/a");
  20396. ASSERT_TRUE(res1);
  20397. EXPECT_EQ("via-proxy", res1->body);
  20398. EXPECT_EQ(1, proxy_hits.load());
  20399. EXPECT_EQ(0, target_hits.load());
  20400. cli.set_no_proxy({"public.example"});
  20401. auto res2 = cli.Get("/b");
  20402. ASSERT_TRUE(res2);
  20403. EXPECT_EQ("direct", res2->body);
  20404. EXPECT_EQ(1, proxy_hits.load());
  20405. EXPECT_EQ(1, target_hits.load());
  20406. }
  20407. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20408. namespace proxy_tunnel_test {
  20409. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20410. class ScopedSSLServer {
  20411. public:
  20412. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20413. port_ = svr_.bind_to_any_port("127.0.0.1");
  20414. }
  20415. ~ScopedSSLServer() {
  20416. svr_.stop();
  20417. if (th_.joinable()) { th_.join(); }
  20418. }
  20419. SSLServer &svr() { return svr_; }
  20420. int port() const { return port_; }
  20421. void listen() {
  20422. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20423. svr_.wait_until_ready();
  20424. }
  20425. private:
  20426. SSLServer svr_;
  20427. std::thread th_;
  20428. int port_ = 0;
  20429. };
  20430. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20431. class ScopedConnectProxy {
  20432. public:
  20433. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20434. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20435. if (listen_fd_ < 0) { return; }
  20436. int yes = 1;
  20437. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20438. sockaddr_in a{};
  20439. a.sin_family = AF_INET;
  20440. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20441. a.sin_port = 0;
  20442. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20443. return;
  20444. }
  20445. socklen_t alen = sizeof(a);
  20446. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20447. 0) {
  20448. return;
  20449. }
  20450. port_ = ntohs(a.sin_port);
  20451. if (::listen(listen_fd_, 1) != 0) { return; }
  20452. th_ = std::thread([this] { run(); });
  20453. }
  20454. ~ScopedConnectProxy() {
  20455. stop_ = true;
  20456. if (listen_fd_ >= 0) {
  20457. ::shutdown(listen_fd_, SHUT_RDWR);
  20458. ::close(listen_fd_);
  20459. }
  20460. if (th_.joinable()) { th_.join(); }
  20461. }
  20462. int port() const { return port_; }
  20463. int connect_hits() const { return connect_hits_.load(); }
  20464. private:
  20465. void run() {
  20466. while (!stop_.load()) {
  20467. fd_set rfds;
  20468. FD_ZERO(&rfds);
  20469. FD_SET(listen_fd_, &rfds);
  20470. timeval tv{0, 100 * 1000};
  20471. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20472. if (sel <= 0) { continue; }
  20473. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20474. if (client_fd < 0) { continue; }
  20475. std::string req;
  20476. char buf[2048];
  20477. while (req.find("\r\n\r\n") == std::string::npos) {
  20478. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20479. if (n <= 0) { break; }
  20480. req.append(buf, static_cast<size_t>(n));
  20481. }
  20482. if (req.compare(0, 7, "CONNECT") != 0) {
  20483. ::close(client_fd);
  20484. continue;
  20485. }
  20486. connect_hits_++;
  20487. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20488. ::send(client_fd, ok, std::strlen(ok), 0);
  20489. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20490. sockaddr_in o{};
  20491. o.sin_family = AF_INET;
  20492. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20493. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20494. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20495. 0) {
  20496. ::close(client_fd);
  20497. ::close(origin_fd);
  20498. continue;
  20499. }
  20500. auto forward = [](int from, int to) {
  20501. char b[8192];
  20502. for (;;) {
  20503. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20504. if (n <= 0) { break; }
  20505. ssize_t off = 0;
  20506. while (off < n) {
  20507. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20508. if (s <= 0) {
  20509. off = n;
  20510. break;
  20511. }
  20512. off += s;
  20513. }
  20514. }
  20515. ::shutdown(to, SHUT_WR);
  20516. };
  20517. std::thread t1([&] { forward(client_fd, origin_fd); });
  20518. std::thread t2([&] { forward(origin_fd, client_fd); });
  20519. t1.join();
  20520. t2.join();
  20521. ::close(client_fd);
  20522. ::close(origin_fd);
  20523. }
  20524. }
  20525. int forward_port_ = -1;
  20526. int listen_fd_ = -1;
  20527. int port_ = 0;
  20528. std::thread th_;
  20529. std::atomic<bool> stop_{false};
  20530. std::atomic<int> connect_hits_{0};
  20531. };
  20532. } // namespace proxy_tunnel_test
  20533. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20534. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20535. // retry; otherwise proxy creds would be sent to the origin.
  20536. std::atomic<int> origin_hits{0};
  20537. std::atomic<bool> origin_saw_proxy_authz{false};
  20538. proxy_tunnel_test::ScopedSSLServer origin;
  20539. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20540. origin_hits++;
  20541. if (req.has_header("Proxy-Authorization")) {
  20542. origin_saw_proxy_authz = true;
  20543. }
  20544. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20545. res.set_header("Proxy-Authenticate",
  20546. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20547. "algorithm=MD5");
  20548. });
  20549. origin.listen();
  20550. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20551. ASSERT_NE(0, proxy.port());
  20552. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20553. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20554. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20555. // and answer with its own status, making this test flaky.
  20556. SSLClient cli("127.0.0.1", origin.port());
  20557. cli.enable_server_certificate_verification(false);
  20558. cli.set_proxy("127.0.0.1", proxy.port());
  20559. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20560. auto res = cli.Get("/x");
  20561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20562. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20563. EXPECT_EQ(1, origin_hits.load());
  20564. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20565. EXPECT_EQ(1, proxy.connect_hits());
  20566. }
  20567. #endif