test.cc 771 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(BearerTokenAuthTest, SchemeValidation) {
  1358. // A value shorter than "Bearer " must not throw from the fixed-length
  1359. // substr, and a non-Bearer scheme must not be reported as a token.
  1360. struct {
  1361. const char *value;
  1362. const char *expected;
  1363. } cases[] = {
  1364. {"x", ""},
  1365. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1366. {"Bearer abc123", "abc123"},
  1367. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1368. };
  1369. for (const auto &c : cases) {
  1370. Request req;
  1371. req.set_header("Authorization", c.value);
  1372. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1373. }
  1374. }
  1375. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1376. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1377. // to depend on the standard library (libstdc++ handed back duplicates in
  1378. // reverse insertion order, libc++ in insertion order).
  1379. Request req;
  1380. req.set_header("Accept-Encoding", "gzip");
  1381. req.set_header("Accept-Encoding", "deflate");
  1382. req.set_header("Accept-Encoding", "br");
  1383. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1384. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1385. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1386. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1387. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1388. }
  1389. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1390. Request req;
  1391. req.set_header("X-Test", "only");
  1392. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1393. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1394. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1395. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1396. }
  1397. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1398. Headers headers;
  1399. headers.emplace("Host", "example.com");
  1400. headers.emplace("Accept-Encoding", "gzip");
  1401. headers.emplace("User-Agent", "test");
  1402. headers.emplace("Accept-Encoding", "deflate");
  1403. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1404. "Accept-Encoding=deflate ",
  1405. entries_to_string(headers));
  1406. }
  1407. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1408. Headers headers = {{"Content-Type", "text/html"},
  1409. {"CONTENT-TYPE", "text/xml"}};
  1410. EXPECT_EQ(2U, headers.count("content-type"));
  1411. auto it = headers.find("content-type");
  1412. ASSERT_TRUE(it != headers.end());
  1413. EXPECT_EQ("text/html", it->second);
  1414. }
  1415. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1416. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1417. // drop only those fields and leave everything positioned between them.
  1418. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1419. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1420. auto rng = headers.equal_range("a");
  1421. headers.erase(rng.first, rng.second);
  1422. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1423. }
  1424. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1425. Headers headers = {
  1426. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1427. EXPECT_EQ(3U, headers.erase("A"));
  1428. EXPECT_EQ(0U, headers.count("A"));
  1429. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1430. }
  1431. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1432. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1433. headers.emplace_front("Host", "example.com");
  1434. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1435. entries_to_string(headers));
  1436. }
  1437. TEST(ParseHeaderValueTest, Range) {
  1438. {
  1439. Ranges ranges;
  1440. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1441. EXPECT_TRUE(ret);
  1442. EXPECT_EQ(1u, ranges.size());
  1443. EXPECT_EQ(1u, ranges[0].first);
  1444. EXPECT_EQ(-1, ranges[0].second);
  1445. }
  1446. {
  1447. Ranges ranges;
  1448. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1449. EXPECT_TRUE(ret);
  1450. EXPECT_EQ(1u, ranges.size());
  1451. EXPECT_EQ(-1, ranges[0].first);
  1452. EXPECT_EQ(1u, ranges[0].second);
  1453. }
  1454. {
  1455. Ranges ranges;
  1456. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1457. EXPECT_TRUE(ret);
  1458. EXPECT_EQ(1u, ranges.size());
  1459. EXPECT_EQ(1u, ranges[0].first);
  1460. EXPECT_EQ(10u, ranges[0].second);
  1461. }
  1462. {
  1463. Ranges ranges;
  1464. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1465. EXPECT_FALSE(ret);
  1466. }
  1467. {
  1468. Ranges ranges;
  1469. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1470. EXPECT_TRUE(ret);
  1471. EXPECT_EQ(2u, ranges.size());
  1472. EXPECT_EQ(1u, ranges[0].first);
  1473. EXPECT_EQ(10u, ranges[0].second);
  1474. EXPECT_EQ(100u, ranges[1].first);
  1475. EXPECT_EQ(-1, ranges[1].second);
  1476. }
  1477. {
  1478. Ranges ranges;
  1479. auto ret =
  1480. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1481. EXPECT_TRUE(ret);
  1482. EXPECT_EQ(3u, ranges.size());
  1483. EXPECT_EQ(1u, ranges[0].first);
  1484. EXPECT_EQ(10u, ranges[0].second);
  1485. EXPECT_EQ(100u, ranges[1].first);
  1486. EXPECT_EQ(200u, ranges[1].second);
  1487. EXPECT_EQ(300u, ranges[2].first);
  1488. EXPECT_EQ(400u, ranges[2].second);
  1489. }
  1490. {
  1491. Ranges ranges;
  1492. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1493. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1494. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1495. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1496. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1497. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1498. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1499. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1500. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1501. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1502. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1503. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1504. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1505. EXPECT_TRUE(ranges.empty());
  1506. }
  1507. }
  1508. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1509. Request req;
  1510. req.set_header("Accept-Encoding", "gzip");
  1511. Response res;
  1512. res.set_header("Content-Type", "text/plain");
  1513. auto ret = detail::encoding_type(req, res);
  1514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1521. Request req;
  1522. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1523. Response res;
  1524. res.set_header("Content-Type", "text/plain");
  1525. auto ret = detail::encoding_type(req, res);
  1526. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1527. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1528. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1529. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1530. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1531. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1532. #else
  1533. EXPECT_TRUE(ret == detail::EncodingType::None);
  1534. #endif
  1535. }
  1536. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1537. Request req;
  1538. req.set_header("Accept-Encoding",
  1539. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1540. Response res;
  1541. res.set_header("Content-Type", "text/plain");
  1542. auto ret = detail::encoding_type(req, res);
  1543. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1544. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1545. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1546. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1547. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1548. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1549. #else
  1550. EXPECT_TRUE(ret == detail::EncodingType::None);
  1551. #endif
  1552. }
  1553. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1554. // All supported encodings rejected with q=0 should return None
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1563. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. EXPECT_TRUE(ret == detail::EncodingType::None);
  1570. }
  1571. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1572. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1573. Request req;
  1574. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1575. Response res;
  1576. res.set_header("Content-Type", "text/plain");
  1577. auto ret = detail::encoding_type(req, res);
  1578. EXPECT_TRUE(ret == detail::EncodingType::None);
  1579. }
  1580. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1581. // RFC 7231: Accept-Encoding values are case-insensitive
  1582. Request req;
  1583. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1584. Response res;
  1585. res.set_header("Content-Type", "text/plain");
  1586. auto ret = detail::encoding_type(req, res);
  1587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1588. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1589. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1590. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1591. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1592. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1593. #else
  1594. EXPECT_TRUE(ret == detail::EncodingType::None);
  1595. #endif
  1596. }
  1597. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1598. // q value should determine priority, not hardcoded order
  1599. Request req;
  1600. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1601. Response res;
  1602. res.set_header("Content-Type", "text/plain");
  1603. auto ret = detail::encoding_type(req, res);
  1604. // gzip has highest q=1.0, so it should be selected even though
  1605. // br and zstd are also supported
  1606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1607. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1608. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1609. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1610. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1611. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1612. #else
  1613. EXPECT_TRUE(ret == detail::EncodingType::None);
  1614. #endif
  1615. }
  1616. TEST(BufferStreamTest, read) {
  1617. detail::BufferStream strm1;
  1618. Stream &strm = strm1;
  1619. EXPECT_EQ(5, strm.write("hello"));
  1620. char buf[512];
  1621. EXPECT_EQ(2, strm.read(buf, 2));
  1622. EXPECT_EQ('h', buf[0]);
  1623. EXPECT_EQ('e', buf[1]);
  1624. EXPECT_EQ(2, strm.read(buf, 2));
  1625. EXPECT_EQ('l', buf[0]);
  1626. EXPECT_EQ('l', buf[1]);
  1627. EXPECT_EQ(1, strm.read(buf, 1));
  1628. EXPECT_EQ('o', buf[0]);
  1629. EXPECT_EQ(0, strm.read(buf, 1));
  1630. }
  1631. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1632. auto host = "www.httpwatch.com";
  1633. auto ip = hosted_at(host);
  1634. EXPECT_EQ("23.96.13.243", ip);
  1635. std::vector<std::string> addrs;
  1636. hosted_at(host, addrs);
  1637. EXPECT_EQ(1u, addrs.size());
  1638. }
  1639. #if 0 // It depends on each test environment...
  1640. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1641. auto host = "www.youtube.com";
  1642. std::vector<std::string> addrs;
  1643. hosted_at(host, addrs);
  1644. EXPECT_EQ(20u, addrs.size());
  1645. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1646. EXPECT_TRUE(it != addrs.end());
  1647. }
  1648. #endif
  1649. class ChunkedEncodingTest : public ::testing::Test {
  1650. protected:
  1651. ChunkedEncodingTest()
  1652. : cli_(HOST, PORT)
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. ,
  1655. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1656. #endif
  1657. {
  1658. cli_.set_connection_timeout(2);
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. cli_.enable_server_certificate_verification(false);
  1661. #endif
  1662. }
  1663. virtual void SetUp() {
  1664. read_file("./image.jpg", image_data_);
  1665. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1666. res.set_content("Hello World!", "text/plain");
  1667. });
  1668. svr_.Get(
  1669. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1670. res.set_chunked_content_provider(
  1671. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1672. size_t remaining = image_data_.size() - offset;
  1673. if (remaining == 0) {
  1674. sink.done();
  1675. } else {
  1676. constexpr size_t CHUNK_SIZE = 1024;
  1677. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1678. sink.write(&image_data_[offset], send_size);
  1679. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1680. }
  1681. return true;
  1682. });
  1683. });
  1684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1685. svr_.wait_until_ready();
  1686. }
  1687. virtual void TearDown() {
  1688. svr_.stop();
  1689. if (!request_threads_.empty()) {
  1690. std::this_thread::sleep_for(std::chrono::seconds(1));
  1691. for (auto &t : request_threads_) {
  1692. t.join();
  1693. }
  1694. }
  1695. t_.join();
  1696. }
  1697. #ifdef CPPHTTPLIB_SSL_ENABLED
  1698. SSLClient cli_;
  1699. SSLServer svr_;
  1700. #else
  1701. Client cli_;
  1702. Server svr_;
  1703. #endif
  1704. thread t_;
  1705. std::vector<thread> request_threads_;
  1706. std::string image_data_;
  1707. };
  1708. TEST_F(ChunkedEncodingTest, NormalGet) {
  1709. auto res = cli_.Get("/chunked");
  1710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1711. std::string out;
  1712. read_file("./image.jpg", out);
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ(out, res->body);
  1715. }
  1716. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1717. std::string body;
  1718. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1729. std::string body;
  1730. auto res = cli_.Get(
  1731. "/chunked",
  1732. [&](const Response &response) {
  1733. EXPECT_EQ(StatusCode::OK_200, response.status);
  1734. return true;
  1735. },
  1736. [&](const char *data, size_t data_length) {
  1737. body.append(data, data_length);
  1738. return true;
  1739. });
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. std::string out;
  1742. read_file("./image.jpg", out);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. EXPECT_EQ(out, body);
  1745. }
  1746. TEST(RangeTest, FromHTTPBin_Online) {
  1747. auto host = "httpbingo.org";
  1748. auto path = std::string{"/range/32"};
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. auto port = 443;
  1751. SSLClient cli(host, port);
  1752. #else
  1753. auto port = 80;
  1754. Client cli(host, port);
  1755. #endif
  1756. cli.set_connection_timeout(5);
  1757. {
  1758. auto res = cli.Get(path);
  1759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1760. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto res = cli.Get(path, headers);
  1766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1767. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{1, 10}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("bcdefghijk", res->body);
  1775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1776. }
  1777. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1778. // entire resource, while the original httpbin returned 200. Both are
  1779. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1780. {
  1781. Headers headers = {make_range_header({{0, 31}})};
  1782. auto res = cli.Get(path, headers);
  1783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1784. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1785. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1786. res->status == StatusCode::PartialContent_206);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, -1}})};
  1790. auto res = cli.Get(path, headers);
  1791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1792. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1793. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1794. res->status == StatusCode::PartialContent_206);
  1795. }
  1796. // go-httpbin returns 206 with clamped range for over-range requests,
  1797. // while the original httpbin returned 416. Both behaviors are observed
  1798. // in real servers, so we only verify the request succeeds.
  1799. {
  1800. Headers headers = {make_range_header({{0, 32}})};
  1801. auto res = cli.Get(path, headers);
  1802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1803. }
  1804. }
  1805. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1806. auto host = "unresolvableaddress.local";
  1807. auto path = std::string{"/"};
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. auto port = 443;
  1810. SSLClient cli(host, port);
  1811. #else
  1812. auto port = 80;
  1813. Client cli(host, port);
  1814. #endif
  1815. cli.set_connection_timeout(1);
  1816. {
  1817. auto res = cli.Get(path);
  1818. ASSERT_FALSE(res);
  1819. }
  1820. std::this_thread::sleep_for(std::chrono::seconds(8));
  1821. }
  1822. #if defined(__linux__) && defined(__GLIBC__) && \
  1823. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1824. // Forward declaration: in split builds split.py strips `inline` and moves the
  1825. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1826. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1827. // against the symbol in both header-only and split builds.
  1828. namespace httplib {
  1829. namespace detail {
  1830. int getaddrinfo_with_timeout(const char *node, const char *service,
  1831. const struct addrinfo *hints,
  1832. struct addrinfo **res, time_t timeout_sec);
  1833. } // namespace detail
  1834. } // namespace httplib
  1835. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1836. //
  1837. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1838. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1839. // gai_suspend() call hits the connection timeout the function calls
  1840. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1841. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1842. // still alive and still references the now-destroyed stack frame.
  1843. //
  1844. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1845. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1846. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1847. // and runs them in a container.
  1848. namespace {
  1849. bool should_run_issue_2431_tests() {
  1850. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1851. return v && *v && std::string(v) != "0";
  1852. }
  1853. std::string unique_unresolvable_host(int n) {
  1854. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1855. // glibc still asks the configured nameserver — which is exactly the path
  1856. // we want to exercise. A unique label per call avoids the resolver cache.
  1857. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1858. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1859. std::to_string(n) + ".invalid";
  1860. }
  1861. } // namespace
  1862. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1863. if (!should_run_issue_2431_tests()) {
  1864. GTEST_SKIP()
  1865. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1866. }
  1867. for (int i = 0; i < 8; ++i) {
  1868. struct addrinfo hints;
  1869. memset(&hints, 0, sizeof(hints));
  1870. hints.ai_family = AF_UNSPEC;
  1871. hints.ai_socktype = SOCK_STREAM;
  1872. auto host = unique_unresolvable_host(i);
  1873. struct addrinfo *result = nullptr;
  1874. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1875. &result, /*timeout_sec=*/1);
  1876. if (rc == 0 && result) { freeaddrinfo(result); }
  1877. }
  1878. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1879. // stack region they still believe holds their gaicb.
  1880. std::this_thread::sleep_for(std::chrono::seconds(3));
  1881. }
  1882. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1883. if (!should_run_issue_2431_tests()) {
  1884. GTEST_SKIP()
  1885. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1886. }
  1887. std::atomic<bool> stop{false};
  1888. std::vector<std::thread> threads;
  1889. for (int t = 0; t < 8; ++t) {
  1890. threads.emplace_back([t, &stop] {
  1891. int i = 0;
  1892. while (!stop.load(std::memory_order_relaxed)) {
  1893. struct addrinfo hints;
  1894. memset(&hints, 0, sizeof(hints));
  1895. hints.ai_family = AF_UNSPEC;
  1896. hints.ai_socktype = SOCK_STREAM;
  1897. auto host = unique_unresolvable_host(t * 100000 + i++);
  1898. struct addrinfo *result = nullptr;
  1899. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1900. &result, /*timeout_sec=*/1);
  1901. if (rc == 0 && result) { freeaddrinfo(result); }
  1902. }
  1903. });
  1904. }
  1905. std::this_thread::sleep_for(std::chrono::seconds(8));
  1906. stop.store(true, std::memory_order_relaxed);
  1907. for (auto &th : threads) {
  1908. th.join();
  1909. }
  1910. std::this_thread::sleep_for(std::chrono::seconds(3));
  1911. }
  1912. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1913. if (!should_run_issue_2431_tests()) {
  1914. GTEST_SKIP()
  1915. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1916. }
  1917. std::atomic<bool> stop{false};
  1918. std::vector<std::thread> threads;
  1919. for (int t = 0; t < 8; ++t) {
  1920. threads.emplace_back([t, &stop] {
  1921. int i = 0;
  1922. while (!stop.load(std::memory_order_relaxed)) {
  1923. auto host = unique_unresolvable_host(t * 100000 + i++);
  1924. Client cli(host, 80);
  1925. cli.set_connection_timeout(1, 0);
  1926. cli.set_read_timeout(1, 0);
  1927. cli.set_write_timeout(1, 0);
  1928. (void)cli.Get("/");
  1929. }
  1930. });
  1931. }
  1932. std::this_thread::sleep_for(std::chrono::seconds(8));
  1933. stop.store(true, std::memory_order_relaxed);
  1934. for (auto &th : threads) {
  1935. th.join();
  1936. }
  1937. std::this_thread::sleep_for(std::chrono::seconds(3));
  1938. }
  1939. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1940. TEST(ConnectionErrorTest, InvalidHost) {
  1941. auto host = "-abcde.com";
  1942. #ifdef CPPHTTPLIB_SSL_ENABLED
  1943. auto port = 443;
  1944. SSLClient cli(host, port);
  1945. #else
  1946. auto port = 80;
  1947. Client cli(host, port);
  1948. #endif
  1949. cli.set_connection_timeout(std::chrono::seconds(2));
  1950. auto res = cli.Get("/");
  1951. ASSERT_TRUE(!res);
  1952. EXPECT_EQ(Error::Connection, res.error());
  1953. }
  1954. TEST(ConnectionErrorTest, InvalidHost2) {
  1955. auto host = "httpcan.org/";
  1956. #ifdef CPPHTTPLIB_SSL_ENABLED
  1957. SSLClient cli(host);
  1958. #else
  1959. Client cli(host);
  1960. #endif
  1961. cli.set_connection_timeout(std::chrono::seconds(2));
  1962. auto res = cli.Get("/");
  1963. ASSERT_TRUE(!res);
  1964. EXPECT_EQ(Error::Connection, res.error());
  1965. }
  1966. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1967. auto host = "httpcan.org/";
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. SSLClient cli(host);
  1970. #else
  1971. Client cli(host);
  1972. #endif
  1973. cli.set_connection_timeout(std::chrono::seconds(2));
  1974. auto res = cli.Get("/");
  1975. ASSERT_TRUE(!res);
  1976. stringstream s;
  1977. s << "error code: " << res.error();
  1978. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1979. }
  1980. TEST(ConnectionErrorTest, InvalidPort) {
  1981. auto host = "localhost";
  1982. auto port = 44380;
  1983. #ifdef CPPHTTPLIB_SSL_ENABLED
  1984. SSLClient cli(host, port);
  1985. #else
  1986. Client cli(host, port);
  1987. #endif
  1988. cli.set_connection_timeout(std::chrono::seconds(2));
  1989. auto res = cli.Get("/");
  1990. ASSERT_TRUE(!res);
  1991. EXPECT_TRUE(Error::Connection == res.error() ||
  1992. Error::ConnectionTimeout == res.error());
  1993. }
  1994. TEST(ConnectionErrorTest, Timeout_Online) {
  1995. auto host = "google.com";
  1996. #ifdef CPPHTTPLIB_SSL_ENABLED
  1997. auto port = 44380;
  1998. SSLClient cli(host, port);
  1999. #else
  2000. auto port = 8080;
  2001. Client cli(host, port);
  2002. #endif
  2003. cli.set_connection_timeout(std::chrono::seconds(2));
  2004. // only probe one address type so that the error reason
  2005. // correlates to the timed-out IPv4, not the unsupported
  2006. // IPv6 connection attempt
  2007. cli.set_address_family(AF_INET);
  2008. auto res = cli.Get("/");
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2011. }
  2012. TEST(CancelTest, NoCancel_Online) {
  2013. auto host = "httpbingo.org";
  2014. auto path = std::string{"/range/32"};
  2015. #ifdef CPPHTTPLIB_SSL_ENABLED
  2016. auto port = 443;
  2017. SSLClient cli(host, port);
  2018. #else
  2019. auto port = 80;
  2020. Client cli(host, port);
  2021. #endif
  2022. cli.set_connection_timeout(std::chrono::seconds(5));
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2025. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2029. // Use /bytes with a large payload so that the DownloadProgress callback
  2030. // (which only fires for Content-Length responses) is invoked before the
  2031. // entire body is received, giving cancellation a chance to fire.
  2032. auto host = "httpbingo.org";
  2033. auto path = std::string{"/bytes/524288"};
  2034. #ifdef CPPHTTPLIB_SSL_ENABLED
  2035. auto port = 443;
  2036. SSLClient cli(host, port);
  2037. #else
  2038. auto port = 80;
  2039. Client cli(host, port);
  2040. #endif
  2041. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2042. cli.set_connection_timeout(std::chrono::seconds(5));
  2043. ASSERT_TRUE(!res);
  2044. EXPECT_EQ(Error::Canceled, res.error());
  2045. }
  2046. TEST(CancelTest, WithCancelLargePayload_Online) {
  2047. auto host = "httpbingo.org";
  2048. auto path = std::string{"/bytes/524288"};
  2049. #ifdef CPPHTTPLIB_SSL_ENABLED
  2050. auto port = 443;
  2051. SSLClient cli(host, port);
  2052. #else
  2053. auto port = 80;
  2054. Client cli(host, port);
  2055. #endif
  2056. cli.set_connection_timeout(std::chrono::seconds(5));
  2057. uint32_t count = 0;
  2058. auto res =
  2059. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2060. ASSERT_TRUE(!res);
  2061. EXPECT_EQ(Error::Canceled, res.error());
  2062. }
  2063. TEST(CancelTest, NoCancelPost) {
  2064. Server svr;
  2065. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2066. res.set_content("Hello World!", "text/plain");
  2067. });
  2068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2069. auto se = detail::scope_exit([&] {
  2070. svr.stop();
  2071. thread.join();
  2072. ASSERT_FALSE(svr.is_running());
  2073. });
  2074. svr.wait_until_ready();
  2075. Client cli(HOST, PORT);
  2076. cli.set_connection_timeout(std::chrono::seconds(5));
  2077. auto res =
  2078. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2079. "application/json", [](uint64_t, uint64_t) { return true; });
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. EXPECT_EQ("Hello World!", res->body);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2085. Server svr;
  2086. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2087. res.set_content("Hello World!", "text/plain");
  2088. });
  2089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2090. auto se = detail::scope_exit([&] {
  2091. svr.stop();
  2092. thread.join();
  2093. ASSERT_FALSE(svr.is_running());
  2094. });
  2095. svr.wait_until_ready();
  2096. Client cli(HOST, PORT);
  2097. cli.set_connection_timeout(std::chrono::seconds(5));
  2098. auto res =
  2099. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2100. "application/json", [](uint64_t, uint64_t) { return false; });
  2101. ASSERT_TRUE(!res);
  2102. EXPECT_EQ(Error::Canceled, res.error());
  2103. }
  2104. TEST(CancelTest, WithCancelLargePayloadPost) {
  2105. Server svr;
  2106. svr.set_payload_max_length(200 * 1024 * 1024);
  2107. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2108. res.set_content(LARGE_DATA, "text/plain");
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. Client cli(HOST, PORT);
  2118. cli.set_payload_max_length(200 * 1024 * 1024);
  2119. cli.set_connection_timeout(std::chrono::seconds(5));
  2120. auto res =
  2121. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2122. "application/json", [](uint64_t, uint64_t) { return false; });
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Canceled, res.error());
  2125. }
  2126. TEST(CancelTest, NoCancelPut) {
  2127. Server svr;
  2128. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!", "text/plain");
  2130. });
  2131. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. thread.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. Client cli(HOST, PORT);
  2139. cli.set_connection_timeout(std::chrono::seconds(5));
  2140. auto res =
  2141. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2142. "application/json", [](uint64_t, uint64_t) { return true; });
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("Hello World!", res->body);
  2145. EXPECT_EQ(StatusCode::OK_200, res->status);
  2146. }
  2147. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2148. Server svr;
  2149. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2153. auto se = detail::scope_exit([&] {
  2154. svr.stop();
  2155. thread.join();
  2156. ASSERT_FALSE(svr.is_running());
  2157. });
  2158. svr.wait_until_ready();
  2159. Client cli(HOST, PORT);
  2160. cli.set_connection_timeout(std::chrono::seconds(5));
  2161. auto res =
  2162. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2163. "application/json", [](uint64_t, uint64_t) { return false; });
  2164. ASSERT_TRUE(!res);
  2165. EXPECT_EQ(Error::Canceled, res.error());
  2166. }
  2167. TEST(CancelTest, WithCancelLargePayloadPut) {
  2168. Server svr;
  2169. svr.set_payload_max_length(200 * 1024 * 1024);
  2170. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2171. res.set_content(LARGE_DATA, "text/plain");
  2172. });
  2173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2174. auto se = detail::scope_exit([&] {
  2175. svr.stop();
  2176. thread.join();
  2177. ASSERT_FALSE(svr.is_running());
  2178. });
  2179. svr.wait_until_ready();
  2180. Client cli(HOST, PORT);
  2181. cli.set_payload_max_length(200 * 1024 * 1024);
  2182. cli.set_connection_timeout(std::chrono::seconds(5));
  2183. auto res =
  2184. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2185. "application/json", [](uint64_t, uint64_t) { return false; });
  2186. ASSERT_TRUE(!res);
  2187. EXPECT_EQ(Error::Canceled, res.error());
  2188. }
  2189. TEST(CancelTest, NoCancelPatch) {
  2190. Server svr;
  2191. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2192. res.set_content("Hello World!", "text/plain");
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli(HOST, PORT);
  2202. cli.set_connection_timeout(std::chrono::seconds(5));
  2203. auto res =
  2204. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2205. "application/json", [](uint64_t, uint64_t) { return true; });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. EXPECT_EQ("Hello World!", res->body);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. }
  2210. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2211. Server svr;
  2212. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2213. res.set_content("Hello World!", "text/plain");
  2214. });
  2215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. thread.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. svr.wait_until_ready();
  2222. Client cli(HOST, PORT);
  2223. cli.set_connection_timeout(std::chrono::seconds(5));
  2224. auto res =
  2225. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2226. "application/json", [](uint64_t, uint64_t) { return false; });
  2227. ASSERT_TRUE(!res);
  2228. EXPECT_EQ(Error::Canceled, res.error());
  2229. }
  2230. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2231. Server svr;
  2232. svr.set_payload_max_length(200 * 1024 * 1024);
  2233. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2234. res.set_content(LARGE_DATA, "text/plain");
  2235. });
  2236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2237. auto se = detail::scope_exit([&] {
  2238. svr.stop();
  2239. thread.join();
  2240. ASSERT_FALSE(svr.is_running());
  2241. });
  2242. svr.wait_until_ready();
  2243. Client cli(HOST, PORT);
  2244. cli.set_payload_max_length(200 * 1024 * 1024);
  2245. cli.set_connection_timeout(std::chrono::seconds(5));
  2246. auto res =
  2247. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2248. "application/json", [](uint64_t, uint64_t) { return false; });
  2249. ASSERT_TRUE(!res);
  2250. EXPECT_EQ(Error::Canceled, res.error());
  2251. }
  2252. TEST(CancelTest, NoCancelDelete) {
  2253. Server svr;
  2254. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2255. res.set_content("Hello World!", "text/plain");
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. auto res =
  2267. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2268. "application/json", [](uint64_t, uint64_t) { return true; });
  2269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2270. EXPECT_EQ("Hello World!", res->body);
  2271. EXPECT_EQ(StatusCode::OK_200, res->status);
  2272. }
  2273. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2274. Server svr;
  2275. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2276. res.set_content("Hello World!", "text/plain");
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. Client cli(HOST, PORT);
  2286. cli.set_connection_timeout(std::chrono::seconds(5));
  2287. auto res =
  2288. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2289. "application/json", [](uint64_t, uint64_t) { return false; });
  2290. ASSERT_TRUE(!res);
  2291. EXPECT_EQ(Error::Canceled, res.error());
  2292. }
  2293. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2294. Server svr;
  2295. svr.set_payload_max_length(200 * 1024 * 1024);
  2296. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2297. res.set_content(LARGE_DATA, "text/plain");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. Client cli(HOST, PORT);
  2307. cli.set_payload_max_length(200 * 1024 * 1024);
  2308. cli.set_connection_timeout(std::chrono::seconds(5));
  2309. auto res =
  2310. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2311. "application/json", [](uint64_t, uint64_t) { return false; });
  2312. ASSERT_TRUE(!res);
  2313. EXPECT_EQ(Error::Canceled, res.error());
  2314. }
  2315. static std::string remove_whitespace(const std::string &input) {
  2316. std::string output;
  2317. output.reserve(input.size());
  2318. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2319. [](unsigned char c) { return !std::isspace(c); });
  2320. return output;
  2321. }
  2322. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2323. auto host = "httpbingo.org";
  2324. auto path = std::string{"/basic-auth/hello/world"};
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. auto port = 443;
  2327. SSLClient cli(host, port);
  2328. #else
  2329. auto port = 80;
  2330. Client cli(host, port);
  2331. #endif
  2332. {
  2333. auto res = cli.Get(path);
  2334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2336. }
  2337. {
  2338. auto res = cli.Get(
  2339. path, Headers{make_basic_authentication_header("hello", "world")});
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. auto body = remove_whitespace(res->body);
  2342. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2343. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2344. EXPECT_EQ(StatusCode::OK_200, res->status);
  2345. }
  2346. {
  2347. cli.set_basic_auth("hello", "world");
  2348. auto res = cli.Get(path);
  2349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2350. auto body = remove_whitespace(res->body);
  2351. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2352. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. }
  2355. {
  2356. cli.set_basic_auth("hello", "bad");
  2357. auto res = cli.Get(path);
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2360. }
  2361. {
  2362. cli.set_basic_auth("bad", "world");
  2363. auto res = cli.Get(path);
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2366. }
  2367. }
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2370. auto host = "httpbingo.org";
  2371. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2372. auto paths = std::vector<std::string>{
  2373. "/digest-auth/auth/hello/world/MD5",
  2374. "/digest-auth/auth/hello/world/SHA-256",
  2375. };
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. {
  2379. auto res = cli.Get(unauth_path);
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2382. }
  2383. {
  2384. cli.set_digest_auth("hello", "world");
  2385. for (const auto &path : paths) {
  2386. auto res = cli.Get(path.c_str());
  2387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2388. auto body = remove_whitespace(res->body);
  2389. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2390. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. }
  2393. cli.set_digest_auth("hello", "bad");
  2394. for (const auto &path : paths) {
  2395. auto res = cli.Get(path.c_str());
  2396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2397. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2398. }
  2399. }
  2400. }
  2401. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2402. // comma-separated list of challenges, and each challenge may itself carry a
  2403. // comma-separated auth-param list, so a server can legally offer Basic
  2404. // before Digest, either as two field lines or packed into one. Runs one 401
  2405. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2406. // value() joins them in receipt order) and checks that the retry carries a
  2407. // well-formed Digest Authorization header naming expected_realm.
  2408. static void
  2409. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2410. const std::string &expected_realm) {
  2411. std::atomic<int> hits{0};
  2412. Server svr;
  2413. svr.Get("/x", [&](const Request &req, Response &res) {
  2414. if (++hits == 1) {
  2415. res.status = StatusCode::Unauthorized_401;
  2416. for (const auto &challenge : challenges) {
  2417. res.set_header("WWW-Authenticate", challenge);
  2418. }
  2419. } else {
  2420. auto authorization = req.get_header_value("Authorization");
  2421. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2422. EXPECT_NE(std::string::npos,
  2423. authorization.find("realm=\"" + expected_realm + "\""));
  2424. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2425. res.set_content("ok", "text/plain");
  2426. }
  2427. });
  2428. auto port = svr.bind_to_any_port(HOST);
  2429. std::thread t([&]() { svr.listen_after_bind(); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. t.join();
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, port);
  2436. cli.set_digest_auth("hello", "world");
  2437. auto res = cli.Get("/x");
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. EXPECT_EQ(2, hits.load());
  2440. }
  2441. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2442. static const char *kDigestChallenge =
  2443. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2444. "algorithm=MD5";
  2445. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2446. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2447. "testrealm");
  2448. }
  2449. // Same challenge list with the schemes in the opposite order, to make sure
  2450. // the fix above didn't just special-case "Basic first".
  2451. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2452. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2453. "testrealm");
  2454. }
  2455. // A comma inside a quoted auth-param value must not be mistaken for the
  2456. // separator between two challenges (or two auth-params).
  2457. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2458. run_digest_challenge_list_test(
  2459. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2460. "algorithm=MD5"},
  2461. "test,realm");
  2462. }
  2463. #endif
  2464. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2465. auto host = "google.com";
  2466. auto another_host = "example.com";
  2467. auto wrong_ip = "0.0.0.0";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2477. }
  2478. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2479. auto host = "google.com";
  2480. auto wrong_ip = "0.0.0.0";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_hostname_addr_map({{host, wrong_ip}});
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2492. // A mapped value that is not an IP literal must be resolved. "localhost"
  2493. // resolves from the hosts file, so this test needs no external DNS.
  2494. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2495. auto host = "target.invalid";
  2496. Server svr;
  2497. std::string received_host;
  2498. svr.Get("/hi", [&](const Request &req, Response &res) {
  2499. received_host = req.get_header_value("Host");
  2500. res.set_content("Hello World!", "text/plain");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(host, port);
  2511. cli.set_hostname_addr_map({{host, HOST}});
  2512. auto res = cli.Get("/hi");
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. // The mapping only redirects the connection; the identity stays host_.
  2516. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2517. }
  2518. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2519. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2520. auto host = "target.invalid";
  2521. Server svr;
  2522. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto port = svr.bind_to_any_port("127.0.0.1");
  2526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(host, port);
  2534. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2540. // An empty mapped value must leave host_ as the connection target. Without
  2541. // that guard the empty value would become the host argument, getaddrinfo
  2542. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2543. // loopback - silently connecting somewhere the caller never asked for.
  2544. // The server listens on loopback, so such a fallback would succeed and is
  2545. // therefore observable as a failure of this test.
  2546. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2547. Server svr;
  2548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2549. res.set_content("Hello World!", "text/plain");
  2550. });
  2551. auto port = svr.bind_to_any_port(HOST);
  2552. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(blackhole, port);
  2560. cli.set_hostname_addr_map({{blackhole, ""}});
  2561. cli.set_connection_timeout(1);
  2562. auto res = cli.Get("/hi");
  2563. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2564. }
  2565. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/absolute-redirect/3"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. SSLClient cli(host);
  2570. #else
  2571. Client cli(host);
  2572. #endif
  2573. cli.set_follow_location(true);
  2574. auto res = cli.Get(path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. }
  2578. TEST(RedirectTest, Redirect_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/redirect/3"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. SSLClient cli(host);
  2583. #else
  2584. Client cli(host);
  2585. #endif
  2586. cli.set_follow_location(true);
  2587. auto res = cli.Get(path);
  2588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. }
  2591. TEST(RelativeRedirectTest, Redirect_Online) {
  2592. auto host = "httpbingo.org";
  2593. auto path = std::string{"/relative-redirect/3"};
  2594. #ifdef CPPHTTPLIB_SSL_ENABLED
  2595. SSLClient cli(host);
  2596. #else
  2597. Client cli(host);
  2598. #endif
  2599. cli.set_follow_location(true);
  2600. auto res = cli.Get(path);
  2601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2602. EXPECT_EQ(StatusCode::OK_200, res->status);
  2603. }
  2604. TEST(TooManyRedirectTest, Redirect_Online) {
  2605. auto host = "httpbingo.org";
  2606. auto path = std::string{"/redirect/21"};
  2607. #ifdef CPPHTTPLIB_SSL_ENABLED
  2608. SSLClient cli(host);
  2609. #else
  2610. Client cli(host);
  2611. #endif
  2612. cli.set_follow_location(true);
  2613. auto res = cli.Get(path);
  2614. ASSERT_TRUE(!res);
  2615. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2616. }
  2617. #ifdef CPPHTTPLIB_SSL_ENABLED
  2618. TEST(YahooRedirectTest, Redirect_Online) {
  2619. Client cli("yahoo.com");
  2620. auto res = cli.Get("/");
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2623. cli.set_follow_location(true);
  2624. res = cli.Get("/");
  2625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2628. }
  2629. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2630. #define REDIR_HOST "httpbingo.org"
  2631. #define REDIR_PATH "/redirect-to"
  2632. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2633. SSLClient cli(REDIR_HOST);
  2634. cli.set_follow_location(true);
  2635. auto res =
  2636. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::OK_200, res->status);
  2639. }
  2640. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2641. SSLClient cli(REDIR_HOST);
  2642. cli.set_follow_location(true);
  2643. Params params;
  2644. params.emplace("url", "http://example.com");
  2645. params.emplace("status_code", "302");
  2646. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. }
  2650. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2651. SSLClient cli(REDIR_HOST);
  2652. cli.set_follow_location(true);
  2653. Params params;
  2654. params.emplace("url", "http://example.com");
  2655. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(UrlWithSpace, Redirect_Online) {
  2660. SSLClient cli("edge.forgecdn.net");
  2661. cli.set_follow_location(true);
  2662. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2666. }
  2667. #endif
  2668. #if !defined(_WIN32) && !defined(_WIN64)
  2669. TEST(ReceiveSignals, Signal) {
  2670. auto setupSignalHandlers = []() {
  2671. struct sigaction act;
  2672. sigemptyset(&act.sa_mask);
  2673. act.sa_flags = SA_SIGINFO;
  2674. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2675. switch (sig) {
  2676. case SIGINT:
  2677. default: break;
  2678. }
  2679. };
  2680. ::sigaction(SIGINT, &act, nullptr);
  2681. };
  2682. Server svr;
  2683. int port = 0;
  2684. auto thread = std::thread([&]() {
  2685. setupSignalHandlers();
  2686. port = svr.bind_to_any_port(HOST);
  2687. svr.listen_after_bind();
  2688. });
  2689. auto se = detail::scope_exit([&] {
  2690. svr.stop();
  2691. thread.join();
  2692. ASSERT_FALSE(svr.is_running());
  2693. });
  2694. svr.wait_until_ready();
  2695. ASSERT_TRUE(svr.is_running());
  2696. pthread_kill(thread.native_handle(), SIGINT);
  2697. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2698. ASSERT_TRUE(svr.is_running());
  2699. }
  2700. #endif
  2701. TEST(RedirectToDifferentPort, Redirect) {
  2702. Server svr1;
  2703. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. int svr1_port = 0;
  2707. auto thread1 = std::thread([&]() {
  2708. svr1_port = svr1.bind_to_any_port(HOST);
  2709. svr1.listen_after_bind();
  2710. });
  2711. Server svr2;
  2712. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2713. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2714. });
  2715. int svr2_port = 0;
  2716. auto thread2 = std::thread([&]() {
  2717. svr2_port = svr2.bind_to_any_port(HOST);
  2718. svr2.listen_after_bind();
  2719. });
  2720. auto se = detail::scope_exit([&] {
  2721. svr2.stop();
  2722. thread2.join();
  2723. svr1.stop();
  2724. thread1.join();
  2725. ASSERT_FALSE(svr2.is_running());
  2726. ASSERT_FALSE(svr1.is_running());
  2727. });
  2728. svr1.wait_until_ready();
  2729. svr2.wait_until_ready();
  2730. Client cli("localhost", svr2_port);
  2731. cli.set_follow_location(true);
  2732. auto res = cli.Get("/2");
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("Hello World!", res->body);
  2736. }
  2737. static void
  2738. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2739. Server svr1;
  2740. std::string captured_authorization;
  2741. svr1.Get("/target", [&](const Request &req, Response &res) {
  2742. captured_authorization = req.get_header_value("Authorization");
  2743. res.set_content("OK", "text/plain");
  2744. });
  2745. int svr1_port = 0;
  2746. auto thread1 = std::thread([&]() {
  2747. svr1_port = svr1.bind_to_any_port(HOST);
  2748. svr1.listen_after_bind();
  2749. });
  2750. Server svr2;
  2751. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2752. res.set_redirect(
  2753. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2754. });
  2755. int svr2_port = 0;
  2756. auto thread2 = std::thread([&]() {
  2757. svr2_port = svr2.bind_to_any_port(HOST);
  2758. svr2.listen_after_bind();
  2759. });
  2760. auto se = detail::scope_exit([&] {
  2761. svr2.stop();
  2762. thread2.join();
  2763. svr1.stop();
  2764. thread1.join();
  2765. ASSERT_FALSE(svr2.is_running());
  2766. ASSERT_FALSE(svr1.is_running());
  2767. });
  2768. svr1.wait_until_ready();
  2769. svr2.wait_until_ready();
  2770. Client cli("localhost", svr2_port);
  2771. cli.set_follow_location(true);
  2772. set_auth(cli);
  2773. auto res = cli.Get("/redir");
  2774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2775. EXPECT_EQ(StatusCode::OK_200, res->status);
  2776. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2777. EXPECT_TRUE(captured_authorization.empty());
  2778. }
  2779. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2780. TestDoNotForwardCredentialsOnRedirect(
  2781. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2782. }
  2783. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2784. TestDoNotForwardCredentialsOnRedirect(
  2785. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2786. }
  2787. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2788. Server svr1;
  2789. std::string captured_cookie;
  2790. bool target_hit = false;
  2791. svr1.Get("/target", [&](const Request &req, Response &res) {
  2792. captured_cookie = req.get_header_value("Cookie");
  2793. target_hit = true;
  2794. res.set_content("OK", "text/plain");
  2795. });
  2796. int svr1_port = 0;
  2797. auto thread1 = std::thread([&]() {
  2798. svr1_port = svr1.bind_to_any_port(HOST);
  2799. svr1.listen_after_bind();
  2800. });
  2801. Server svr2;
  2802. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2803. res.set_redirect(
  2804. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2805. });
  2806. int svr2_port = 0;
  2807. auto thread2 = std::thread([&]() {
  2808. svr2_port = svr2.bind_to_any_port(HOST);
  2809. svr2.listen_after_bind();
  2810. });
  2811. auto se = detail::scope_exit([&] {
  2812. svr2.stop();
  2813. thread2.join();
  2814. svr1.stop();
  2815. thread1.join();
  2816. ASSERT_FALSE(svr2.is_running());
  2817. ASSERT_FALSE(svr1.is_running());
  2818. });
  2819. svr1.wait_until_ready();
  2820. svr2.wait_until_ready();
  2821. Client cli("localhost", svr2_port);
  2822. cli.set_follow_location(true);
  2823. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2824. auto res = cli.Get("/redir", headers);
  2825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2826. EXPECT_EQ(StatusCode::OK_200, res->status);
  2827. EXPECT_TRUE(target_hit);
  2828. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2829. EXPECT_TRUE(captured_cookie.empty());
  2830. }
  2831. TEST(RedirectToSamePort, ForwardCookie) {
  2832. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2833. // header so that ordinary session flows keep working.
  2834. Server svr;
  2835. std::string captured_cookie;
  2836. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2837. res.set_redirect("/target", 302);
  2838. });
  2839. svr.Get("/target", [&](const Request &req, Response &res) {
  2840. captured_cookie = req.get_header_value("Cookie");
  2841. res.set_content("OK", "text/plain");
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, port);
  2852. cli.set_follow_location(true);
  2853. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2854. auto res = cli.Get("/redir", headers);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2858. }
  2859. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2860. Server svr;
  2861. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2862. // Port number that overflows int — should not crash
  2863. res.set_redirect("http://localhost:99999999999999999999/target");
  2864. });
  2865. auto port = svr.bind_to_any_port(HOST);
  2866. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2867. auto se = detail::scope_exit([&] {
  2868. svr.stop();
  2869. thread.join();
  2870. ASSERT_FALSE(svr.is_running());
  2871. });
  2872. svr.wait_until_ready();
  2873. Client cli(HOST, port);
  2874. cli.set_follow_location(true);
  2875. auto res = cli.Get("/redir");
  2876. // Should fail gracefully, not crash (no valid response due to bad port)
  2877. EXPECT_FALSE(res);
  2878. }
  2879. TEST(RedirectFromPageWithContent, Redirect) {
  2880. Server svr;
  2881. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("___", "text/plain");
  2883. res.set_redirect("/2");
  2884. });
  2885. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. th.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. {
  2896. Client cli("localhost", PORT);
  2897. cli.set_follow_location(true);
  2898. std::string body;
  2899. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2900. body.append(data, data_length);
  2901. return true;
  2902. });
  2903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2904. EXPECT_EQ(StatusCode::OK_200, res->status);
  2905. EXPECT_EQ("Hello World!", body);
  2906. }
  2907. {
  2908. Client cli("localhost", PORT);
  2909. std::string body;
  2910. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2911. body.append(data, data_length);
  2912. return true;
  2913. });
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Found_302, res->status);
  2916. EXPECT_EQ("___", body);
  2917. }
  2918. }
  2919. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2920. Server svr;
  2921. auto port_str = std::to_string(PORT);
  2922. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2923. auto expected_host = "[::1]:" + port_str;
  2924. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("___", "text/plain");
  2926. // res.set_redirect("/2");
  2927. res.set_redirect(redirect_url);
  2928. });
  2929. svr.Get("/2", [&](const Request &req, Response &res) {
  2930. auto host_header = req.headers.find("Host");
  2931. ASSERT_TRUE(host_header != req.headers.end());
  2932. EXPECT_EQ(expected_host, host_header->second);
  2933. res.set_content("Hello World!", "text/plain");
  2934. });
  2935. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2936. auto se = detail::scope_exit([&] {
  2937. svr.stop();
  2938. th.join();
  2939. ASSERT_FALSE(svr.is_running());
  2940. });
  2941. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2942. // actually starts anything, so the condition !svr.is_running() will
  2943. // always remain true, and the loop never stops.
  2944. // This basically counts how many milliseconds have passed since the
  2945. // call to svr.listen(), and if after 5 seconds nothing started yet
  2946. // aborts the test.
  2947. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2949. ASSERT_LT(milliseconds, 5000U);
  2950. }
  2951. {
  2952. Client cli("::1", PORT);
  2953. cli.set_follow_location(true);
  2954. std::string body;
  2955. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2956. body.append(data, data_length);
  2957. return true;
  2958. });
  2959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("Hello World!", body);
  2962. }
  2963. {
  2964. Client cli("::1", PORT);
  2965. std::string body;
  2966. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2971. EXPECT_EQ(StatusCode::Found_302, res->status);
  2972. EXPECT_EQ("___", body);
  2973. }
  2974. }
  2975. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2976. Server svr;
  2977. svr.Get("/foo", [](const Request &req, Response &res) {
  2978. auto a = req.params.find("a");
  2979. if (a != req.params.end()) {
  2980. res.set_content((*a).second, "text/plain");
  2981. res.status = StatusCode::OK_200;
  2982. } else {
  2983. res.status = StatusCode::BadRequest_400;
  2984. }
  2985. });
  2986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2987. auto se = detail::scope_exit([&] {
  2988. svr.stop();
  2989. thread.join();
  2990. ASSERT_FALSE(svr.is_running());
  2991. });
  2992. svr.wait_until_ready();
  2993. {
  2994. Client cli(HOST, PORT);
  2995. cli.set_path_encode(false);
  2996. auto res = cli.Get("/foo?a=explicitly+encoded");
  2997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2998. EXPECT_EQ(StatusCode::OK_200, res->status);
  2999. // This expects it back with a space, as the `+` won't have been
  3000. // url-encoded, and server-side the params get decoded turning `+`
  3001. // into spaces.
  3002. EXPECT_EQ("explicitly encoded", res->body);
  3003. }
  3004. }
  3005. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3006. // When path encoding is disabled the client must transmit the supplied
  3007. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3008. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3009. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3010. // than a space (0x20). Assert on the raw wire target to catch this.
  3011. Server svr;
  3012. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3013. svr.Get("/foo", [&](const Request &req, Response &res) {
  3014. EXPECT_EQ(expected_target, req.target);
  3015. res.status = StatusCode::OK_200;
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. {
  3025. Client cli(HOST, PORT);
  3026. cli.set_path_encode(false);
  3027. auto res = cli.Get(expected_target.c_str());
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3033. // `open_stream()` used to skip the path encoding that the buffered send
  3034. // path applies, so the same `path` produced different bytes in the request
  3035. // line depending on which API was used. Assert the two agree.
  3036. Server svr;
  3037. std::string target;
  3038. svr.Get(".*", [&](const Request &req, Response &res) {
  3039. target = req.target;
  3040. res.status = StatusCode::OK_200;
  3041. });
  3042. auto port = svr.bind_to_any_port(HOST);
  3043. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3044. auto se = detail::scope_exit([&] {
  3045. svr.stop();
  3046. thread.join();
  3047. ASSERT_FALSE(svr.is_running());
  3048. });
  3049. svr.wait_until_ready();
  3050. struct {
  3051. const char *path;
  3052. const char *expected;
  3053. } cases[] = {
  3054. {"/a b?x=1", "/a%20b?x=1"},
  3055. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3056. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3057. };
  3058. for (const auto &c : cases) {
  3059. Client cli(HOST, port);
  3060. target.clear();
  3061. auto res = cli.Get(c.path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3064. auto buffered_target = target;
  3065. target.clear();
  3066. auto handle = cli.open_stream("GET", c.path);
  3067. EXPECT_TRUE(handle.is_valid())
  3068. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3069. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3070. }
  3071. }
  3072. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3073. // The `set_path_encode(false)` contract — transmit the supplied target
  3074. // verbatim — must hold for the streaming API too.
  3075. Server svr;
  3076. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3077. std::string target;
  3078. svr.Get("/foo", [&](const Request &req, Response &res) {
  3079. target = req.target;
  3080. res.status = StatusCode::OK_200;
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. thread.join();
  3087. ASSERT_FALSE(svr.is_running());
  3088. });
  3089. svr.wait_until_ready();
  3090. {
  3091. Client cli(HOST, port);
  3092. cli.set_path_encode(false);
  3093. auto handle = cli.open_stream("GET", expected_target);
  3094. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3095. EXPECT_EQ(expected_target, target);
  3096. }
  3097. }
  3098. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3099. // With path encoding enabled a CR/LF in the target is percent-encoded
  3100. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3101. // write_request_line still backstops `set_path_encode(false)`, which is
  3102. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3103. Server svr;
  3104. // Captured before routing: the decoded path contains a newline, which a
  3105. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3106. std::string target;
  3107. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3108. target = req.target;
  3109. res.status = StatusCode::OK_200;
  3110. return Server::HandlerResponse::Handled;
  3111. });
  3112. auto port = svr.bind_to_any_port(HOST);
  3113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3114. auto se = detail::scope_exit([&] {
  3115. svr.stop();
  3116. thread.join();
  3117. ASSERT_FALSE(svr.is_running());
  3118. });
  3119. svr.wait_until_ready();
  3120. {
  3121. Client cli(HOST, port);
  3122. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3123. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3124. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3125. }
  3126. }
  3127. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3128. // Nothing may reach the wire: a raw CR/LF target would split the request
  3129. // line and inject headers.
  3130. Server svr;
  3131. // Pre-routing so that "not called" means nothing reached the server at all,
  3132. // rather than merely failing to match a handler pattern.
  3133. auto handler_called = false;
  3134. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3135. handler_called = true;
  3136. res.status = StatusCode::OK_200;
  3137. return Server::HandlerResponse::Handled;
  3138. });
  3139. auto port = svr.bind_to_any_port(HOST);
  3140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3141. auto se = detail::scope_exit([&] {
  3142. svr.stop();
  3143. thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. });
  3146. svr.wait_until_ready();
  3147. {
  3148. Client cli(HOST, port);
  3149. cli.set_path_encode(false);
  3150. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3151. EXPECT_FALSE(handle.is_valid());
  3152. EXPECT_EQ(Error::Write, handle.error);
  3153. EXPECT_FALSE(handler_called);
  3154. }
  3155. }
  3156. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3157. // Which of the two branches runs is decided by whether the query component
  3158. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3159. // an empty query and must still fall back to building one from
  3160. // `req.params`, while a non-empty query must win over `req.params`.
  3161. Server svr;
  3162. std::string target;
  3163. svr.Get("/foo", [&](const Request &req, Response &res) {
  3164. target = req.target;
  3165. res.status = StatusCode::OK_200;
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. {
  3176. // Trailing `?` -> empty query component -> `req.params` is used.
  3177. Client cli(HOST, port);
  3178. Request req;
  3179. req.method = "GET";
  3180. req.path = "/foo?";
  3181. req.params.emplace("a", "1");
  3182. target.clear();
  3183. auto res = cli.send(req);
  3184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3185. EXPECT_EQ("/foo?a=1", target);
  3186. }
  3187. {
  3188. // Non-empty query in `req.path` -> `req.params` is not appended.
  3189. Client cli(HOST, port);
  3190. Request req;
  3191. req.method = "GET";
  3192. req.path = "/foo?b=2";
  3193. req.params.emplace("a", "1");
  3194. target.clear();
  3195. auto res = cli.send(req);
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ("/foo?b=2", target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3201. Server svr;
  3202. svr.Get("/", [](const Request &req, Response &) {
  3203. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3204. });
  3205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. thread.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli(HOST, PORT);
  3214. cli.set_path_encode(false);
  3215. auto res = cli.Get("/?something=%0A");
  3216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3217. EXPECT_EQ(StatusCode::OK_200, res->status);
  3218. }
  3219. }
  3220. TEST(BindServerTest, BindDualStack) {
  3221. Server svr;
  3222. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3223. res.set_content("Hello World!", "text/plain");
  3224. });
  3225. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3226. auto se = detail::scope_exit([&] {
  3227. svr.stop();
  3228. thread.join();
  3229. ASSERT_FALSE(svr.is_running());
  3230. });
  3231. svr.wait_until_ready();
  3232. {
  3233. Client cli("127.0.0.1", PORT);
  3234. auto res = cli.Get("/1");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. {
  3240. Client cli("::1", PORT);
  3241. auto res = cli.Get("/1");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("Hello World!", res->body);
  3245. }
  3246. }
  3247. TEST(BindServerTest, BindAndListenSeparately) {
  3248. Server svr;
  3249. int port = svr.bind_to_any_port("0.0.0.0");
  3250. ASSERT_TRUE(svr.is_valid());
  3251. ASSERT_TRUE(port > 0);
  3252. svr.stop();
  3253. }
  3254. // Reports whether anything is still listening on a loopback port. A plain
  3255. // connect() is used instead of a Client request because a socket left bound by
  3256. // mistake accepts the connection into its backlog and never answers, which
  3257. // would hang the test instead of failing it.
  3258. static bool is_loopback_port_accepting(int port) {
  3259. sockaddr_in addr{};
  3260. addr.sin_family = AF_INET;
  3261. addr.sin_port = htons(static_cast<uint16_t>(port));
  3262. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3263. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3264. EXPECT_NE(sock, INVALID_SOCKET);
  3265. if (sock == INVALID_SOCKET) { return false; }
  3266. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3267. static_cast<socklen_t>(sizeof(addr)));
  3268. detail::close_socket(sock);
  3269. return ret == 0;
  3270. }
  3271. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3272. Server svr;
  3273. auto port = svr.bind_to_any_port("127.0.0.1");
  3274. ASSERT_TRUE(port > 0);
  3275. svr.stop();
  3276. // bind_to_any_port() already called listen(2), so until stop() closed the
  3277. // descriptor the port kept accepting connections into the backlog. ASSERT
  3278. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3279. // below blocks forever in the accept loop.
  3280. ASSERT_FALSE(is_loopback_port_accepting(port));
  3281. // Nothing is left to accept on, so listen_after_bind() must report failure
  3282. // instead of returning success without ever serving.
  3283. EXPECT_FALSE(svr.listen_after_bind());
  3284. // The failed listen marks the server decommissioned, so a waiter returns
  3285. // instead of spinning forever.
  3286. svr.wait_until_ready();
  3287. }
  3288. #ifdef CPPHTTPLIB_SSL_ENABLED
  3289. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3291. CLIENT_CA_CERT_DIR);
  3292. int port = svr.bind_to_any_port("0.0.0.0");
  3293. ASSERT_TRUE(svr.is_valid());
  3294. ASSERT_TRUE(port > 0);
  3295. svr.stop();
  3296. }
  3297. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3298. // or a rejected CustomRoute() registration would not stop the server binding.
  3299. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3301. CLIENT_CA_CERT_DIR);
  3302. ASSERT_TRUE(svr.is_valid());
  3303. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3304. EXPECT_FALSE(svr.is_valid());
  3305. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3306. }
  3307. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3308. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3309. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3310. int port = svr.bind_to_any_port("0.0.0.0");
  3311. ASSERT_TRUE(svr.is_valid());
  3312. ASSERT_TRUE(port > 0);
  3313. svr.stop();
  3314. }
  3315. TEST(BindServerTest, UpdateCertsPem) {
  3316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3317. int port = svr.bind_to_any_port("0.0.0.0");
  3318. ASSERT_TRUE(svr.is_valid());
  3319. ASSERT_TRUE(port > 0);
  3320. // Read PEM files
  3321. std::string cert_pem, key_pem, ca_pem;
  3322. read_file(SERVER_CERT_FILE, cert_pem);
  3323. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3324. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3325. // Update server certificates using PEM API
  3326. ASSERT_TRUE(
  3327. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3328. ASSERT_TRUE(svr.is_valid());
  3329. svr.stop();
  3330. }
  3331. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3332. // Start server with client CA (enables client auth)
  3333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3334. ASSERT_TRUE(svr.is_valid());
  3335. bool handler_called = false;
  3336. svr.Get("/test", [&](const Request &req, Response &res) {
  3337. handler_called = true;
  3338. // Verify client certificate is present
  3339. auto cert = req.peer_cert();
  3340. EXPECT_TRUE(static_cast<bool>(cert));
  3341. res.set_content("ok", "text/plain");
  3342. });
  3343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3344. auto se = detail::scope_exit([&] {
  3345. svr.stop();
  3346. t.join();
  3347. ASSERT_FALSE(svr.is_running());
  3348. });
  3349. svr.wait_until_ready();
  3350. // Read PEM files
  3351. std::string cert_pem, key_pem, ca_pem;
  3352. read_file(SERVER_CERT_FILE, cert_pem);
  3353. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3354. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3355. // Update server certificates and client CA using PEM API while server running
  3356. ASSERT_TRUE(
  3357. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3358. // Connect with client certificate
  3359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3360. cli.enable_server_certificate_verification(false);
  3361. cli.set_connection_timeout(30);
  3362. auto res = cli.Get("/test");
  3363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. ASSERT_TRUE(handler_called);
  3366. EXPECT_EQ("ok", res->body);
  3367. }
  3368. #endif
  3369. TEST(ErrorHandlerTest, ContentLength) {
  3370. Server svr;
  3371. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3372. res.status = StatusCode::OK_200;
  3373. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3374. "text/html"); // <= Content-Length still 13
  3375. });
  3376. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3377. res.set_content("Hello World!\n", "text/plain");
  3378. res.status = 524;
  3379. });
  3380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3381. auto se = detail::scope_exit([&] {
  3382. svr.stop();
  3383. thread.join();
  3384. ASSERT_FALSE(svr.is_running());
  3385. });
  3386. svr.wait_until_ready();
  3387. {
  3388. Client cli(HOST, PORT);
  3389. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3393. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3394. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3395. }
  3396. }
  3397. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3398. TEST(ExceptionTest, WithoutExceptionHandler) {
  3399. Server svr;
  3400. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3401. throw std::runtime_error("exception...");
  3402. });
  3403. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3404. throw std::runtime_error("exception\r\n...");
  3405. });
  3406. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3407. auto se = detail::scope_exit([&] {
  3408. svr.stop();
  3409. listen_thread.join();
  3410. ASSERT_FALSE(svr.is_running());
  3411. });
  3412. svr.wait_until_ready();
  3413. Client cli("localhost", PORT);
  3414. {
  3415. auto res = cli.Get("/exception");
  3416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3417. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3418. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3419. }
  3420. {
  3421. auto res = cli.Get("/unknown");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3424. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3425. }
  3426. }
  3427. TEST(ExceptionTest, WithExceptionHandler) {
  3428. Server svr;
  3429. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3430. std::exception_ptr ep) {
  3431. EXPECT_FALSE(ep == nullptr);
  3432. try {
  3433. std::rethrow_exception(ep);
  3434. } catch (std::exception &e) {
  3435. EXPECT_EQ("abc", std::string(e.what()));
  3436. } catch (...) {}
  3437. res.status = StatusCode::InternalServerError_500;
  3438. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3439. "text/html"); // <= Content-Length still 13 at this point
  3440. });
  3441. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3442. res.set_content("Hello World!\n", "text/plain");
  3443. throw std::runtime_error("abc");
  3444. });
  3445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3446. auto se = detail::scope_exit([&] {
  3447. svr.stop();
  3448. thread.join();
  3449. ASSERT_FALSE(svr.is_running());
  3450. });
  3451. svr.wait_until_ready();
  3452. for (size_t i = 0; i < 10; i++) {
  3453. Client cli(HOST, PORT);
  3454. for (size_t j = 0; j < 100; j++) {
  3455. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3457. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3460. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3461. }
  3462. cli.set_keep_alive(true);
  3463. for (size_t j = 0; j < 100; j++) {
  3464. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3467. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3468. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3469. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3470. }
  3471. }
  3472. }
  3473. TEST(ExceptionTest, AndErrorHandler) {
  3474. Server svr;
  3475. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3476. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3477. });
  3478. svr.set_exception_handler(
  3479. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3480. EXPECT_FALSE(ep == nullptr);
  3481. try {
  3482. std::rethrow_exception(ep);
  3483. } catch (std::exception &e) {
  3484. res.set_content(e.what(), "text/html");
  3485. } catch (...) {}
  3486. res.status = StatusCode::InternalServerError_500;
  3487. });
  3488. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3489. throw std::runtime_error("EXCEPTION");
  3490. });
  3491. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3492. res.set_content("ERROR", "text/html");
  3493. res.status = StatusCode::InternalServerError_500;
  3494. });
  3495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3496. auto se = detail::scope_exit([&] {
  3497. svr.stop();
  3498. thread.join();
  3499. ASSERT_FALSE(svr.is_running());
  3500. });
  3501. svr.wait_until_ready();
  3502. Client cli(HOST, PORT);
  3503. {
  3504. auto res = cli.Get("/exception");
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3507. EXPECT_EQ("EXCEPTION", res->body);
  3508. }
  3509. {
  3510. auto res = cli.Get("/error");
  3511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3512. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3513. EXPECT_EQ("ERROR", res->body);
  3514. }
  3515. {
  3516. auto res = cli.Get("/invalid");
  3517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. EXPECT_EQ("NOT_FOUND", res->body);
  3520. }
  3521. }
  3522. #endif
  3523. TEST(NoContentTest, ContentLength) {
  3524. Server svr;
  3525. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3526. res.status = StatusCode::NoContent_204;
  3527. });
  3528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3529. auto se = detail::scope_exit([&] {
  3530. svr.stop();
  3531. thread.join();
  3532. ASSERT_FALSE(svr.is_running());
  3533. });
  3534. svr.wait_until_ready();
  3535. {
  3536. Client cli(HOST, PORT);
  3537. auto res = cli.Get("/hi");
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3540. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3541. }
  3542. }
  3543. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3544. #ifdef CPPHTTPLIB_SSL_ENABLED
  3545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3546. ASSERT_TRUE(svr.is_valid());
  3547. #else
  3548. Server svr;
  3549. #endif
  3550. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3551. if (req.path == "/routing_handler") {
  3552. res.set_header("PRE_ROUTING", "on");
  3553. res.set_content("Routing Handler", "text/plain");
  3554. return httplib::Server::HandlerResponse::Handled;
  3555. }
  3556. return httplib::Server::HandlerResponse::Unhandled;
  3557. });
  3558. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3559. res.set_content("Error", "text/html");
  3560. });
  3561. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3562. if (req.path == "/routing_handler") {
  3563. res.set_header("POST_ROUTING", "on");
  3564. }
  3565. });
  3566. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3567. res.set_content("Hello World!\n", "text/plain");
  3568. });
  3569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. #ifdef CPPHTTPLIB_SSL_ENABLED
  3578. SSLClient cli(HOST, PORT);
  3579. cli.enable_server_certificate_verification(false);
  3580. #else
  3581. Client cli(HOST, PORT);
  3582. #endif
  3583. auto res = cli.Get("/routing_handler");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("Routing Handler", res->body);
  3587. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3588. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3589. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3590. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3591. }
  3592. {
  3593. #ifdef CPPHTTPLIB_SSL_ENABLED
  3594. SSLClient cli(HOST, PORT);
  3595. cli.enable_server_certificate_verification(false);
  3596. #else
  3597. Client cli(HOST, PORT);
  3598. #endif
  3599. auto res = cli.Get("/hi");
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. EXPECT_EQ("Hello World!\n", res->body);
  3603. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3604. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3605. }
  3606. {
  3607. #ifdef CPPHTTPLIB_SSL_ENABLED
  3608. SSLClient cli(HOST, PORT);
  3609. cli.enable_server_certificate_verification(false);
  3610. #else
  3611. Client cli(HOST, PORT);
  3612. #endif
  3613. auto res = cli.Get("/aaa");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3616. EXPECT_EQ("Error", res->body);
  3617. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3618. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3619. }
  3620. }
  3621. TEST(RequestHandlerTest, PreRequestHandler) {
  3622. auto route_path = "/user/:user";
  3623. Server svr;
  3624. svr.Get("/hi", [](const Request &, Response &res) {
  3625. res.set_content("hi", "text/plain");
  3626. });
  3627. svr.Get(route_path, [](const Request &req, Response &res) {
  3628. res.set_content(req.path_params.at("user"), "text/plain");
  3629. });
  3630. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3631. if (req.matched_route == route_path) {
  3632. auto user = req.path_params.at("user");
  3633. if (user != "john") {
  3634. res.status = StatusCode::Forbidden_403;
  3635. res.set_content("error", "text/html");
  3636. return Server::HandlerResponse::Handled;
  3637. }
  3638. }
  3639. return Server::HandlerResponse::Unhandled;
  3640. });
  3641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3642. auto se = detail::scope_exit([&] {
  3643. svr.stop();
  3644. thread.join();
  3645. ASSERT_FALSE(svr.is_running());
  3646. });
  3647. svr.wait_until_ready();
  3648. Client cli(HOST, PORT);
  3649. {
  3650. auto res = cli.Get("/hi");
  3651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3652. EXPECT_EQ(StatusCode::OK_200, res->status);
  3653. EXPECT_EQ("hi", res->body);
  3654. }
  3655. {
  3656. auto res = cli.Get("/user/john");
  3657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3658. EXPECT_EQ(StatusCode::OK_200, res->status);
  3659. EXPECT_EQ("john", res->body);
  3660. }
  3661. {
  3662. auto res = cli.Get("/user/invalid-user");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3665. EXPECT_EQ("error", res->body);
  3666. }
  3667. }
  3668. // The pre-request handler must run before the request body is read, so a
  3669. // rejected request never forces the server to buffer a (potentially large)
  3670. // body. Here the posted body is larger than the payload limit: if the body
  3671. // were read first the server would answer 413, but because the pre-request
  3672. // handler runs first it answers 403 and the body is never read.
  3673. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3674. Server svr;
  3675. svr.set_payload_max_length(8);
  3676. auto handler_ran = false;
  3677. svr.Post("/reject", [&](const Request &req, Response &res) {
  3678. handler_ran = true;
  3679. res.set_content(req.body, "text/plain");
  3680. });
  3681. svr.Post("/accept", [](const Request &req, Response &res) {
  3682. res.set_content(req.body, "text/plain");
  3683. });
  3684. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3685. if (req.matched_route == "/reject") {
  3686. res.status = StatusCode::Forbidden_403;
  3687. res.set_content("denied", "text/plain");
  3688. return Server::HandlerResponse::Handled;
  3689. }
  3690. return Server::HandlerResponse::Unhandled;
  3691. });
  3692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3693. auto se = detail::scope_exit([&] {
  3694. svr.stop();
  3695. thread.join();
  3696. ASSERT_FALSE(svr.is_running());
  3697. });
  3698. svr.wait_until_ready();
  3699. Client cli(HOST, PORT);
  3700. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3701. // rejects with 403 before the body is read, so 413 is never reached.
  3702. {
  3703. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3706. EXPECT_EQ("denied", res->body);
  3707. EXPECT_FALSE(handler_ran);
  3708. }
  3709. // An approved route still reads the body and enforces the payload limit.
  3710. {
  3711. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3714. }
  3715. }
  3716. TEST(UserDataTest, BasicOperations) {
  3717. httplib::UserData ud;
  3718. // Initially empty
  3719. EXPECT_FALSE(ud.has("key"));
  3720. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3721. // set and get
  3722. ud.set("key", 42);
  3723. EXPECT_TRUE(ud.has("key"));
  3724. auto *p = ud.get<int>("key");
  3725. ASSERT_NE(nullptr, p);
  3726. EXPECT_EQ(42, *p);
  3727. // Type mismatch → nullptr
  3728. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3729. // Overwrite with different type
  3730. ud.set("key", std::string("hello"));
  3731. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3732. auto *s = ud.get<std::string>("key");
  3733. ASSERT_NE(nullptr, s);
  3734. EXPECT_EQ("hello", *s);
  3735. // erase
  3736. ud.erase("key");
  3737. EXPECT_FALSE(ud.has("key"));
  3738. // clear
  3739. ud.set("a", 1);
  3740. ud.set("b", 2);
  3741. ud.clear();
  3742. EXPECT_FALSE(ud.has("a"));
  3743. EXPECT_FALSE(ud.has("b"));
  3744. }
  3745. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3746. struct AuthCtx {
  3747. std::string user_id;
  3748. };
  3749. Server svr;
  3750. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3751. res.user_data.set("auth", AuthCtx{"alice"});
  3752. return Server::HandlerResponse::Unhandled;
  3753. });
  3754. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3755. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3756. ASSERT_NE(nullptr, ctx);
  3757. res.set_content("Hello " + ctx->user_id, "text/plain");
  3758. });
  3759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3760. auto se = detail::scope_exit([&] {
  3761. svr.stop();
  3762. thread.join();
  3763. ASSERT_FALSE(svr.is_running());
  3764. });
  3765. svr.wait_until_ready();
  3766. Client cli(HOST, PORT);
  3767. auto res = cli.Get("/me");
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::OK_200, res->status);
  3770. EXPECT_EQ("Hello alice", res->body);
  3771. }
  3772. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3773. struct RoleCtx {
  3774. std::string role;
  3775. };
  3776. Server svr;
  3777. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3778. res.user_data.set("role", RoleCtx{"admin"});
  3779. return Server::HandlerResponse::Unhandled;
  3780. });
  3781. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3782. auto *ctx = res.user_data.get<RoleCtx>("role");
  3783. ASSERT_NE(nullptr, ctx);
  3784. res.set_content(ctx->role, "text/plain");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. Client cli(HOST, PORT);
  3794. auto res = cli.Get("/role");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("admin", res->body);
  3798. }
  3799. TEST(InvalidFormatTest, StatusCode) {
  3800. Server svr;
  3801. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3802. res.set_content("Hello World!\n", "text/plain");
  3803. res.status = 9999; // Status should be a three-digit code...
  3804. });
  3805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. Client cli(HOST, PORT);
  3814. auto res = cli.Get("/hi");
  3815. ASSERT_FALSE(res);
  3816. }
  3817. }
  3818. TEST(URLFragmentTest, WithFragment) {
  3819. Server svr;
  3820. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3821. EXPECT_TRUE(req.target == "/hi");
  3822. });
  3823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3824. auto se = detail::scope_exit([&] {
  3825. svr.stop();
  3826. thread.join();
  3827. ASSERT_FALSE(svr.is_running());
  3828. });
  3829. svr.wait_until_ready();
  3830. {
  3831. Client cli(HOST, PORT);
  3832. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3833. EXPECT_TRUE(res);
  3834. EXPECT_EQ(StatusCode::OK_200, res->status);
  3835. res = cli.Get("/hi%23key1=val1=key2=val2");
  3836. EXPECT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3838. }
  3839. }
  3840. TEST(HeaderWriter, SetHeaderWriter) {
  3841. Server svr;
  3842. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3843. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3844. return detail::write_headers(strm, hdrs);
  3845. });
  3846. svr.Get("/hi", [](const Request &req, Response &res) {
  3847. auto it = req.headers.find("CustomClientHeader");
  3848. EXPECT_TRUE(it != req.headers.end());
  3849. EXPECT_EQ(it->second, "CustomClientValue");
  3850. res.set_content("Hello World!\n", "text/plain");
  3851. });
  3852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3853. auto se = detail::scope_exit([&] {
  3854. svr.stop();
  3855. thread.join();
  3856. ASSERT_FALSE(svr.is_running());
  3857. });
  3858. svr.wait_until_ready();
  3859. {
  3860. Client cli(HOST, PORT);
  3861. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3862. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3863. return detail::write_headers(strm, hdrs);
  3864. });
  3865. auto res = cli.Get("/hi");
  3866. EXPECT_TRUE(res);
  3867. EXPECT_EQ(StatusCode::OK_200, res->status);
  3868. auto it = res->headers.find("CustomServerHeader");
  3869. EXPECT_TRUE(it != res->headers.end());
  3870. EXPECT_EQ(it->second, "CustomServerValue");
  3871. }
  3872. }
  3873. class ServerTest : public ::testing::Test {
  3874. protected:
  3875. ServerTest()
  3876. : cli_(HOST, PORT)
  3877. #ifdef CPPHTTPLIB_SSL_ENABLED
  3878. ,
  3879. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3880. #endif
  3881. {
  3882. #ifdef CPPHTTPLIB_SSL_ENABLED
  3883. cli_.enable_server_certificate_verification(false);
  3884. #endif
  3885. // Allow LARGE_DATA (100MB) responses
  3886. cli_.set_payload_max_length(200 * 1024 * 1024);
  3887. }
  3888. virtual void SetUp() {
  3889. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3890. svr_.set_payload_max_length(200 * 1024 * 1024);
  3891. svr_.set_mount_point("/", "./www");
  3892. svr_.set_mount_point("/mount", "./www2");
  3893. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3894. svr_.Get("/hi",
  3895. [&](const Request & /*req*/, Response &res) {
  3896. res.set_content("Hello World!", "text/plain");
  3897. })
  3898. .Get("/file_content",
  3899. [&](const Request & /*req*/, Response &res) {
  3900. res.set_file_content("./www/dir/test.html");
  3901. })
  3902. .Get("/file_content_with_content_type",
  3903. [&](const Request & /*req*/, Response &res) {
  3904. res.set_file_content("./www/file", "text/plain");
  3905. })
  3906. .Get("/invalid_file_content",
  3907. [&](const Request & /*req*/, Response &res) {
  3908. res.set_file_content("./www/dir/invalid_file_path");
  3909. })
  3910. .Get("/http_response_splitting",
  3911. [&](const Request & /*req*/, Response &res) {
  3912. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3913. EXPECT_EQ(0U, res.headers.size());
  3914. EXPECT_FALSE(res.has_header("a"));
  3915. res.set_header("a", "1\nSet-Cookie: a=1");
  3916. EXPECT_EQ(0U, res.headers.size());
  3917. EXPECT_FALSE(res.has_header("a"));
  3918. res.set_header("a", "1\rSet-Cookie: a=1");
  3919. EXPECT_EQ(0U, res.headers.size());
  3920. EXPECT_FALSE(res.has_header("a"));
  3921. res.set_header("a\r\nb", "0");
  3922. EXPECT_EQ(0U, res.headers.size());
  3923. EXPECT_FALSE(res.has_header("a"));
  3924. res.set_header("a\rb", "0");
  3925. EXPECT_EQ(0U, res.headers.size());
  3926. EXPECT_FALSE(res.has_header("a"));
  3927. res.set_header("a\nb", "0");
  3928. EXPECT_EQ(0U, res.headers.size());
  3929. EXPECT_FALSE(res.has_header("a"));
  3930. res.set_redirect("1\r\nSet-Cookie: a=1");
  3931. EXPECT_EQ(0U, res.headers.size());
  3932. EXPECT_FALSE(res.has_header("Location"));
  3933. })
  3934. .Get("/slow",
  3935. [&](const Request & /*req*/, Response &res) {
  3936. std::this_thread::sleep_for(std::chrono::seconds(4));
  3937. res.set_content("slow", "text/plain");
  3938. })
  3939. #if 0
  3940. .Post("/slowpost",
  3941. [&](const Request & /*req*/, Response &res) {
  3942. std::this_thread::sleep_for(std::chrono::seconds(2));
  3943. res.set_content("slow", "text/plain");
  3944. })
  3945. #endif
  3946. .Get("/remote_addr",
  3947. [&](const Request &req, Response &res) {
  3948. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3949. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3951. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3952. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3953. #endif
  3954. res.set_content(req.remote_addr, "text/plain");
  3955. })
  3956. .Get("/local_addr",
  3957. [&](const Request &req, Response &res) {
  3958. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3959. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3960. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3961. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3962. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3963. #endif
  3964. auto local_addr = req.local_addr;
  3965. auto local_port = std::to_string(req.local_port);
  3966. res.set_content(local_addr.append(":").append(local_port),
  3967. "text/plain");
  3968. })
  3969. .Get("/endwith%",
  3970. [&](const Request & /*req*/, Response &res) {
  3971. res.set_content("Hello World!", "text/plain");
  3972. })
  3973. .Get("/a\\+\\+b",
  3974. [&](const Request &req, Response &res) {
  3975. ASSERT_TRUE(req.has_param("a +b"));
  3976. auto val = req.get_param_value("a +b");
  3977. res.set_content(val, "text/plain");
  3978. })
  3979. .Get("/", [&](const Request & /*req*/,
  3980. Response &res) { res.set_redirect("/hi"); })
  3981. .Post("/1",
  3982. [](const Request & /*req*/, Response &res) {
  3983. res.set_redirect("/2", StatusCode::SeeOther_303);
  3984. })
  3985. .Get("/2",
  3986. [](const Request & /*req*/, Response &res) {
  3987. res.set_content("redirected.", "text/plain");
  3988. res.status = StatusCode::OK_200;
  3989. })
  3990. .Post("/person",
  3991. [&](const Request &req, Response &res) {
  3992. if (req.has_param("name") && req.has_param("note")) {
  3993. persons_[req.get_param_value("name")] =
  3994. req.get_param_value("note");
  3995. } else {
  3996. res.status = StatusCode::BadRequest_400;
  3997. }
  3998. })
  3999. .Put("/person",
  4000. [&](const Request &req, Response &res) {
  4001. if (req.has_param("name") && req.has_param("note")) {
  4002. persons_[req.get_param_value("name")] =
  4003. req.get_param_value("note");
  4004. } else {
  4005. res.status = StatusCode::BadRequest_400;
  4006. }
  4007. })
  4008. .Get("/person/(.*)",
  4009. [&](const Request &req, Response &res) {
  4010. string name = req.matches[1];
  4011. if (persons_.find(name) != persons_.end()) {
  4012. auto note = persons_[name];
  4013. res.set_content(note, "text/plain");
  4014. } else {
  4015. res.status = StatusCode::NotFound_404;
  4016. }
  4017. })
  4018. .Delete("/person",
  4019. [&](const Request &req, Response &res) {
  4020. if (req.has_param("name")) {
  4021. string name = req.get_param_value("name");
  4022. if (persons_.find(name) != persons_.end()) {
  4023. persons_.erase(name);
  4024. res.set_content("DELETED", "text/plain");
  4025. } else {
  4026. res.status = StatusCode::NotFound_404;
  4027. }
  4028. } else {
  4029. res.status = StatusCode::BadRequest_400;
  4030. }
  4031. })
  4032. .Post("/x-www-form-urlencoded-json",
  4033. [&](const Request &req, Response &res) {
  4034. auto json = req.get_param_value("json");
  4035. ASSERT_EQ(JSON_DATA, json);
  4036. res.set_content(json, "appliation/json");
  4037. res.status = StatusCode::OK_200;
  4038. })
  4039. .Get("/streamed-chunked",
  4040. [&](const Request & /*req*/, Response &res) {
  4041. res.set_chunked_content_provider(
  4042. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4043. sink.os << "123";
  4044. sink.os << "456";
  4045. sink.os << "789";
  4046. sink.done();
  4047. return true;
  4048. });
  4049. })
  4050. .Get("/streamed-chunked-with-prohibited-trailer",
  4051. [&](const Request & /*req*/, Response &res) {
  4052. auto i = new int(0);
  4053. // Declare both a prohibited trailer (Content-Length) and an
  4054. // allowed one
  4055. res.set_header("Trailer", "Content-Length, X-Allowed");
  4056. res.set_chunked_content_provider(
  4057. "text/plain",
  4058. [i](size_t /*offset*/, DataSink &sink) {
  4059. switch (*i) {
  4060. case 0: sink.os << "123"; break;
  4061. case 1: sink.os << "456"; break;
  4062. case 2: sink.os << "789"; break;
  4063. case 3: {
  4064. sink.done_with_trailer(
  4065. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4066. } break;
  4067. }
  4068. (*i)++;
  4069. return true;
  4070. },
  4071. [i](bool success) {
  4072. EXPECT_TRUE(success);
  4073. delete i;
  4074. });
  4075. })
  4076. .Get("/streamed-chunked2",
  4077. [&](const Request & /*req*/, Response &res) {
  4078. auto i = new int(0);
  4079. res.set_chunked_content_provider(
  4080. "text/plain",
  4081. [i](size_t /*offset*/, DataSink &sink) {
  4082. switch (*i) {
  4083. case 0: sink.os << "123"; break;
  4084. case 1: sink.os << "456"; break;
  4085. case 2: sink.os << "789"; break;
  4086. case 3: sink.done(); break;
  4087. }
  4088. (*i)++;
  4089. return true;
  4090. },
  4091. [i](bool success) {
  4092. EXPECT_TRUE(success);
  4093. delete i;
  4094. });
  4095. })
  4096. .Get("/streamed-chunked-with-trailer",
  4097. [&](const Request & /*req*/, Response &res) {
  4098. auto i = new int(0);
  4099. res.set_header("Trailer", "Dummy1, Dummy2");
  4100. res.set_chunked_content_provider(
  4101. "text/plain",
  4102. [i](size_t /*offset*/, DataSink &sink) {
  4103. switch (*i) {
  4104. case 0: sink.os << "123"; break;
  4105. case 1: sink.os << "456"; break;
  4106. case 2: sink.os << "789"; break;
  4107. case 3: {
  4108. sink.done_with_trailer(
  4109. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4110. } break;
  4111. }
  4112. (*i)++;
  4113. return true;
  4114. },
  4115. [i](bool success) {
  4116. EXPECT_TRUE(success);
  4117. delete i;
  4118. });
  4119. })
  4120. .Get("/streamed",
  4121. [&](const Request & /*req*/, Response &res) {
  4122. res.set_content_provider(
  4123. 6, "text/plain",
  4124. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4125. sink.os << (offset < 3 ? "a" : "b");
  4126. return true;
  4127. });
  4128. })
  4129. .Get("/streamed-without-length",
  4130. [&](const Request & /*req*/, Response &res) {
  4131. auto data = new std::string("abcdefg");
  4132. res.set_content_provider(
  4133. "text/plain",
  4134. [data](size_t offset, DataSink &sink) {
  4135. if (offset < data->size()) {
  4136. sink.os << data->substr(offset);
  4137. }
  4138. sink.done();
  4139. return true;
  4140. },
  4141. [data](bool success) {
  4142. EXPECT_TRUE(success);
  4143. delete data;
  4144. });
  4145. })
  4146. .Get("/streamed-with-range",
  4147. [&](const Request &req, Response &res) {
  4148. auto data = new std::string("abcdefg");
  4149. // An explicit status keeps the server from picking the 206 it
  4150. // would otherwise choose for a ranged request, so the response
  4151. // is not a partial representation.
  4152. auto status = req.get_param_value("status");
  4153. if (status == "200") {
  4154. res.status = StatusCode::OK_200;
  4155. } else if (status == "403") {
  4156. res.status = StatusCode::Forbidden_403;
  4157. }
  4158. res.set_content_provider(
  4159. data->size(), "text/plain",
  4160. [data](size_t offset, size_t length, DataSink &sink) {
  4161. size_t DATA_CHUNK_SIZE = 4;
  4162. const auto &d = *data;
  4163. auto out_len =
  4164. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4165. auto ret =
  4166. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4167. EXPECT_TRUE(ret);
  4168. return true;
  4169. },
  4170. [data, &req](bool success) {
  4171. EXPECT_EQ(success, !req.has_param("error"));
  4172. delete data;
  4173. });
  4174. })
  4175. .Get("/streamed-cancel",
  4176. [&](const Request & /*req*/, Response &res) {
  4177. res.set_content_provider(
  4178. size_t(-1), "text/plain",
  4179. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4180. sink.os << "data_chunk";
  4181. return true;
  4182. });
  4183. })
  4184. .Get("/regex-with-delimiter",
  4185. [&](const Request &req, Response & /*res*/) {
  4186. ASSERT_TRUE(req.has_param("key"));
  4187. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4188. })
  4189. .Get("/with-range",
  4190. [&](const Request & /*req*/, Response &res) {
  4191. res.set_content("abcdefg", "text/plain");
  4192. })
  4193. .Get("/test-start-time",
  4194. [&](const Request &req, Response & /*res*/) {
  4195. EXPECT_NE(req.start_time_,
  4196. std::chrono::steady_clock::time_point::min());
  4197. })
  4198. .Get("/with-range-customized-response",
  4199. [&](const Request & /*req*/, Response &res) {
  4200. res.status = StatusCode::BadRequest_400;
  4201. res.set_content(JSON_DATA, "application/json");
  4202. })
  4203. .Post("/chunked",
  4204. [&](const Request &req, Response & /*res*/) {
  4205. EXPECT_EQ(req.body, "dechunked post body");
  4206. })
  4207. .Post("/large-chunked",
  4208. [&](const Request &req, Response & /*res*/) {
  4209. std::string expected(6 * 30 * 1024u, 'a');
  4210. EXPECT_EQ(req.body, expected);
  4211. })
  4212. .Post("/multipart",
  4213. [&](const Request &req, Response & /*res*/) {
  4214. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4215. req.form.get_field_count("text2") +
  4216. req.form.get_field_count("file3") +
  4217. req.form.get_field_count("file4"));
  4218. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4219. req.form.get_file_count("file2"));
  4220. ASSERT_TRUE(!req.form.has_file("???"));
  4221. ASSERT_TRUE(!req.form.has_field("???"));
  4222. ASSERT_TRUE(req.body.empty());
  4223. {
  4224. const auto &text = req.form.get_field("text1");
  4225. EXPECT_EQ("text default", text);
  4226. }
  4227. {
  4228. const auto &text = req.form.get_field("text2");
  4229. EXPECT_EQ("aωb", text);
  4230. }
  4231. {
  4232. const auto &file = req.form.get_file("file1");
  4233. EXPECT_EQ("hello.txt", file.filename);
  4234. EXPECT_EQ("text/plain", file.content_type);
  4235. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4236. }
  4237. {
  4238. const auto &file = req.form.get_file("file2");
  4239. EXPECT_EQ("world.json", file.filename);
  4240. EXPECT_EQ("application/json", file.content_type);
  4241. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4242. }
  4243. {
  4244. const auto &text = req.form.get_field("file3");
  4245. EXPECT_EQ(0u, text.size());
  4246. }
  4247. {
  4248. const auto &text = req.form.get_field("file4");
  4249. EXPECT_EQ(0u, text.size());
  4250. }
  4251. })
  4252. .Post("/multipart/multi_file_values",
  4253. [&](const Request &req, Response & /*res*/) {
  4254. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4255. req.form.get_field_count("multi_text1"));
  4256. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4257. ASSERT_TRUE(!req.form.has_file("???"));
  4258. ASSERT_TRUE(!req.form.has_field("???"));
  4259. ASSERT_TRUE(req.body.empty());
  4260. {
  4261. const auto &text = req.form.get_field("text");
  4262. EXPECT_EQ("default text", text);
  4263. }
  4264. {
  4265. const auto &text1_values = req.form.get_fields("multi_text1");
  4266. EXPECT_EQ(2u, text1_values.size());
  4267. EXPECT_EQ("aaaaa", text1_values[0]);
  4268. EXPECT_EQ("bbbbb", text1_values[1]);
  4269. }
  4270. {
  4271. const auto &file1_values = req.form.get_files("multi_file1");
  4272. EXPECT_EQ(2u, file1_values.size());
  4273. auto file1 = file1_values[0];
  4274. EXPECT_EQ(file1.filename, "hello.txt");
  4275. EXPECT_EQ(file1.content_type, "text/plain");
  4276. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4277. auto file2 = file1_values[1];
  4278. EXPECT_EQ(file2.filename, "world.json");
  4279. EXPECT_EQ(file2.content_type, "application/json");
  4280. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4281. }
  4282. })
  4283. .Post("/empty",
  4284. [&](const Request &req, Response &res) {
  4285. EXPECT_EQ(req.body, "");
  4286. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4287. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4288. res.set_content("empty", "text/plain");
  4289. })
  4290. .Post("/empty-no-content-type",
  4291. [&](const Request &req, Response &res) {
  4292. EXPECT_EQ(req.body, "");
  4293. EXPECT_FALSE(req.has_header("Content-Type"));
  4294. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4295. res.set_content("empty-no-content-type", "text/plain");
  4296. })
  4297. .Post("/path-only",
  4298. [&](const Request &req, Response &res) {
  4299. EXPECT_EQ(req.body, "");
  4300. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4301. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4302. res.set_content("path-only", "text/plain");
  4303. })
  4304. .Post("/path-headers-only",
  4305. [&](const Request &req, Response &res) {
  4306. EXPECT_EQ(req.body, "");
  4307. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4308. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4309. EXPECT_EQ("world", req.get_header_value("hello"));
  4310. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4311. res.set_content("path-headers-only", "text/plain");
  4312. })
  4313. .Post("/post-large",
  4314. [&](const Request &req, Response &res) {
  4315. EXPECT_EQ(req.body, LARGE_DATA);
  4316. res.set_content(req.body, "text/plain");
  4317. })
  4318. .Post("/post-loopback",
  4319. [&](const Request &, Response &res,
  4320. ContentReader const &content_reader) {
  4321. std::string body;
  4322. content_reader([&](const char *data, size_t data_length) {
  4323. body.append(data, data_length);
  4324. return true;
  4325. });
  4326. res.set_content(body, "text/plain");
  4327. })
  4328. .Put("/put-loopback",
  4329. [&](const Request &, Response &res,
  4330. ContentReader const &content_reader) {
  4331. std::string body;
  4332. content_reader([&](const char *data, size_t data_length) {
  4333. body.append(data, data_length);
  4334. return true;
  4335. });
  4336. res.set_content(body, "text/plain");
  4337. })
  4338. .Patch("/patch-loopback",
  4339. [&](const Request &, Response &res,
  4340. ContentReader const &content_reader) {
  4341. std::string body;
  4342. content_reader([&](const char *data, size_t data_length) {
  4343. body.append(data, data_length);
  4344. return true;
  4345. });
  4346. res.set_content(body, "text/plain");
  4347. })
  4348. .Put("/empty-no-content-type",
  4349. [&](const Request &req, Response &res) {
  4350. EXPECT_EQ(req.body, "");
  4351. EXPECT_FALSE(req.has_header("Content-Type"));
  4352. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4353. res.set_content("empty-no-content-type", "text/plain");
  4354. })
  4355. .Put("/put",
  4356. [&](const Request &req, Response &res) {
  4357. EXPECT_EQ(req.body, "PUT");
  4358. res.set_content(req.body, "text/plain");
  4359. })
  4360. .Put("/put-large",
  4361. [&](const Request &req, Response &res) {
  4362. EXPECT_EQ(req.body, LARGE_DATA);
  4363. res.set_content(req.body, "text/plain");
  4364. })
  4365. .Patch("/patch",
  4366. [&](const Request &req, Response &res) {
  4367. EXPECT_EQ(req.body, "PATCH");
  4368. res.set_content(req.body, "text/plain");
  4369. })
  4370. .Delete("/delete",
  4371. [&](const Request & /*req*/, Response &res) {
  4372. res.set_content("DELETE", "text/plain");
  4373. })
  4374. .Delete("/delete-body",
  4375. [&](const Request &req, Response &res) {
  4376. EXPECT_EQ(req.body, "content");
  4377. res.set_content(req.body, "text/plain");
  4378. })
  4379. .Options(R"(\*)",
  4380. [&](const Request & /*req*/, Response &res) {
  4381. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4382. })
  4383. .CustomRoute("PROPFIND", "/dav/:id",
  4384. [&](const Request &req, Response &res) {
  4385. res.set_header("x-body-size",
  4386. std::to_string(req.body.size()));
  4387. res.set_header("x-matched-route", req.matched_route);
  4388. res.set_header("x-dav-id", req.path_params.at("id"));
  4389. res.status = StatusCode::MultiStatus_207;
  4390. res.set_content(req.body, "application/xml");
  4391. })
  4392. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4393. [&](const Request &req, Response &res) {
  4394. res.set_header("x-dav-match", req.matches[1]);
  4395. res.status = StatusCode::MultiStatus_207;
  4396. })
  4397. .CustomRoute("MKCOL", "/dav-mkcol",
  4398. [&](const Request &req, Response &res) {
  4399. EXPECT_TRUE(req.body.empty());
  4400. res.status = StatusCode::Created_201;
  4401. })
  4402. .CustomRoute(
  4403. "REPORT", "/dav-report",
  4404. [&](const Request & /*req*/, Response &res,
  4405. const ContentReader &content_reader) {
  4406. std::string body;
  4407. content_reader([&](const char *data, size_t data_length) {
  4408. body.append(data, data_length);
  4409. return true;
  4410. });
  4411. res.set_header("x-body-size", std::to_string(body.size()));
  4412. res.status = StatusCode::MultiStatus_207;
  4413. res.set_content(body, "application/xml");
  4414. })
  4415. .Get("/request-target",
  4416. [&](const Request &req, Response & /*res*/) {
  4417. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4418. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4419. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4420. })
  4421. .Get("/long-query-value",
  4422. [&](const Request &req, Response & /*res*/) {
  4423. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4424. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4425. })
  4426. .Get("/too-long-query-value",
  4427. [&](const Request &req, Response & /*res*/) {
  4428. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4429. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4430. })
  4431. .Get("/array-param",
  4432. [&](const Request &req, Response & /*res*/) {
  4433. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4434. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4435. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4436. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4437. })
  4438. .Get("/array-param-values",
  4439. [&](const Request &req, Response & /*res*/) {
  4440. auto values = req.get_param_values("array");
  4441. EXPECT_EQ(3u, values.size());
  4442. EXPECT_EQ("value1", values[0]);
  4443. EXPECT_EQ("value2", values[1]);
  4444. EXPECT_EQ("value3", values[2]);
  4445. auto empty = req.get_param_values("nonexistent");
  4446. EXPECT_TRUE(empty.empty());
  4447. })
  4448. .Post("/validate-no-multiple-headers",
  4449. [&](const Request &req, Response & /*res*/) {
  4450. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4451. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4452. })
  4453. .Post("/content_receiver",
  4454. [&](const Request &req, Response &res,
  4455. const ContentReader &content_reader) {
  4456. if (req.is_multipart_form_data()) {
  4457. std::vector<FormData> items;
  4458. content_reader(
  4459. [&](const FormData &file) {
  4460. items.push_back(file);
  4461. return true;
  4462. },
  4463. [&](const char *data, size_t data_length) {
  4464. items.back().content.append(data, data_length);
  4465. return true;
  4466. });
  4467. EXPECT_EQ(5u, items.size());
  4468. {
  4469. const auto &file = get_file_value(items, "text1");
  4470. EXPECT_TRUE(file.filename.empty());
  4471. EXPECT_EQ("text default", file.content);
  4472. }
  4473. {
  4474. const auto &file = get_file_value(items, "text2");
  4475. EXPECT_TRUE(file.filename.empty());
  4476. EXPECT_EQ("aωb", file.content);
  4477. }
  4478. {
  4479. const auto &file = get_file_value(items, "file1");
  4480. EXPECT_EQ("hello.txt", file.filename);
  4481. EXPECT_EQ("text/plain", file.content_type);
  4482. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4483. }
  4484. {
  4485. const auto &file = get_file_value(items, "file2");
  4486. EXPECT_EQ("world.json", file.filename);
  4487. EXPECT_EQ("application/json", file.content_type);
  4488. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4489. }
  4490. {
  4491. const auto &file = get_file_value(items, "file3");
  4492. EXPECT_TRUE(file.filename.empty());
  4493. EXPECT_EQ("application/octet-stream", file.content_type);
  4494. EXPECT_EQ(0u, file.content.size());
  4495. }
  4496. } else {
  4497. std::string body;
  4498. content_reader([&](const char *data, size_t data_length) {
  4499. EXPECT_EQ(7U, data_length);
  4500. body.append(data, data_length);
  4501. return true;
  4502. });
  4503. EXPECT_EQ(body, "content");
  4504. res.set_content(body, "text/plain");
  4505. }
  4506. })
  4507. .Put("/content_receiver",
  4508. [&](const Request & /*req*/, Response &res,
  4509. const ContentReader &content_reader) {
  4510. std::string body;
  4511. content_reader([&](const char *data, size_t data_length) {
  4512. body.append(data, data_length);
  4513. return true;
  4514. });
  4515. EXPECT_EQ(body, "content");
  4516. res.set_content(body, "text/plain");
  4517. })
  4518. .Patch("/content_receiver",
  4519. [&](const Request & /*req*/, Response &res,
  4520. const ContentReader &content_reader) {
  4521. std::string body;
  4522. content_reader([&](const char *data, size_t data_length) {
  4523. body.append(data, data_length);
  4524. return true;
  4525. });
  4526. EXPECT_EQ(body, "content");
  4527. res.set_content(body, "text/plain");
  4528. })
  4529. .Post("/query-string-and-body",
  4530. [&](const Request &req, Response & /*res*/) {
  4531. ASSERT_TRUE(req.has_param("key"));
  4532. EXPECT_EQ(req.get_param_value("key"), "value");
  4533. EXPECT_EQ(req.body, "content");
  4534. })
  4535. .Get("/last-request",
  4536. [&](const Request &req, Response & /*res*/) {
  4537. EXPECT_EQ("close", req.get_header_value("Connection"));
  4538. })
  4539. .Get(R"(/redirect/(\d+))",
  4540. [&](const Request &req, Response &res) {
  4541. auto num = std::stoi(req.matches[1]) + 1;
  4542. std::string url = "/redirect/" + std::to_string(num);
  4543. res.set_redirect(url);
  4544. })
  4545. .Post("/binary",
  4546. [&](const Request &req, Response &res) {
  4547. EXPECT_EQ(4U, req.body.size());
  4548. EXPECT_EQ("application/octet-stream",
  4549. req.get_header_value("Content-Type"));
  4550. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4551. res.set_content(req.body, "application/octet-stream");
  4552. })
  4553. .Put("/binary",
  4554. [&](const Request &req, Response &res) {
  4555. EXPECT_EQ(4U, req.body.size());
  4556. EXPECT_EQ("application/octet-stream",
  4557. req.get_header_value("Content-Type"));
  4558. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4559. res.set_content(req.body, "application/octet-stream");
  4560. })
  4561. .Patch("/binary",
  4562. [&](const Request &req, Response &res) {
  4563. EXPECT_EQ(4U, req.body.size());
  4564. EXPECT_EQ("application/octet-stream",
  4565. req.get_header_value("Content-Type"));
  4566. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4567. res.set_content(req.body, "application/octet-stream");
  4568. })
  4569. .Delete("/binary",
  4570. [&](const Request &req, Response &res) {
  4571. EXPECT_EQ(4U, req.body.size());
  4572. EXPECT_EQ("application/octet-stream",
  4573. req.get_header_value("Content-Type"));
  4574. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4575. res.set_content(req.body, "application/octet-stream");
  4576. })
  4577. .Get("/issue1772",
  4578. [&](const Request & /*req*/, Response &res) {
  4579. res.status = 401;
  4580. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4581. })
  4582. .Delete("/issue609",
  4583. [](const httplib::Request &, httplib::Response &res,
  4584. const httplib::ContentReader &) {
  4585. res.set_content("ok", "text/plain");
  4586. })
  4587. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4588. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4589. .Get("/compress",
  4590. [&](const Request & /*req*/, Response &res) {
  4591. res.set_content(
  4592. "12345678901234567890123456789012345678901234567890123456789"
  4593. "01234567890123456789012345678901234567890",
  4594. "text/plain");
  4595. })
  4596. .Get("/compress-with-charset",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. res.set_content(
  4599. "12345678901234567890123456789012345678901234567890123456789"
  4600. "01234567890123456789012345678901234567890",
  4601. "application/json; charset=utf-8");
  4602. })
  4603. .Get("/nocompress",
  4604. [&](const Request & /*req*/, Response &res) {
  4605. res.set_content(
  4606. "12345678901234567890123456789012345678901234567890123456789"
  4607. "01234567890123456789012345678901234567890",
  4608. "application/octet-stream");
  4609. })
  4610. .Post("/compress-multipart",
  4611. [&](const Request &req, Response & /*res*/) {
  4612. EXPECT_EQ(2u, req.form.fields.size());
  4613. ASSERT_TRUE(!req.form.has_field("???"));
  4614. {
  4615. const auto &text = req.form.get_field("key1");
  4616. EXPECT_EQ("test", text);
  4617. }
  4618. {
  4619. const auto &text = req.form.get_field("key2");
  4620. EXPECT_EQ("--abcdefg123", text);
  4621. }
  4622. })
  4623. #endif
  4624. ;
  4625. persons_["john"] = "programmer";
  4626. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4627. svr_.wait_until_ready();
  4628. }
  4629. virtual void TearDown() {
  4630. svr_.stop();
  4631. if (!request_threads_.empty()) {
  4632. std::this_thread::sleep_for(std::chrono::seconds(1));
  4633. for (auto &t : request_threads_) {
  4634. t.join();
  4635. }
  4636. }
  4637. t_.join();
  4638. }
  4639. map<string, string> persons_;
  4640. #ifdef CPPHTTPLIB_SSL_ENABLED
  4641. SSLClient cli_;
  4642. SSLServer svr_;
  4643. #else
  4644. Client cli_;
  4645. Server svr_;
  4646. #endif
  4647. thread t_;
  4648. std::vector<thread> request_threads_;
  4649. };
  4650. TEST_F(ServerTest, GetMethod200) {
  4651. auto res = cli_.Get("/hi");
  4652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4653. EXPECT_EQ("HTTP/1.1", res->version);
  4654. EXPECT_EQ(StatusCode::OK_200, res->status);
  4655. EXPECT_EQ("OK", res->reason);
  4656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4657. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4658. EXPECT_EQ("Hello World!", res->body);
  4659. }
  4660. TEST_F(ServerTest, GetEmptyFile) {
  4661. auto res = cli_.Get("/empty_file");
  4662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4665. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4666. EXPECT_EQ("", res->body);
  4667. }
  4668. TEST_F(ServerTest, GetFileContent) {
  4669. auto res = cli_.Get("/file_content");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4673. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4674. EXPECT_EQ("test.html", res->body);
  4675. }
  4676. TEST_F(ServerTest, GetFileContentWithRange) {
  4677. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4679. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4680. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4681. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4682. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4683. EXPECT_EQ("est", res->body);
  4684. }
  4685. TEST_F(ServerTest, GetFileContentWithContentType) {
  4686. auto res = cli_.Get("/file_content_with_content_type");
  4687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4688. EXPECT_EQ(StatusCode::OK_200, res->status);
  4689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4690. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4691. EXPECT_EQ("file\n", res->body);
  4692. }
  4693. TEST_F(ServerTest, GetInvalidFileContent) {
  4694. auto res = cli_.Get("/invalid_file_content");
  4695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4697. }
  4698. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4699. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. EXPECT_EQ("HTTP/1.1", res->version);
  4702. EXPECT_EQ(StatusCode::OK_200, res->status);
  4703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4704. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4705. EXPECT_EQ("Hello World!", res->body);
  4706. }
  4707. TEST_F(ServerTest, GetMethod302) {
  4708. auto res = cli_.Get("/");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::Found_302, res->status);
  4711. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4712. }
  4713. TEST_F(ServerTest, GetMethod302Redirect) {
  4714. cli_.set_follow_location(true);
  4715. auto res = cli_.Get("/");
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. EXPECT_EQ("Hello World!", res->body);
  4719. EXPECT_EQ("/hi", res->location);
  4720. }
  4721. TEST_F(ServerTest, GetMethod404) {
  4722. auto res = cli_.Get("/invalid");
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4725. }
  4726. TEST_F(ServerTest, HeadMethod200) {
  4727. auto res = cli_.Head("/hi");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body.empty());
  4732. }
  4733. TEST_F(ServerTest, HeadMethod200Static) {
  4734. auto res = cli_.Head("/mount/dir/index.html");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4738. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4739. EXPECT_TRUE(res->body.empty());
  4740. }
  4741. TEST_F(ServerTest, HeadMethod404) {
  4742. auto res = cli_.Head("/invalid");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4745. EXPECT_TRUE(res->body.empty());
  4746. }
  4747. TEST_F(ServerTest, GetMethodPersonJohn) {
  4748. auto res = cli_.Get("/person/john");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4752. EXPECT_EQ("programmer", res->body);
  4753. }
  4754. TEST_F(ServerTest, PostMethod1) {
  4755. auto res = cli_.Get("/person/john1");
  4756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4758. res = cli_.Post("/person", "name=john1&note=coder",
  4759. "application/x-www-form-urlencoded");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. ASSERT_EQ(StatusCode::OK_200, res->status);
  4762. res = cli_.Get("/person/john1");
  4763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4764. ASSERT_EQ(StatusCode::OK_200, res->status);
  4765. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4766. ASSERT_EQ("coder", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostMethod2) {
  4769. auto res = cli_.Get("/person/john2");
  4770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4771. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4772. Params params;
  4773. params.emplace("name", "john2");
  4774. params.emplace("note", "coder");
  4775. res = cli_.Post("/person", params);
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. res = cli_.Get("/person/john2");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4782. ASSERT_EQ("coder", res->body);
  4783. }
  4784. TEST_F(ServerTest, PutMethod3) {
  4785. auto res = cli_.Get("/person/john3");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4788. Params params;
  4789. params.emplace("name", "john3");
  4790. params.emplace("note", "coder");
  4791. res = cli_.Put("/person", params);
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. res = cli_.Get("/person/john3");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. ASSERT_EQ(StatusCode::OK_200, res->status);
  4797. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4798. ASSERT_EQ("coder", res->body);
  4799. }
  4800. TEST_F(ServerTest, DeleteMethod1) {
  4801. auto res = cli_.Get("/person/john4");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4804. Params params;
  4805. params.emplace("name", "john4");
  4806. params.emplace("note", "coder");
  4807. res = cli_.Post("/person", params);
  4808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4809. ASSERT_EQ(StatusCode::OK_200, res->status);
  4810. res = cli_.Get("/person/john4");
  4811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4812. ASSERT_EQ(StatusCode::OK_200, res->status);
  4813. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4814. ASSERT_EQ("coder", res->body);
  4815. Params delete_params;
  4816. delete_params.emplace("name", "john4");
  4817. res = cli_.Delete("/person", delete_params);
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. ASSERT_EQ(StatusCode::OK_200, res->status);
  4820. ASSERT_EQ("DELETED", res->body);
  4821. res = cli_.Get("/person/john4");
  4822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4823. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4824. }
  4825. TEST_F(ServerTest, DeleteMethod2) {
  4826. auto res = cli_.Get("/person/john5");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4829. Params params;
  4830. params.emplace("name", "john5");
  4831. params.emplace("note", "developer");
  4832. res = cli_.Post("/person", params);
  4833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4834. ASSERT_EQ(StatusCode::OK_200, res->status);
  4835. res = cli_.Get("/person/john5");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. ASSERT_EQ(StatusCode::OK_200, res->status);
  4838. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4839. ASSERT_EQ("developer", res->body);
  4840. Params delete_params;
  4841. delete_params.emplace("name", "john5");
  4842. Headers headers;
  4843. headers.emplace("Custom-Header", "test-value");
  4844. res = cli_.Delete("/person", headers, delete_params);
  4845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4846. ASSERT_EQ(StatusCode::OK_200, res->status);
  4847. ASSERT_EQ("DELETED", res->body);
  4848. res = cli_.Get("/person/john5");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4851. }
  4852. TEST_F(ServerTest, DeleteMethod3) {
  4853. auto res = cli_.Get("/person/john6");
  4854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4855. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4856. Params params;
  4857. params.emplace("name", "john6");
  4858. params.emplace("note", "tester");
  4859. res = cli_.Post("/person", params);
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. res = cli_.Get("/person/john6");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. ASSERT_EQ(StatusCode::OK_200, res->status);
  4865. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. ASSERT_EQ("tester", res->body);
  4867. Params delete_params;
  4868. delete_params.emplace("name", "john6");
  4869. Headers headers;
  4870. headers.emplace("Custom-Header", "test-value");
  4871. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. ASSERT_EQ(StatusCode::OK_200, res->status);
  4874. ASSERT_EQ("DELETED", res->body);
  4875. res = cli_.Get("/person/john6");
  4876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4877. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4878. }
  4879. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4880. Params params;
  4881. params.emplace("json", JSON_DATA);
  4882. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. ASSERT_EQ(StatusCode::OK_200, res->status);
  4885. ASSERT_EQ(JSON_DATA, res->body);
  4886. }
  4887. TEST_F(ServerTest, PostEmptyContent) {
  4888. auto res = cli_.Post("/empty", "", "text/plain");
  4889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4890. ASSERT_EQ(StatusCode::OK_200, res->status);
  4891. ASSERT_EQ("empty", res->body);
  4892. }
  4893. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4894. auto res = cli_.Post("/empty-no-content-type");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. ASSERT_EQ(StatusCode::OK_200, res->status);
  4897. ASSERT_EQ("empty-no-content-type", res->body);
  4898. }
  4899. TEST_F(ServerTest, PostPathOnly) {
  4900. auto res = cli_.Post("/path-only");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. ASSERT_EQ(StatusCode::OK_200, res->status);
  4903. ASSERT_EQ("path-only", res->body);
  4904. }
  4905. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4906. auto res = cli_.Post("/path-headers-only",
  4907. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4909. ASSERT_EQ(StatusCode::OK_200, res->status);
  4910. ASSERT_EQ("path-headers-only", res->body);
  4911. }
  4912. TEST_F(ServerTest, PostLarge) {
  4913. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. ASSERT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ(LARGE_DATA, res->body);
  4917. }
  4918. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4919. auto res = cli_.Put("/empty-no-content-type");
  4920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4921. ASSERT_EQ(StatusCode::OK_200, res->status);
  4922. ASSERT_EQ("empty-no-content-type", res->body);
  4923. }
  4924. TEST_F(ServerTest, GetMethodDir) {
  4925. auto res = cli_.Get("/dir/");
  4926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4927. EXPECT_EQ(StatusCode::OK_200, res->status);
  4928. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4929. auto body = R"(<html>
  4930. <head>
  4931. </head>
  4932. <body>
  4933. <a href="/dir/test.html">Test</a>
  4934. <a href="/hi">hi</a>
  4935. </body>
  4936. </html>
  4937. )";
  4938. EXPECT_EQ(body, res->body);
  4939. }
  4940. TEST_F(ServerTest, GetMethodDirTest) {
  4941. auto res = cli_.Get("/dir/test.html");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4945. EXPECT_EQ("test.html", res->body);
  4946. }
  4947. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4948. auto res = cli_.Get("/dir/../dir/test.html");
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4952. EXPECT_EQ("test.html", res->body);
  4953. }
  4954. TEST_F(ServerTest, GetMethodInvalidPath) {
  4955. auto res = cli_.Get("/dir/../test.html");
  4956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4958. }
  4959. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4960. auto res = cli_.Get("/../www/dir/test.html");
  4961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4963. }
  4964. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4965. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4968. }
  4969. TEST_F(ServerTest, GetMethodDirMountTest) {
  4970. auto res = cli_.Get("/mount/dir/test.html");
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4974. EXPECT_EQ("test.html", res->body);
  4975. }
  4976. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4977. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4981. EXPECT_EQ("test.html", res->body);
  4982. }
  4983. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4984. auto res = cli_.Get("/mount/dir/../test.html");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4987. }
  4988. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4989. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4992. }
  4993. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4994. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4997. }
  4998. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4999. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5002. }
  5003. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5004. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5007. }
  5008. TEST_F(ServerTest, PostMethod303) {
  5009. auto res = cli_.Post("/1", "body", "text/plain");
  5010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5011. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5012. EXPECT_EQ("/2", res->get_header_value("Location"));
  5013. }
  5014. TEST_F(ServerTest, PostMethod303Redirect) {
  5015. cli_.set_follow_location(true);
  5016. auto res = cli_.Post("/1", "body", "text/plain");
  5017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. EXPECT_EQ("redirected.", res->body);
  5020. EXPECT_EQ("/2", res->location);
  5021. }
  5022. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5023. auto res = cli_.Get("/dir/test.abcde");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5027. EXPECT_EQ("abcde", res->body);
  5028. }
  5029. TEST_F(ServerTest, StaticFileRange) {
  5030. auto res =
  5031. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5034. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5035. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5036. EXPECT_EQ(true, res->has_header("Content-Range"));
  5037. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5038. EXPECT_EQ(std::string("cd"), res->body);
  5039. }
  5040. TEST_F(ServerTest, StaticFileRanges) {
  5041. auto res = cli_.Get("/dir/test.abcde",
  5042. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5045. EXPECT_TRUE(
  5046. res->get_header_value("Content-Type")
  5047. .find(
  5048. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5049. 0);
  5050. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5051. }
  5052. TEST_F(ServerTest, StaticFileRangeHead) {
  5053. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5056. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5057. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5058. EXPECT_EQ(true, res->has_header("Content-Range"));
  5059. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5060. }
  5061. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5062. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ(true, res->has_header("Content-Range"));
  5068. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5069. res->get_header_value("Content-Range"));
  5070. EXPECT_EQ("LAST\n", res->body);
  5071. }
  5072. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5073. auto res =
  5074. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5078. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5079. EXPECT_EQ(true, res->has_header("Content-Range"));
  5080. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5081. }
  5082. TEST_F(ServerTest, StaticFileBigFile) {
  5083. auto res = cli_.Get("/dir/1MB.txt");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5087. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5088. }
  5089. TEST_F(ServerTest, InvalidBaseDirMount) {
  5090. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5091. }
  5092. TEST_F(ServerTest, Binary) {
  5093. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5094. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5095. "application/octet-stream");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. ASSERT_EQ(StatusCode::OK_200, res->status);
  5098. ASSERT_EQ(4U, res->body.size());
  5099. res = cli_.Put("/binary", binary.data(), binary.size(),
  5100. "application/octet-stream");
  5101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5102. ASSERT_EQ(StatusCode::OK_200, res->status);
  5103. ASSERT_EQ(4U, res->body.size());
  5104. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5105. "application/octet-stream");
  5106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5107. ASSERT_EQ(StatusCode::OK_200, res->status);
  5108. ASSERT_EQ(4U, res->body.size());
  5109. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5110. "application/octet-stream");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. ASSERT_EQ(StatusCode::OK_200, res->status);
  5113. ASSERT_EQ(4U, res->body.size());
  5114. }
  5115. TEST_F(ServerTest, BinaryString) {
  5116. auto binary = std::string("\x00\x01\x02\x03", 4);
  5117. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5119. ASSERT_EQ(StatusCode::OK_200, res->status);
  5120. ASSERT_EQ(4U, res->body.size());
  5121. res = cli_.Put("/binary", binary, "application/octet-stream");
  5122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5123. ASSERT_EQ(StatusCode::OK_200, res->status);
  5124. ASSERT_EQ(4U, res->body.size());
  5125. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5127. ASSERT_EQ(StatusCode::OK_200, res->status);
  5128. ASSERT_EQ(4U, res->body.size());
  5129. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. ASSERT_EQ(StatusCode::OK_200, res->status);
  5132. ASSERT_EQ(4U, res->body.size());
  5133. }
  5134. TEST_F(ServerTest, EmptyRequest) {
  5135. auto res = cli_.Get("");
  5136. ASSERT_TRUE(!res);
  5137. EXPECT_EQ(Error::Connection, res.error());
  5138. }
  5139. TEST_F(ServerTest, LongRequest) {
  5140. std::string request;
  5141. for (size_t i = 0; i < 545; i++) {
  5142. request += "/TooLongRequest";
  5143. }
  5144. request += "OK";
  5145. auto res = cli_.Get(request.c_str());
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5148. }
  5149. TEST_F(ServerTest, TooLongRequest) {
  5150. std::string request;
  5151. for (size_t i = 0; i < 546; i++) {
  5152. request += "/TooLongRequest";
  5153. }
  5154. request += "_NG";
  5155. auto start = std::chrono::high_resolution_clock::now();
  5156. cli_.set_keep_alive(true);
  5157. auto res = cli_.Get(request.c_str());
  5158. auto end = std::chrono::high_resolution_clock::now();
  5159. auto elapsed =
  5160. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5161. .count();
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5164. EXPECT_LE(elapsed, 1000);
  5165. EXPECT_EQ("close", res->get_header_value("Connection"));
  5166. EXPECT_FALSE(cli_.is_socket_open());
  5167. }
  5168. TEST_F(ServerTest, AlmostTooLongRequest) {
  5169. // test for #2046 - URI length check shouldn't include other content on req
  5170. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5171. // leading /, space, HTTP/1.1)
  5172. std::string request =
  5173. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5174. auto res = cli_.Get(request.c_str());
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5177. }
  5178. TEST_F(ServerTest, LongHeader) {
  5179. Request req;
  5180. req.method = "GET";
  5181. req.path = "/hi";
  5182. std::string host_and_port;
  5183. host_and_port += HOST;
  5184. host_and_port += ":";
  5185. host_and_port += std::to_string(PORT);
  5186. req.headers.emplace("Host", host_and_port.c_str());
  5187. req.headers.emplace("Accept", "*/*");
  5188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5189. req.headers.emplace(
  5190. "Header-Name",
  5191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@");
  5220. auto res = std::make_shared<Response>();
  5221. auto error = Error::Success;
  5222. auto ret = cli_.send(req, *res, error);
  5223. ASSERT_TRUE(ret);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. }
  5226. TEST_F(ServerTest, LongQueryValue) {
  5227. auto start = std::chrono::high_resolution_clock::now();
  5228. cli_.set_keep_alive(true);
  5229. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5230. auto end = std::chrono::high_resolution_clock::now();
  5231. auto elapsed =
  5232. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5233. .count();
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5236. EXPECT_LE(elapsed, 1000);
  5237. EXPECT_EQ("close", res->get_header_value("Connection"));
  5238. EXPECT_FALSE(cli_.is_socket_open());
  5239. }
  5240. TEST_F(ServerTest, TooLongQueryValue) {
  5241. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5242. ASSERT_FALSE(res);
  5243. EXPECT_EQ(Error::Read, res.error());
  5244. }
  5245. TEST_F(ServerTest, TooLongHeader) {
  5246. Request req;
  5247. req.method = "GET";
  5248. req.path = "/hi";
  5249. std::string host_and_port;
  5250. host_and_port += HOST;
  5251. host_and_port += ":";
  5252. host_and_port += std::to_string(PORT);
  5253. req.headers.emplace("Host", host_and_port.c_str());
  5254. req.headers.emplace("Accept", "*/*");
  5255. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5256. req.headers.emplace(
  5257. "Header-Name",
  5258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5286. "@@@@@@@@@@@@@@@@@");
  5287. auto res = std::make_shared<Response>();
  5288. auto error = Error::Success;
  5289. auto ret = cli_.send(req, *res, error);
  5290. ASSERT_TRUE(ret);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeaderCountAtLimit) {
  5294. // Test with headers just under the 100 limit
  5295. httplib::Headers headers;
  5296. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5297. // This should keep us just under the 100 header limit
  5298. for (int i = 0; i < 95; i++) {
  5299. std::string name = "X-Test-Header-" + std::to_string(i);
  5300. std::string value = "value" + std::to_string(i);
  5301. headers.emplace(name, value);
  5302. }
  5303. // This should work fine as we're under the limit
  5304. auto res = cli_.Get("/hi", headers);
  5305. EXPECT_TRUE(res);
  5306. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5307. }
  5308. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5309. // Test with many headers to exceed the 100 limit
  5310. httplib::Headers headers;
  5311. // Add 150 headers to definitely exceed the 100 limit
  5312. for (int i = 0; i < 150; i++) {
  5313. std::string name = "X-Test-Header-" + std::to_string(i);
  5314. std::string value = "value" + std::to_string(i);
  5315. headers.emplace(name, value);
  5316. }
  5317. // This should fail due to exceeding header count limit
  5318. cli_.set_keep_alive(true);
  5319. auto res = cli_.Get("/hi", headers);
  5320. // The server should respond with 400 Bad Request
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5323. EXPECT_EQ("close", res->get_header_value("Connection"));
  5324. EXPECT_FALSE(cli_.is_socket_open());
  5325. }
  5326. TEST_F(ServerTest, PercentEncoding) {
  5327. auto res = cli_.Get("/e%6edwith%");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. }
  5331. TEST_F(ServerTest, PercentEncodingUnicode) {
  5332. auto res = cli_.Get("/e%u006edwith%");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. }
  5336. TEST_F(ServerTest, InvalidPercentEncoding) {
  5337. auto res = cli_.Get("/%endwith%");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5340. }
  5341. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5342. auto res = cli_.Get("/%uendwith%");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5347. auto res = cli_.Get("/hello?aaa=bbb%");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5350. }
  5351. TEST_F(ServerTest, PlusSignEncoding) {
  5352. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::OK_200, res->status);
  5355. EXPECT_EQ("a +b", res->body);
  5356. }
  5357. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5358. // This test simulates a potential DoS attack using many headers
  5359. // to verify our security fix prevents memory exhaustion
  5360. httplib::Headers attack_headers;
  5361. // Attempt to add many headers like an attacker would (200 headers to far
  5362. // exceed limit)
  5363. for (int i = 0; i < 200; i++) {
  5364. std::string name = "X-Attack-Header-" + std::to_string(i);
  5365. std::string value = "attack_payload_" + std::to_string(i);
  5366. attack_headers.emplace(name, value);
  5367. }
  5368. // Try to POST with excessive headers
  5369. cli_.set_keep_alive(true);
  5370. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5371. // Should either fail or return 400 Bad Request due to security limit
  5372. if (res) {
  5373. // If we get a response, it should be 400 Bad Request
  5374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5375. EXPECT_EQ("close", res->get_header_value("Connection"));
  5376. }
  5377. EXPECT_FALSE(cli_.is_socket_open());
  5378. }
  5379. TEST_F(ServerTest, MultipartFormData) {
  5380. UploadFormDataItems items = {
  5381. {"text1", "text default", "", ""},
  5382. {"text2", "aωb", "", ""},
  5383. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5384. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5385. {"file3", "", "", "application/octet-stream"},
  5386. {"file4", "", "", " application/json tmp-string "}};
  5387. auto res = cli_.Post("/multipart", items);
  5388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5392. UploadFormDataItems items = {
  5393. {"text", "default text", "", ""},
  5394. {"multi_text1", "aaaaa", "", ""},
  5395. {"multi_text1", "bbbbb", "", ""},
  5396. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5397. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5398. "application/json"},
  5399. };
  5400. auto res = cli_.Post("/multipart/multi_file_values", items);
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5405. auto res = cli_.Get("/hi");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5409. EXPECT_EQ("Hello World!", res->body);
  5410. }
  5411. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5412. Request req;
  5413. req.method = "POST";
  5414. req.path = "/chunked";
  5415. std::string host_and_port;
  5416. host_and_port += HOST;
  5417. host_and_port += ":";
  5418. host_and_port += std::to_string(PORT);
  5419. req.headers.emplace("Host", host_and_port.c_str());
  5420. req.headers.emplace("Accept", "*/*");
  5421. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5422. req.headers.emplace("Content-Type", "text/plain");
  5423. req.headers.emplace("Content-Length", "0");
  5424. req.headers.emplace(
  5425. "Transfer-Encoding",
  5426. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5427. // Client does not chunk, so make a chunked body manually.
  5428. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5429. auto res = std::make_shared<Response>();
  5430. auto error = Error::Success;
  5431. auto ret = cli_.send(req, *res, error);
  5432. ASSERT_TRUE(ret);
  5433. EXPECT_EQ(StatusCode::OK_200, res->status);
  5434. }
  5435. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5436. // rather than treat them as valid lengths.
  5437. template <typename ClientT>
  5438. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5439. Request req;
  5440. req.method = "POST";
  5441. req.path = "/chunked";
  5442. std::string host_and_port;
  5443. host_and_port += HOST;
  5444. host_and_port += ":";
  5445. host_and_port += std::to_string(PORT);
  5446. req.headers.emplace("Host", host_and_port.c_str());
  5447. req.headers.emplace("Content-Length", "0");
  5448. req.headers.emplace("Transfer-Encoding", "chunked");
  5449. req.body = body;
  5450. auto res = std::make_shared<Response>();
  5451. auto error = Error::Success;
  5452. ASSERT_TRUE(cli.send(req, *res, error));
  5453. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5454. }
  5455. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5456. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5457. }
  5458. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5459. expect_chunked_body_rejected(
  5460. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5461. }
  5462. TEST_F(ServerTest, GetStreamed2) {
  5463. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5467. EXPECT_EQ(true, res->has_header("Content-Range"));
  5468. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5469. EXPECT_EQ(std::string("ab"), res->body);
  5470. }
  5471. TEST_F(ServerTest, GetStreamed) {
  5472. auto res = cli_.Get("/streamed");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5476. EXPECT_EQ(std::string("aaabbb"), res->body);
  5477. }
  5478. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5479. auto res = cli_.Get("/streamed-without-length",
  5480. Headers{make_range_header({{0, -1}})});
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(false, res->has_header("Content-Length"));
  5484. EXPECT_EQ(false, res->has_header("Content-Range"));
  5485. EXPECT_EQ(std::string("abcdefg"), res->body);
  5486. }
  5487. TEST_F(ServerTest, GetStreamedWithRange1) {
  5488. auto res =
  5489. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5492. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5493. EXPECT_EQ(true, res->has_header("Content-Range"));
  5494. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5495. EXPECT_EQ(std::string("def"), res->body);
  5496. }
  5497. TEST_F(ServerTest, GetStreamedWithRange2) {
  5498. auto res =
  5499. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5501. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5502. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(true, res->has_header("Content-Range"));
  5504. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5505. EXPECT_EQ(std::string("bcdefg"), res->body);
  5506. }
  5507. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5508. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5511. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5512. EXPECT_EQ(true, res->has_header("Content-Range"));
  5513. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5514. EXPECT_EQ(std::string("efg"), res->body);
  5515. }
  5516. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5517. auto res =
  5518. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5521. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5522. EXPECT_EQ(false, res->has_header("Content-Range"));
  5523. EXPECT_EQ(0U, res->body.size());
  5524. }
  5525. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5526. // Only a 206 is served as a partial representation. Under any other status
  5527. // `apply_ranges()` reported the full content length, so the body must match
  5528. // that header, and the content provider must never be asked for an offset
  5529. // outside the representation.
  5530. auto check = [&](int status, const char *range) {
  5531. auto path =
  5532. std::string("/streamed-with-range?status=") + std::to_string(status);
  5533. auto ctx = path + " Range: " + range;
  5534. auto res = cli_.Get(path, Headers{{"Range", range}});
  5535. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5536. EXPECT_EQ(status, res->status) << ctx;
  5537. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5539. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5540. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5541. };
  5542. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5543. check(403, "bytes=3-5");
  5544. // The offset is far past the representation.
  5545. check(403, "bytes=100000-100200");
  5546. // `first_pos` is still -1 here, and the bounds asserts in
  5547. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5548. check(403, "bytes=-3");
  5549. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5550. // multipart branch would have written one that is empty.
  5551. check(403, "bytes=1-2, 4-5");
  5552. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5553. // covers the whole representation.
  5554. check(200, "bytes=3-5");
  5555. check(200, "bytes=1-2, 4-5");
  5556. }
  5557. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5558. auto res =
  5559. cli_.Get("/streamed-with-range",
  5560. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5561. "92233720368547758079223372036854775807"}});
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5564. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5565. EXPECT_EQ(false, res->has_header("Content-Range"));
  5566. EXPECT_EQ(0U, res->body.size());
  5567. }
  5568. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5569. auto res = cli_.Get(
  5570. "/with-range",
  5571. Headers{{"Range",
  5572. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5573. {"Accept-Encoding", ""}});
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5576. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5577. EXPECT_EQ(true, res->has_header("Content-Range"));
  5578. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5579. EXPECT_EQ(std::string("abcdefg"), res->body);
  5580. }
  5581. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5582. auto res = cli_.Get("/with-range", Headers{
  5583. {"Range", "bytes=0-"},
  5584. {"Accept-Encoding", ""},
  5585. });
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5588. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ(true, res->has_header("Content-Range"));
  5590. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5591. EXPECT_EQ(std::string("abcdefg"), res->body);
  5592. }
  5593. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5594. auto res = cli_.Get("/streamed-with-range",
  5595. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5598. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5599. EXPECT_EQ(false, res->has_header("Content-Range"));
  5600. EXPECT_EQ(267U, res->body.size());
  5601. // Check that both range contents are present
  5602. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5603. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5604. // Check that Content-Range headers are present for both ranges
  5605. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5606. std::string::npos);
  5607. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5608. std::string::npos);
  5609. }
  5610. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5611. Ranges ranges;
  5612. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5613. ranges.emplace_back(0, -1);
  5614. }
  5615. auto res = cli_.Get("/streamed-with-range?error",
  5616. Headers{{make_range_header(ranges)}});
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ(false, res->has_header("Content-Range"));
  5621. EXPECT_EQ(0U, res->body.size());
  5622. }
  5623. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5624. auto res = cli_.Get("/streamed-with-range",
  5625. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5628. EXPECT_EQ(5U, res->body.size());
  5629. // Check that overlapping ranges are coalesced into a single range
  5630. EXPECT_EQ("bcdef", res->body);
  5631. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5632. // Should be single range, not multipart
  5633. EXPECT_TRUE(res->has_header("Content-Range"));
  5634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5635. }
  5636. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5637. auto res = cli_.Get("/streamed-with-range",
  5638. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5641. EXPECT_EQ(268U, res->body.size());
  5642. // Check that both range contents are present
  5643. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5644. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5645. // Check that Content-Range headers are present for both ranges
  5646. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5647. std::string::npos);
  5648. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5649. std::string::npos);
  5650. }
  5651. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5652. auto res = cli_.Get("/streamed-with-range",
  5653. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5656. EXPECT_EQ(269U, res->body.size());
  5657. // Check that both duplicate range contents are present
  5658. size_t first_abc = res->body.find("abc\r\n");
  5659. EXPECT_TRUE(first_abc != std::string::npos);
  5660. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5661. EXPECT_TRUE(second_abc != std::string::npos);
  5662. // Check that Content-Range headers are present for both ranges
  5663. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5664. EXPECT_TRUE(first_range != std::string::npos);
  5665. size_t second_range =
  5666. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5667. EXPECT_TRUE(second_range != std::string::npos);
  5668. }
  5669. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5670. auto res =
  5671. cli_.Get("/streamed-with-range?error",
  5672. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5675. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5676. EXPECT_EQ(false, res->has_header("Content-Range"));
  5677. EXPECT_EQ(0U, res->body.size());
  5678. }
  5679. TEST_F(ServerTest, GetStreamedEndless) {
  5680. uint64_t offset = 0;
  5681. auto res = cli_.Get("/streamed-cancel",
  5682. [&](const char * /*data*/, uint64_t data_length) {
  5683. if (offset < 100) {
  5684. offset += data_length;
  5685. return true;
  5686. }
  5687. return false;
  5688. });
  5689. ASSERT_TRUE(!res);
  5690. EXPECT_EQ(Error::Canceled, res.error());
  5691. }
  5692. TEST_F(ServerTest, ClientStop) {
  5693. std::atomic_size_t count{4};
  5694. std::vector<std::thread> threads;
  5695. for (auto i = count.load(); i != 0; --i) {
  5696. threads.emplace_back([&]() {
  5697. auto res = cli_.Get("/streamed-cancel",
  5698. [&](const char *, uint64_t) { return true; });
  5699. --count;
  5700. ASSERT_TRUE(!res);
  5701. EXPECT_TRUE(res.error() == Error::Canceled ||
  5702. res.error() == Error::Read || res.error() == Error::Write);
  5703. });
  5704. }
  5705. std::this_thread::sleep_for(std::chrono::seconds(2));
  5706. while (count != 0) {
  5707. cli_.stop();
  5708. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5709. }
  5710. for (auto &t : threads) {
  5711. t.join();
  5712. }
  5713. }
  5714. TEST_F(ServerTest, GetWithRange1) {
  5715. auto res = cli_.Get("/with-range", Headers{
  5716. make_range_header({{3, 5}}),
  5717. {"Accept-Encoding", ""},
  5718. });
  5719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5721. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5722. EXPECT_EQ(true, res->has_header("Content-Range"));
  5723. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5724. EXPECT_EQ(std::string("def"), res->body);
  5725. }
  5726. TEST_F(ServerTest, GetWithRange2) {
  5727. auto res = cli_.Get("/with-range", Headers{
  5728. make_range_header({{1, -1}}),
  5729. {"Accept-Encoding", ""},
  5730. });
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5733. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5734. EXPECT_EQ(true, res->has_header("Content-Range"));
  5735. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5736. EXPECT_EQ(std::string("bcdefg"), res->body);
  5737. }
  5738. TEST_F(ServerTest, GetWithRange3) {
  5739. auto res = cli_.Get("/with-range", Headers{
  5740. make_range_header({{0, 0}}),
  5741. {"Accept-Encoding", ""},
  5742. });
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5745. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5746. EXPECT_EQ(true, res->has_header("Content-Range"));
  5747. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5748. EXPECT_EQ(std::string("a"), res->body);
  5749. }
  5750. TEST_F(ServerTest, GetWithRange4) {
  5751. auto res = cli_.Get("/with-range", Headers{
  5752. make_range_header({{-1, 2}}),
  5753. {"Accept-Encoding", ""},
  5754. });
  5755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5757. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5758. EXPECT_EQ(true, res->has_header("Content-Range"));
  5759. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5760. EXPECT_EQ(std::string("fg"), res->body);
  5761. }
  5762. TEST_F(ServerTest, GetWithRange5) {
  5763. auto res = cli_.Get("/with-range", Headers{
  5764. make_range_header({{0, 5}}),
  5765. {"Accept-Encoding", ""},
  5766. });
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5769. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5770. EXPECT_EQ(true, res->has_header("Content-Range"));
  5771. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5772. EXPECT_EQ(std::string("abcdef"), res->body);
  5773. }
  5774. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5775. auto res =
  5776. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5779. }
  5780. TEST_F(ServerTest, GetWithRangeMultipart) {
  5781. auto res =
  5782. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5785. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5786. EXPECT_EQ(false, res->has_header("Content-Range"));
  5787. EXPECT_EQ(267U, res->body.size());
  5788. }
  5789. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5790. auto res = cli_.Get("/with-range",
  5791. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5794. }
  5795. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5796. auto res = cli_.Get("/with-range-customized-response",
  5797. Headers{{make_range_header({{1, 2}})}});
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5800. EXPECT_EQ(true, res->has_header("Content-Length"));
  5801. EXPECT_EQ(false, res->has_header("Content-Range"));
  5802. EXPECT_EQ(JSON_DATA, res->body);
  5803. }
  5804. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5805. auto res = cli_.Get("/with-range-customized-response",
  5806. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5809. EXPECT_EQ(true, res->has_header("Content-Length"));
  5810. EXPECT_EQ(false, res->has_header("Content-Range"));
  5811. EXPECT_EQ(JSON_DATA, res->body);
  5812. }
  5813. TEST_F(ServerTest, Issue1772) {
  5814. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5817. }
  5818. TEST_F(ServerTest, Issue609) {
  5819. auto res = cli_.Delete("/issue609");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ(std::string("ok"), res->body);
  5823. }
  5824. TEST_F(ServerTest, GetStreamedChunked) {
  5825. auto res = cli_.Get("/streamed-chunked");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. EXPECT_EQ(StatusCode::OK_200, res->status);
  5828. EXPECT_EQ(std::string("123456789"), res->body);
  5829. }
  5830. TEST_F(ServerTest, GetStreamedChunked2) {
  5831. auto res = cli_.Get("/streamed-chunked2");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. EXPECT_EQ(std::string("123456789"), res->body);
  5835. }
  5836. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5837. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. EXPECT_EQ(std::string("123456789"), res->body);
  5841. EXPECT_TRUE(res->has_header("Trailer"));
  5842. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5843. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5844. // Trailers are now stored separately from headers (security fix)
  5845. EXPECT_EQ(2U, res->trailers.size());
  5846. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5847. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5848. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5849. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5850. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5851. // Verify trailers are NOT in headers (security verification)
  5852. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5853. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5854. }
  5855. TEST_F(ServerTest, LargeChunkedPost) {
  5856. Request req;
  5857. req.method = "POST";
  5858. req.path = "/large-chunked";
  5859. std::string host_and_port;
  5860. host_and_port += HOST;
  5861. host_and_port += ":";
  5862. host_and_port += std::to_string(PORT);
  5863. req.headers.emplace("Host", host_and_port.c_str());
  5864. req.headers.emplace("Accept", "*/*");
  5865. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5866. req.headers.emplace("Content-Type", "text/plain");
  5867. req.headers.emplace("Content-Length", "0");
  5868. req.headers.emplace("Transfer-Encoding", "chunked");
  5869. std::string long_string(30 * 1024u, 'a');
  5870. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5871. // Attempt to make a large enough post to exceed OS buffers, to test that
  5872. // the server handles short reads if the full chunk data isn't available.
  5873. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5874. auto res = std::make_shared<Response>();
  5875. auto error = Error::Success;
  5876. auto ret = cli_.send(req, *res, error);
  5877. ASSERT_TRUE(ret);
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. }
  5880. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5881. auto res = cli_.Get("/remote_addr");
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5885. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5886. }
  5887. TEST_F(ServerTest, GetMethodLocalAddr) {
  5888. auto res = cli_.Get("/local_addr");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::OK_200, res->status);
  5891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5892. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5893. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5894. }
  5895. TEST_F(ServerTest, HTTPResponseSplitting) {
  5896. auto res = cli_.Get("/http_response_splitting");
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. }
  5900. TEST_F(ServerTest, SlowRequest) {
  5901. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5902. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5903. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5904. }
  5905. #if 0
  5906. TEST_F(ServerTest, SlowPost) {
  5907. char buffer[64 * 1024];
  5908. memset(buffer, 0x42, sizeof(buffer));
  5909. auto res = cli_.Post(
  5910. "/slowpost", 64 * 1024 * 1024,
  5911. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5912. auto ret = sink.write(buffer, sizeof(buffer));
  5913. EXPECT_TRUE(ret);
  5914. return true;
  5915. },
  5916. "text/plain");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. }
  5920. TEST_F(ServerTest, SlowPostFail) {
  5921. char buffer[64 * 1024];
  5922. memset(buffer, 0x42, sizeof(buffer));
  5923. cli_.set_write_timeout(std::chrono::seconds(0));
  5924. auto res = cli_.Post(
  5925. "/slowpost", 64 * 1024 * 1024,
  5926. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5927. sink.write(buffer, sizeof(buffer));
  5928. return true;
  5929. },
  5930. "text/plain");
  5931. ASSERT_TRUE(!res);
  5932. EXPECT_EQ(Error::Write, res.error());
  5933. }
  5934. #endif
  5935. TEST_F(ServerTest, Put) {
  5936. auto res = cli_.Put("/put", "PUT", "text/plain");
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("PUT", res->body);
  5940. }
  5941. TEST_F(ServerTest, PutWithContentProvider) {
  5942. auto res = cli_.Put(
  5943. "/put", 3,
  5944. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5945. sink.os << "PUT";
  5946. return true;
  5947. },
  5948. "text/plain");
  5949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5950. EXPECT_EQ(StatusCode::OK_200, res->status);
  5951. EXPECT_EQ("PUT", res->body);
  5952. }
  5953. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5954. auto res = cli_.Post(
  5955. "/post", 42,
  5956. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5957. return false;
  5958. },
  5959. "text/plain");
  5960. ASSERT_TRUE(!res);
  5961. EXPECT_EQ(Error::Canceled, res.error());
  5962. }
  5963. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5964. auto res = cli_.Put(
  5965. "/put",
  5966. [](size_t /*offset*/, DataSink &sink) {
  5967. sink.os << "PUT";
  5968. sink.done();
  5969. return true;
  5970. },
  5971. "text/plain");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ("PUT", res->body);
  5975. }
  5976. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5977. auto res = cli_.Post(
  5978. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5979. "text/plain");
  5980. ASSERT_TRUE(!res);
  5981. EXPECT_EQ(Error::Canceled, res.error());
  5982. }
  5983. TEST_F(ServerTest, PostLoopBack) {
  5984. std::string body;
  5985. auto res = cli_.Post(
  5986. "/post-loopback", 9,
  5987. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5988. EXPECT_EQ(9u, length);
  5989. sink.write("123", 3);
  5990. sink.write("456", 3);
  5991. sink.write("789", 3);
  5992. return true;
  5993. },
  5994. "text/plain",
  5995. [&body](const char *data, size_t data_length) {
  5996. body.append(data, data_length);
  5997. return true;
  5998. });
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("123456789", body);
  6002. }
  6003. TEST_F(ServerTest, PutLoopBack) {
  6004. std::string body;
  6005. auto res = cli_.Put(
  6006. "/put-loopback", 9,
  6007. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6008. EXPECT_EQ(9u, length);
  6009. sink.write("123", 3);
  6010. sink.write("456", 3);
  6011. sink.write("789", 3);
  6012. return true;
  6013. },
  6014. "text/plain",
  6015. [&body](const char *data, size_t data_length) {
  6016. body.append(data, data_length);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. EXPECT_EQ("123456789", body);
  6022. }
  6023. TEST_F(ServerTest, PatchLoopBack) {
  6024. std::string body;
  6025. auto res = cli_.Patch(
  6026. "/patch-loopback", 9,
  6027. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6028. EXPECT_EQ(9u, length);
  6029. sink.write("123", 3);
  6030. sink.write("456", 3);
  6031. sink.write("789", 3);
  6032. return true;
  6033. },
  6034. "text/plain",
  6035. [&body](const char *data, size_t data_length) {
  6036. body.append(data, data_length);
  6037. return true;
  6038. });
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_EQ("123456789", body);
  6042. }
  6043. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6044. std::string body;
  6045. auto res = cli_.Post(
  6046. "/post-loopback",
  6047. [](size_t /*offset*/, DataSink &sink) {
  6048. sink.write("123", 3);
  6049. sink.write("456", 3);
  6050. sink.write("789", 3);
  6051. sink.done();
  6052. return true;
  6053. },
  6054. "text/plain",
  6055. [&body](const char *data, size_t data_length) {
  6056. body.append(data, data_length);
  6057. return true;
  6058. });
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::OK_200, res->status);
  6061. EXPECT_EQ("123456789", body);
  6062. }
  6063. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6064. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6065. cli_.set_compress(true);
  6066. auto res = cli_.Put(
  6067. "/put", 3,
  6068. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6069. sink.os << "PUT";
  6070. return true;
  6071. },
  6072. "text/plain");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::OK_200, res->status);
  6075. EXPECT_EQ("PUT", res->body);
  6076. }
  6077. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6078. cli_.set_compress(true);
  6079. auto res = cli_.Post(
  6080. "/post", 42,
  6081. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6082. return false;
  6083. },
  6084. "text/plain");
  6085. ASSERT_TRUE(!res);
  6086. EXPECT_EQ(Error::Canceled, res.error());
  6087. }
  6088. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6089. cli_.set_compress(true);
  6090. auto res = cli_.Put(
  6091. "/put",
  6092. [](size_t /*offset*/, DataSink &sink) {
  6093. sink.os << "PUT";
  6094. sink.done();
  6095. return true;
  6096. },
  6097. "text/plain");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("PUT", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6103. cli_.set_compress(true);
  6104. auto res = cli_.Post(
  6105. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6106. "text/plain");
  6107. ASSERT_TRUE(!res);
  6108. EXPECT_EQ(Error::Canceled, res.error());
  6109. }
  6110. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6111. cli_.set_compress(true);
  6112. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::OK_200, res->status);
  6115. EXPECT_EQ(LARGE_DATA, res->body);
  6116. }
  6117. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6118. #ifdef CPPHTTPLIB_SSL_ENABLED
  6119. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6120. Client cli(s.c_str());
  6121. cli.enable_server_certificate_verification(false);
  6122. #else
  6123. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6124. Client cli(s.c_str());
  6125. #endif
  6126. cli.set_compress(true);
  6127. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. EXPECT_EQ(StatusCode::OK_200, res->status);
  6130. EXPECT_EQ(LARGE_DATA, res->body);
  6131. // The compressed size should be less than a 10th of the original. May vary
  6132. // depending on the zlib library.
  6133. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6134. static_cast<uint64_t>(10 * 1024 * 1024));
  6135. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6136. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6137. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6138. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6139. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6140. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6141. #endif
  6142. }
  6143. TEST_F(ServerTest, PutContentWithDeflate) {
  6144. cli_.set_compress(false);
  6145. Headers headers;
  6146. headers.emplace("Content-Encoding", "deflate");
  6147. // PUT in deflate format:
  6148. auto res = cli_.Put("/put", headers,
  6149. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. EXPECT_EQ("PUT", res->body);
  6153. }
  6154. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6155. Headers headers;
  6156. headers.emplace("Accept-Encoding", "gzip, deflate");
  6157. auto res = cli_.Get("/streamed-chunked", headers);
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. EXPECT_EQ(std::string("123456789"), res->body);
  6161. }
  6162. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6163. Headers headers;
  6164. headers.emplace("Accept-Encoding", "gzip, deflate");
  6165. auto res = cli_.Get("/streamed-chunked2", headers);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. EXPECT_EQ(std::string("123456789"), res->body);
  6169. }
  6170. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6171. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::OK_200, res->status);
  6174. }
  6175. TEST(GzipDecompressor, ChunkedDecompression) {
  6176. std::string data;
  6177. for (size_t i = 0; i < 32 * 1024; ++i) {
  6178. data.push_back(static_cast<char>('a' + i % 26));
  6179. }
  6180. std::string compressed_data;
  6181. {
  6182. httplib::detail::gzip_compressor compressor;
  6183. bool result = compressor.compress(
  6184. data.data(), data.size(),
  6185. /*last=*/true,
  6186. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6187. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6188. compressed_data_size);
  6189. return true;
  6190. });
  6191. ASSERT_TRUE(result);
  6192. }
  6193. std::string decompressed_data;
  6194. {
  6195. httplib::detail::gzip_decompressor decompressor;
  6196. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6197. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6198. size_t chunk_size = 130;
  6199. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6200. chunk_begin += chunk_size) {
  6201. size_t current_chunk_size =
  6202. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6203. bool result = decompressor.decompress(
  6204. compressed_data.data() + chunk_begin, current_chunk_size,
  6205. [&](const char *decompressed_data_chunk,
  6206. size_t decompressed_data_chunk_size) {
  6207. decompressed_data.insert(decompressed_data.size(),
  6208. decompressed_data_chunk,
  6209. decompressed_data_chunk_size);
  6210. return true;
  6211. });
  6212. ASSERT_TRUE(result);
  6213. }
  6214. }
  6215. ASSERT_EQ(data, decompressed_data);
  6216. }
  6217. TEST(GzipDecompressor, DeflateDecompression) {
  6218. std::string original_text = "Raw deflate without gzip";
  6219. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6220. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6221. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6222. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6223. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6224. std::string decompressed_data;
  6225. {
  6226. httplib::detail::gzip_decompressor decompressor;
  6227. bool result = decompressor.decompress(
  6228. compressed_data.data(), compressed_data.size(),
  6229. [&](const char *decompressed_data_chunk,
  6230. size_t decompressed_data_chunk_size) {
  6231. decompressed_data.insert(decompressed_data.size(),
  6232. decompressed_data_chunk,
  6233. decompressed_data_chunk_size);
  6234. return true;
  6235. });
  6236. ASSERT_TRUE(result);
  6237. }
  6238. ASSERT_EQ(original_text, decompressed_data);
  6239. }
  6240. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6241. std::string original_text = "Raw deflate without gzip";
  6242. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6243. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6244. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6245. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6246. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6247. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6248. std::string decompressed_data;
  6249. {
  6250. httplib::detail::gzip_decompressor decompressor;
  6251. bool result = decompressor.decompress(
  6252. compressed_data.data(), compressed_data.size(),
  6253. [&](const char *decompressed_data_chunk,
  6254. size_t decompressed_data_chunk_size) {
  6255. decompressed_data.insert(decompressed_data.size(),
  6256. decompressed_data_chunk,
  6257. decompressed_data_chunk_size);
  6258. return true;
  6259. });
  6260. ASSERT_TRUE(result);
  6261. }
  6262. ASSERT_EQ(original_text, decompressed_data);
  6263. }
  6264. #endif
  6265. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6266. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6267. Headers headers;
  6268. headers.emplace("Accept-Encoding", "br");
  6269. auto res = cli_.Get("/streamed-chunked", headers);
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. EXPECT_EQ(std::string("123456789"), res->body);
  6273. }
  6274. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6275. Headers headers;
  6276. headers.emplace("Accept-Encoding", "br");
  6277. auto res = cli_.Get("/streamed-chunked2", headers);
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ(std::string("123456789"), res->body);
  6281. }
  6282. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6283. cli_.set_compress(true);
  6284. auto res = cli_.Put(
  6285. "/put", 3,
  6286. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6287. sink.os << "PUT";
  6288. return true;
  6289. },
  6290. "text/plain");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ("PUT", res->body);
  6294. }
  6295. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6296. cli_.set_compress(true);
  6297. auto res = cli_.Put(
  6298. "/put",
  6299. [](size_t /*offset*/, DataSink &sink) {
  6300. sink.os << "PUT";
  6301. sink.done();
  6302. return true;
  6303. },
  6304. "text/plain");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ("PUT", res->body);
  6308. }
  6309. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6310. cli_.set_compress(true);
  6311. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ(LARGE_DATA, res->body);
  6315. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6316. }
  6317. #endif
  6318. TEST_F(ServerTest, Patch) {
  6319. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ("PATCH", res->body);
  6323. }
  6324. TEST_F(ServerTest, Delete) {
  6325. auto res = cli_.Delete("/delete");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. EXPECT_EQ("DELETE", res->body);
  6329. }
  6330. TEST_F(ServerTest, DeleteContentReceiver) {
  6331. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. EXPECT_EQ("content", res->body);
  6335. }
  6336. TEST_F(ServerTest, Options) {
  6337. auto res = cli_.Options("*");
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6341. EXPECT_TRUE(res->body.empty());
  6342. }
  6343. TEST_F(ServerTest, URL) {
  6344. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. }
  6348. TEST_F(ServerTest, ArrayParam) {
  6349. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST_F(ServerTest, ArrayParamValues) {
  6354. auto res =
  6355. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. }
  6359. TEST_F(ServerTest, NoMultipleHeaders) {
  6360. Headers headers = {{"Content-Length", "5"}};
  6361. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6362. "text/plain");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::OK_200, res->status);
  6365. }
  6366. TEST_F(ServerTest, PostContentReceiver) {
  6367. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. ASSERT_EQ(StatusCode::OK_200, res->status);
  6370. ASSERT_EQ("content", res->body);
  6371. }
  6372. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6373. UploadFormDataItems items = {
  6374. {"text1", "text default", "", ""},
  6375. {"text2", "aωb", "", ""},
  6376. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6377. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6378. {"file3", "", "", "application/octet-stream"},
  6379. };
  6380. auto res = cli_.Post("/content_receiver", items);
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. }
  6384. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6385. UploadFormDataItems items = {
  6386. {"text1", "text default", "", ""},
  6387. {"text2", "aωb", "", ""},
  6388. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6389. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6390. {"file3", "", "", "application/octet-stream"},
  6391. };
  6392. auto boundary = std::string("+++++");
  6393. std::string body;
  6394. for (const auto &item : items) {
  6395. body += "--" + boundary + "\r\n";
  6396. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6397. if (!item.filename.empty()) {
  6398. body += "; filename=\"" + item.filename + "\"";
  6399. }
  6400. body += "\r\n";
  6401. if (!item.content_type.empty()) {
  6402. body += "Content-Type: " + item.content_type + "\r\n";
  6403. }
  6404. body += "\r\n";
  6405. body += item.content + "\r\n";
  6406. }
  6407. body += "--" + boundary + "--\r\n";
  6408. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6409. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::OK_200, res->status);
  6412. }
  6413. TEST(MultipartFormDataTest, FieldEscaping) {
  6414. Server svr;
  6415. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6416. const ContentReader &content_reader) {
  6417. ASSERT_TRUE(req.is_multipart_form_data());
  6418. std::vector<FormData> received;
  6419. content_reader(
  6420. [&](const FormData &file) {
  6421. received.push_back(file);
  6422. return true;
  6423. },
  6424. [&](const char *data, size_t data_length) {
  6425. received.back().content.append(data, data_length);
  6426. return true;
  6427. });
  6428. // '"', CR and LF in names and filenames are escaped following the
  6429. // WHATWG HTML standard, so each part still parses as a single part
  6430. // with no injected headers. Content types get CR/LF escaped too,
  6431. // while '"' (legal there, e.g. quoted charset) is preserved.
  6432. ASSERT_EQ(4U, received.size());
  6433. EXPECT_EQ("na%22me", received[0].name);
  6434. EXPECT_EQ("quoted name", received[0].content);
  6435. EXPECT_EQ("file", received[1].name);
  6436. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6437. received[1].filename);
  6438. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6439. EXPECT_EQ("injected", received[1].content);
  6440. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6441. EXPECT_EQ("my%22file.txt", received[2].filename);
  6442. EXPECT_EQ("cr lf name", received[2].content);
  6443. EXPECT_EQ("typed", received[3].name);
  6444. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6445. received[3].content_type);
  6446. EXPECT_EQ("typed content", received[3].content);
  6447. });
  6448. auto port = svr.bind_to_any_port("localhost");
  6449. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6450. auto se = detail::scope_exit([&] {
  6451. svr.stop();
  6452. t.join();
  6453. ASSERT_FALSE(svr.is_running());
  6454. });
  6455. svr.wait_until_ready();
  6456. Client cli("localhost", port);
  6457. UploadFormDataItems items = {
  6458. {"na\"me", "quoted name", "", ""},
  6459. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6460. "application/octet-stream"},
  6461. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6462. {"typed", "typed content", "",
  6463. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6464. };
  6465. auto res = cli.Post("/post", items);
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. }
  6469. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6470. const UploadFormDataItems items = {
  6471. {"name1", "Content 1", "", ""},
  6472. {"name2", "Content 2", "file2.txt", "text/plain"},
  6473. };
  6474. Server svr;
  6475. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6476. const ContentReader &content_reader) {
  6477. ASSERT_TRUE(req.is_multipart_form_data());
  6478. std::vector<FormData> received;
  6479. content_reader(
  6480. [&](const FormData &file) {
  6481. received.push_back(file);
  6482. return true;
  6483. },
  6484. [&](const char *data, size_t data_length) {
  6485. received.back().content.append(data, data_length);
  6486. return true;
  6487. });
  6488. ASSERT_EQ(2U, received.size());
  6489. EXPECT_EQ("name1", received[0].name);
  6490. EXPECT_EQ("Content 1", received[0].content);
  6491. EXPECT_EQ("name2", received[1].name);
  6492. EXPECT_EQ("Content 2", received[1].content);
  6493. EXPECT_EQ("file2.txt", received[1].filename);
  6494. EXPECT_EQ("text/plain", received[1].content_type);
  6495. });
  6496. auto port = svr.bind_to_any_port("localhost");
  6497. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. t.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. Client cli("localhost", port);
  6505. // Whole-body serialization with a generated boundary
  6506. {
  6507. MultipartFormDataWriter writer;
  6508. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6509. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6510. writer.content_type());
  6511. auto body = writer.serialize(items);
  6512. EXPECT_EQ(body.size(), writer.content_length(items));
  6513. auto res = cli.Post("/post", body, writer.content_type());
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::OK_200, res->status);
  6516. }
  6517. // Per-part framing with a custom boundary via a content provider
  6518. {
  6519. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6520. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6521. MultipartFormDataWriter writer("custom-boundary_123");
  6522. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6523. std::string body;
  6524. for (const auto &item : items) {
  6525. body += writer.item_begin(item);
  6526. body += item.content;
  6527. body += MultipartFormDataWriter::item_end();
  6528. }
  6529. body += writer.finish();
  6530. EXPECT_EQ(body.size(), writer.content_length(items));
  6531. auto res = cli.Post(
  6532. "/post", body.size(),
  6533. [&](size_t offset, size_t length, DataSink &sink) {
  6534. sink.write(body.data() + offset, length);
  6535. return true;
  6536. },
  6537. writer.content_type());
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. }
  6541. }
  6542. TEST_F(ServerTest, PostContentReceiverGzip) {
  6543. cli_.set_compress(true);
  6544. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. ASSERT_EQ(StatusCode::OK_200, res->status);
  6547. ASSERT_EQ("content", res->body);
  6548. }
  6549. TEST_F(ServerTest, PutContentReceiver) {
  6550. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. ASSERT_EQ(StatusCode::OK_200, res->status);
  6553. ASSERT_EQ("content", res->body);
  6554. }
  6555. TEST_F(ServerTest, PatchContentReceiver) {
  6556. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. ASSERT_EQ(StatusCode::OK_200, res->status);
  6559. ASSERT_EQ("content", res->body);
  6560. }
  6561. template <typename ClientType>
  6562. void TestWithHeadersAndContentReceiver(
  6563. ClientType &cli,
  6564. std::function<Result(ClientType &, const std::string &, const Headers &,
  6565. const std::string &, const std::string &,
  6566. ContentReceiver, DownloadProgress)>
  6567. request_func) {
  6568. Headers headers;
  6569. headers.emplace("X-Custom-Header", "test-value");
  6570. std::string received_body;
  6571. auto res = request_func(
  6572. cli, "/content_receiver", headers, "content", "application/json",
  6573. [&](const char *data, size_t data_length) {
  6574. received_body.append(data, data_length);
  6575. return true;
  6576. },
  6577. nullptr);
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::OK_200, res->status);
  6580. EXPECT_EQ("content", received_body);
  6581. }
  6582. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6583. #ifdef CPPHTTPLIB_SSL_ENABLED
  6584. using ClientT = SSLClient;
  6585. #else
  6586. using ClientT = Client;
  6587. #endif
  6588. TestWithHeadersAndContentReceiver<ClientT>(
  6589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6590. const std::string &body, const std::string &content_type,
  6591. ContentReceiver receiver, DownloadProgress progress) {
  6592. return cli.Post(path, headers, body, content_type, receiver, progress);
  6593. });
  6594. }
  6595. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6596. #ifdef CPPHTTPLIB_SSL_ENABLED
  6597. using ClientT = SSLClient;
  6598. #else
  6599. using ClientT = Client;
  6600. #endif
  6601. TestWithHeadersAndContentReceiver<ClientT>(
  6602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6603. const std::string &body, const std::string &content_type,
  6604. ContentReceiver receiver, DownloadProgress progress) {
  6605. return cli.Put(path, headers, body, content_type, receiver, progress);
  6606. });
  6607. }
  6608. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6609. #ifdef CPPHTTPLIB_SSL_ENABLED
  6610. using ClientT = SSLClient;
  6611. #else
  6612. using ClientT = Client;
  6613. #endif
  6614. TestWithHeadersAndContentReceiver<ClientT>(
  6615. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6616. const std::string &body, const std::string &content_type,
  6617. ContentReceiver receiver, DownloadProgress progress) {
  6618. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6619. });
  6620. }
  6621. template <typename ClientType>
  6622. void TestWithHeadersAndContentReceiverWithProgress(
  6623. ClientType &cli,
  6624. std::function<Result(ClientType &, const std::string &, const Headers &,
  6625. const std::string &, const std::string &,
  6626. ContentReceiver, DownloadProgress)>
  6627. request_func) {
  6628. Headers headers;
  6629. headers.emplace("X-Test-Header", "progress-test");
  6630. std::string received_body;
  6631. auto progress_called = false;
  6632. auto res = request_func(
  6633. cli, "/content_receiver", headers, "content", "text/plain",
  6634. [&](const char *data, size_t data_length) {
  6635. received_body.append(data, data_length);
  6636. return true;
  6637. },
  6638. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6639. progress_called = true;
  6640. return true;
  6641. });
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("content", received_body);
  6645. EXPECT_TRUE(progress_called);
  6646. }
  6647. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6648. #ifdef CPPHTTPLIB_SSL_ENABLED
  6649. using ClientT = SSLClient;
  6650. #else
  6651. using ClientT = Client;
  6652. #endif
  6653. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6654. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6655. const std::string &body, const std::string &content_type,
  6656. ContentReceiver receiver, DownloadProgress progress) {
  6657. return cli.Post(path, headers, body, content_type, receiver, progress);
  6658. });
  6659. }
  6660. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6661. #ifdef CPPHTTPLIB_SSL_ENABLED
  6662. using ClientT = SSLClient;
  6663. #else
  6664. using ClientT = Client;
  6665. #endif
  6666. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6667. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6668. const std::string &body, const std::string &content_type,
  6669. ContentReceiver receiver, DownloadProgress progress) {
  6670. return cli.Put(path, headers, body, content_type, receiver, progress);
  6671. });
  6672. }
  6673. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6674. #ifdef CPPHTTPLIB_SSL_ENABLED
  6675. using ClientT = SSLClient;
  6676. #else
  6677. using ClientT = Client;
  6678. #endif
  6679. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6680. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6681. const std::string &body, const std::string &content_type,
  6682. ContentReceiver receiver, DownloadProgress progress) {
  6683. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6684. });
  6685. }
  6686. template <typename ClientType>
  6687. void TestWithHeadersAndContentReceiverError(
  6688. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6689. const Headers &, const std::string &,
  6690. const std::string &, ContentReceiver)>
  6691. request_func) {
  6692. Headers headers;
  6693. headers.emplace("X-Error-Test", "true");
  6694. std::string received_body;
  6695. auto receiver_failed = false;
  6696. auto res =
  6697. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6698. [&](const char *data, size_t data_length) {
  6699. received_body.append(data, data_length);
  6700. receiver_failed = true;
  6701. return false;
  6702. });
  6703. ASSERT_FALSE(res);
  6704. EXPECT_TRUE(receiver_failed);
  6705. }
  6706. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6707. #ifdef CPPHTTPLIB_SSL_ENABLED
  6708. using ClientT = SSLClient;
  6709. #else
  6710. using ClientT = Client;
  6711. #endif
  6712. TestWithHeadersAndContentReceiverError<ClientT>(
  6713. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6714. const std::string &body, const std::string &content_type,
  6715. ContentReceiver receiver) {
  6716. return cli.Post(path, headers, body, content_type, receiver);
  6717. });
  6718. }
  6719. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6720. #ifdef CPPHTTPLIB_SSL_ENABLED
  6721. using ClientT = SSLClient;
  6722. #else
  6723. using ClientT = Client;
  6724. #endif
  6725. TestWithHeadersAndContentReceiverError<ClientT>(
  6726. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6727. const std::string &body, const std::string &content_type,
  6728. ContentReceiver receiver) {
  6729. return cli.Put(path, headers, body, content_type, receiver);
  6730. });
  6731. }
  6732. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6733. #ifdef CPPHTTPLIB_SSL_ENABLED
  6734. using ClientT = SSLClient;
  6735. #else
  6736. using ClientT = Client;
  6737. #endif
  6738. TestWithHeadersAndContentReceiverError<ClientT>(
  6739. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6740. const std::string &body, const std::string &content_type,
  6741. ContentReceiver receiver) {
  6742. return cli.Patch(path, headers, body, content_type, receiver);
  6743. });
  6744. }
  6745. TEST_F(ServerTest, PostQueryStringAndBody) {
  6746. auto res =
  6747. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. ASSERT_EQ(StatusCode::OK_200, res->status);
  6750. }
  6751. TEST_F(ServerTest, HTTP2Magic) {
  6752. Request req;
  6753. req.method = "PRI";
  6754. req.path = "*";
  6755. req.body = "SM";
  6756. auto res = std::make_shared<Response>();
  6757. auto error = Error::Success;
  6758. auto ret = cli_.send(req, *res, error);
  6759. ASSERT_TRUE(ret);
  6760. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6761. }
  6762. TEST_F(ServerTest, KeepAlive) {
  6763. auto res = cli_.Get("/hi");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6767. EXPECT_EQ("Hello World!", res->body);
  6768. res = cli_.Get("/hi");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6772. EXPECT_EQ("Hello World!", res->body);
  6773. res = cli_.Get("/hi");
  6774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6775. EXPECT_EQ(StatusCode::OK_200, res->status);
  6776. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6777. EXPECT_EQ("Hello World!", res->body);
  6778. res = cli_.Get("/not-exist");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6781. res = cli_.Post("/empty", "", "text/plain");
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6785. EXPECT_EQ("empty", res->body);
  6786. EXPECT_EQ("close", res->get_header_value("Connection"));
  6787. res = cli_.Post(
  6788. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6789. "text/plain");
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(StatusCode::OK_200, res->status);
  6792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("empty", res->body);
  6794. cli_.set_keep_alive(false);
  6795. res = cli_.Get("/last-request");
  6796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. EXPECT_EQ("close", res->get_header_value("Connection"));
  6799. }
  6800. TEST_F(ServerTest, TooManyRedirect) {
  6801. cli_.set_follow_location(true);
  6802. auto res = cli_.Get("/redirect/0");
  6803. ASSERT_TRUE(!res);
  6804. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6805. }
  6806. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6807. Request req;
  6808. req.method = "FOOBAR";
  6809. req.path = "/hi";
  6810. cli_.set_keep_alive(true);
  6811. auto res = cli_.send(req);
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6814. EXPECT_EQ("close", res->get_header_value("Connection"));
  6815. EXPECT_FALSE(cli_.is_socket_open());
  6816. }
  6817. TEST_F(ServerTest, CustomRouteReadsBody) {
  6818. const std::string xml =
  6819. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  6820. Request req;
  6821. req.method = "PROPFIND";
  6822. req.path = "/dav/dir";
  6823. req.set_header("Depth", "1");
  6824. req.body = xml;
  6825. auto res = cli_.send(req);
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6828. EXPECT_EQ(xml, res->body);
  6829. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  6830. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  6831. }
  6832. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  6833. Request req;
  6834. req.method = "PROPFIND";
  6835. req.path = "/dav/42";
  6836. auto res = cli_.send(req);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6839. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  6840. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  6841. }
  6842. TEST_F(ServerTest, CustomRouteRegexPattern) {
  6843. Request req;
  6844. req.method = "PROPFIND";
  6845. req.path = "/dav-re/123";
  6846. auto res = cli_.send(req);
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6849. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  6850. }
  6851. TEST_F(ServerTest, CustomRouteWithoutBody) {
  6852. Request req;
  6853. req.method = "MKCOL";
  6854. req.path = "/dav-mkcol";
  6855. auto res = cli_.send(req);
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::Created_201, res->status);
  6858. }
  6859. TEST_F(ServerTest, CustomRouteWithContentReader) {
  6860. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  6861. Request req;
  6862. req.method = "REPORT";
  6863. req.path = "/dav-report";
  6864. req.body = xml;
  6865. auto res = cli_.send(req);
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6868. EXPECT_EQ(xml, res->body);
  6869. }
  6870. // A content reader route must fire even when the request carries no body,
  6871. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  6872. // Without that, a body-less PROPFIND-style request would fall through to 404.
  6873. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  6874. Request req;
  6875. req.method = "REPORT";
  6876. req.path = "/dav-report";
  6877. auto res = cli_.send(req);
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6880. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  6881. }
  6882. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  6883. Request req;
  6884. req.method = "PROPFIND";
  6885. req.path = "/not-dav";
  6886. auto res = cli_.send(req);
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6889. }
  6890. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  6891. Request req;
  6892. req.method = "UNLOCK";
  6893. req.path = "/dav/dir";
  6894. cli_.set_keep_alive(true);
  6895. auto res = cli_.send(req);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6898. EXPECT_EQ("close", res->get_header_value("Connection"));
  6899. EXPECT_FALSE(cli_.is_socket_open());
  6900. }
  6901. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  6902. // The mount point serves this path, but only for GET and HEAD.
  6903. auto get_res = cli_.Get("/dir/index.html");
  6904. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  6906. Request req;
  6907. req.method = "PROPFIND";
  6908. req.path = "/dir/index.html";
  6909. auto res = cli_.send(req);
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6912. }
  6913. TEST_F(ServerTest, CustomRouteKeepAlive) {
  6914. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6915. cli_.set_keep_alive(true);
  6916. for (auto i = 0; i < 2; i++) {
  6917. Request req;
  6918. req.method = "PROPFIND";
  6919. req.path = "/dav/dir";
  6920. req.body = xml;
  6921. auto res = cli_.send(req);
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6924. EXPECT_EQ(xml, res->body);
  6925. EXPECT_TRUE(cli_.is_socket_open());
  6926. }
  6927. // A built-in method must still be served on the same connection.
  6928. cli_.set_keep_alive(false);
  6929. auto res = cli_.Get("/hi");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ("close", res->get_header_value("Connection"));
  6933. }
  6934. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  6935. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6936. Request req;
  6937. req.method = "PROPFIND";
  6938. req.path = "/dav/dir";
  6939. req.set_header("Expect", "100-continue");
  6940. req.body = xml;
  6941. auto res = cli_.send(req);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6944. EXPECT_EQ(xml, res->body);
  6945. }
  6946. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6947. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6948. TEST_F(ServerTest, Gzip) {
  6949. Headers headers;
  6950. headers.emplace("Accept-Encoding", "gzip, deflate");
  6951. auto res = cli_.Get("/compress", headers);
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6955. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6956. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6957. "7890123456789012345678901234567890",
  6958. res->body);
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. }
  6961. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6962. Headers headers;
  6963. headers.emplace("Accept-Encoding", "gzip, deflate");
  6964. auto res = cli_.Get("/compress-with-charset", headers);
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6967. EXPECT_EQ("application/json; charset=utf-8",
  6968. res->get_header_value("Content-Type"));
  6969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6970. "7890123456789012345678901234567890",
  6971. res->body);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6975. Headers headers;
  6976. headers.emplace("Accept-Encoding", "");
  6977. auto res = cli_.Get("/compress", headers);
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6981. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6983. "7890123456789012345678901234567890",
  6984. res->body);
  6985. EXPECT_EQ(StatusCode::OK_200, res->status);
  6986. }
  6987. TEST_F(ServerTest, GzipWithContentReceiver) {
  6988. Headers headers;
  6989. headers.emplace("Accept-Encoding", "gzip, deflate");
  6990. std::string body;
  6991. auto res = cli_.Get("/compress", headers,
  6992. [&](const char *data, uint64_t data_length) {
  6993. EXPECT_EQ(100U, data_length);
  6994. body.append(data, data_length);
  6995. return true;
  6996. });
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7000. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7001. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7002. "7890123456789012345678901234567890",
  7003. body);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. }
  7006. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7007. Headers headers;
  7008. headers.emplace("Accept-Encoding", "gzip, deflate");
  7009. cli_.set_decompress(false);
  7010. auto res = cli_.Get("/compress", headers);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7013. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7014. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7015. EXPECT_EQ(33U, res->body.size());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7019. Headers headers;
  7020. headers.emplace("Accept-Encoding", "");
  7021. std::string body;
  7022. auto res = cli_.Get("/compress", headers,
  7023. [&](const char *data, uint64_t data_length) {
  7024. EXPECT_EQ(100U, data_length);
  7025. body.append(data, data_length);
  7026. return true;
  7027. });
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7031. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7032. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7033. "7890123456789012345678901234567890",
  7034. body);
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, NoGzip) {
  7038. Headers headers;
  7039. headers.emplace("Accept-Encoding", "gzip, deflate");
  7040. auto res = cli_.Get("/nocompress", headers);
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7043. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7044. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7045. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7046. "7890123456789012345678901234567890",
  7047. res->body);
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. }
  7050. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7051. Headers headers;
  7052. headers.emplace("Accept-Encoding", "gzip, deflate");
  7053. std::string body;
  7054. auto res = cli_.Get("/nocompress", headers,
  7055. [&](const char *data, uint64_t data_length) {
  7056. EXPECT_EQ(100U, data_length);
  7057. body.append(data, data_length);
  7058. return true;
  7059. });
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7062. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7063. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7064. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7065. "7890123456789012345678901234567890",
  7066. body);
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. }
  7069. TEST_F(ServerTest, MultipartFormDataGzip) {
  7070. UploadFormDataItems items = {
  7071. {"key1", "test", "", ""},
  7072. {"key2", "--abcdefg123", "", ""},
  7073. };
  7074. cli_.set_compress(true);
  7075. auto res = cli_.Post("/compress-multipart", items);
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. #endif
  7080. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7081. TEST_F(ServerTest, Brotli) {
  7082. Headers headers;
  7083. headers.emplace("Accept-Encoding", "br");
  7084. auto res = cli_.Get("/compress", headers);
  7085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7086. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7088. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7089. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7090. "7890123456789012345678901234567890",
  7091. res->body);
  7092. EXPECT_EQ(StatusCode::OK_200, res->status);
  7093. }
  7094. #endif
  7095. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7096. TEST_F(ServerTest, Zstd) {
  7097. Headers headers;
  7098. headers.emplace("Accept-Encoding", "zstd");
  7099. auto res = cli_.Get("/compress", headers);
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7103. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7105. "7890123456789012345678901234567890",
  7106. res->body);
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. }
  7109. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7110. Headers headers;
  7111. headers.emplace("Accept-Encoding", "");
  7112. auto res = cli_.Get("/compress", headers);
  7113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7114. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7116. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7117. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7118. "7890123456789012345678901234567890",
  7119. res->body);
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. }
  7122. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7123. Headers headers;
  7124. headers.emplace("Accept-Encoding", "zstd");
  7125. std::string body;
  7126. auto res = cli_.Get("/compress", headers,
  7127. [&](const char *data, uint64_t data_length) {
  7128. EXPECT_EQ(100U, data_length);
  7129. body.append(data, data_length);
  7130. return true;
  7131. });
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7135. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7136. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7137. "7890123456789012345678901234567890",
  7138. body);
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. }
  7141. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7142. Headers headers;
  7143. headers.emplace("Accept-Encoding", "zstd");
  7144. cli_.set_decompress(false);
  7145. auto res = cli_.Get("/compress", headers);
  7146. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7147. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7148. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7149. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7153. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. ASSERT_EQ(26U, res->body.size());
  7156. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7157. 0);
  7158. }
  7159. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7160. Headers headers;
  7161. headers.emplace("Accept-Encoding", "");
  7162. std::string body;
  7163. auto res = cli_.Get("/compress", headers,
  7164. [&](const char *data, uint64_t data_length) {
  7165. EXPECT_EQ(100U, data_length);
  7166. body.append(data, data_length);
  7167. return true;
  7168. });
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7172. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7174. "7890123456789012345678901234567890",
  7175. body);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. }
  7178. TEST_F(ServerTest, NoZstd) {
  7179. Headers headers;
  7180. headers.emplace("Accept-Encoding", "zstd");
  7181. auto res = cli_.Get("/nocompress", headers);
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7184. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7185. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7186. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7187. "7890123456789012345678901234567890",
  7188. res->body);
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. }
  7191. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7192. Headers headers;
  7193. headers.emplace("Accept-Encoding", "zstd");
  7194. std::string body;
  7195. auto res = cli_.Get("/nocompress", headers,
  7196. [&](const char *data, uint64_t data_length) {
  7197. EXPECT_EQ(100U, data_length);
  7198. body.append(data, data_length);
  7199. return true;
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7206. "7890123456789012345678901234567890",
  7207. body);
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. // TODO: How to enable zstd ??
  7211. TEST_F(ServerTest, MultipartFormDataZstd) {
  7212. UploadFormDataItems items = {
  7213. {"key1", "test", "", ""},
  7214. {"key2", "--abcdefg123", "", ""},
  7215. };
  7216. Headers headers;
  7217. headers.emplace("Accept-Encoding", "zstd");
  7218. cli_.set_compress(true);
  7219. auto res = cli_.Post("/compress-multipart", headers, items);
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. }
  7223. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7224. Headers headers;
  7225. headers.emplace("Accept-Encoding", "zstd");
  7226. cli_.set_compress(true);
  7227. auto res = cli_.Put(
  7228. "/put", headers, 3,
  7229. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7230. sink.os << "PUT";
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ("PUT", res->body);
  7237. }
  7238. // Pre-compression logging tests
  7239. TEST_F(ServerTest, PreCompressionLogging) {
  7240. // Test data for compression (matches the actual /compress endpoint content)
  7241. const std::string test_content =
  7242. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7243. "3456789012345678901234567890";
  7244. // Variables to capture logging data
  7245. std::string pre_compression_body;
  7246. std::string pre_compression_content_type;
  7247. std::string pre_compression_content_encoding;
  7248. std::string post_compression_body;
  7249. std::string post_compression_content_type;
  7250. std::string post_compression_content_encoding;
  7251. // Set up pre-compression logger
  7252. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7253. const Response &res) {
  7254. pre_compression_body = res.body;
  7255. pre_compression_content_type = res.get_header_value("Content-Type");
  7256. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7257. });
  7258. // Set up post-compression logger
  7259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7260. post_compression_body = res.body;
  7261. post_compression_content_type = res.get_header_value("Content-Type");
  7262. post_compression_content_encoding =
  7263. res.get_header_value("Content-Encoding");
  7264. });
  7265. // Test with gzip compression
  7266. Headers headers;
  7267. headers.emplace("Accept-Encoding", "gzip");
  7268. auto res = cli_.Get("/compress", headers);
  7269. // Verify response was compressed
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7273. // Verify pre-compression logger captured uncompressed content
  7274. EXPECT_EQ(test_content, pre_compression_body);
  7275. EXPECT_EQ("text/plain", pre_compression_content_type);
  7276. EXPECT_TRUE(pre_compression_content_encoding
  7277. .empty()); // No encoding header before compression
  7278. // Verify post-compression logger captured compressed content
  7279. EXPECT_NE(test_content,
  7280. post_compression_body); // Should be different after compression
  7281. EXPECT_EQ("text/plain", post_compression_content_type);
  7282. EXPECT_EQ("gzip", post_compression_content_encoding);
  7283. // Verify compressed content is smaller
  7284. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7285. }
  7286. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7287. const std::string test_content =
  7288. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7289. "3456789012345678901234567890";
  7290. std::string pre_compression_body;
  7291. std::string post_compression_body;
  7292. svr_.set_pre_compression_logger(
  7293. [&](const Request & /*req*/, const Response &res) {
  7294. pre_compression_body = res.body;
  7295. });
  7296. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7297. post_compression_body = res.body;
  7298. });
  7299. Headers headers;
  7300. headers.emplace("Accept-Encoding", "br");
  7301. auto res = cli_.Get("/compress", headers);
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7305. // Verify pre-compression content is uncompressed
  7306. EXPECT_EQ(test_content, pre_compression_body);
  7307. // Verify post-compression content is compressed
  7308. EXPECT_NE(test_content, post_compression_body);
  7309. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7310. }
  7311. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7312. const std::string test_content =
  7313. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7314. "3456789012345678901234567890";
  7315. std::string pre_compression_body;
  7316. std::string post_compression_body;
  7317. svr_.set_pre_compression_logger(
  7318. [&](const Request & /*req*/, const Response &res) {
  7319. pre_compression_body = res.body;
  7320. });
  7321. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7322. post_compression_body = res.body;
  7323. });
  7324. // Request without compression (use /nocompress endpoint)
  7325. Headers headers;
  7326. auto res = cli_.Get("/nocompress", headers);
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::OK_200, res->status);
  7329. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7330. // Pre-compression logger should not be called when no compression is applied
  7331. EXPECT_TRUE(
  7332. pre_compression_body.empty()); // Pre-compression logger not called
  7333. EXPECT_EQ(
  7334. test_content,
  7335. post_compression_body); // Post-compression logger captures final content
  7336. }
  7337. TEST_F(ServerTest, LoggerSeesContentLength) {
  7338. size_t logged_content_length = 0;
  7339. std::string logged_content_length_header;
  7340. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7341. logged_content_length = res.content_length_;
  7342. logged_content_length_header = res.get_header_value("Content-Length");
  7343. });
  7344. auto res = cli_.Get("/nocompress");
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. EXPECT_EQ(res->body.size(), logged_content_length);
  7348. EXPECT_EQ(std::to_string(logged_content_length),
  7349. logged_content_length_header);
  7350. }
  7351. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7352. const std::string test_content =
  7353. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7354. "3456789012345678901234567890";
  7355. std::string pre_compression_body;
  7356. bool pre_logger_called = false;
  7357. // Set only pre-compression logger
  7358. svr_.set_pre_compression_logger(
  7359. [&](const Request & /*req*/, const Response &res) {
  7360. pre_compression_body = res.body;
  7361. pre_logger_called = true;
  7362. });
  7363. Headers headers;
  7364. headers.emplace("Accept-Encoding", "gzip");
  7365. auto res = cli_.Get("/compress", headers);
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::OK_200, res->status);
  7368. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7369. // Verify pre-compression logger was called
  7370. EXPECT_TRUE(pre_logger_called);
  7371. EXPECT_EQ(test_content, pre_compression_body);
  7372. }
  7373. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7374. {
  7375. // Test with Expect: 100-continue header - success case
  7376. // Server returns 100 Continue, client sends body, server returns 200 OK
  7377. Request req;
  7378. req.method = "POST";
  7379. req.path = "/post-large";
  7380. req.set_header("Expect", "100-continue");
  7381. req.body = LARGE_DATA;
  7382. Response res;
  7383. auto error = Error::Success;
  7384. cli_.set_keep_alive(true);
  7385. auto ret = cli_.send(req, res, error);
  7386. EXPECT_TRUE(ret);
  7387. EXPECT_EQ(StatusCode::OK_200, res.status);
  7388. EXPECT_EQ(LARGE_DATA, res.body);
  7389. }
  7390. {
  7391. // Test with Expect: 100-continue header - error case
  7392. // Client should not send the body when server returns an error
  7393. Request req;
  7394. req.method = "POST";
  7395. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7396. req.set_header("Expect", "100-continue");
  7397. req.body = LARGE_DATA;
  7398. Response res;
  7399. auto error = Error::Success;
  7400. auto start = std::chrono::high_resolution_clock::now();
  7401. cli_.set_keep_alive(true);
  7402. auto ret = cli_.send(req, res, error);
  7403. auto end = std::chrono::high_resolution_clock::now();
  7404. auto elapsed =
  7405. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7406. .count();
  7407. // With Expect: 100-continue, request completes successfully but with error
  7408. EXPECT_TRUE(ret);
  7409. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7410. EXPECT_EQ("close", res.get_header_value("Connection"));
  7411. EXPECT_FALSE(cli_.is_socket_open());
  7412. EXPECT_LE(elapsed, 2000);
  7413. }
  7414. {
  7415. // Send an extra GET request to ensure error recovery without hanging
  7416. Request req;
  7417. req.method = "GET";
  7418. req.path = "/hi";
  7419. auto start = std::chrono::high_resolution_clock::now();
  7420. auto res = cli_.send(req);
  7421. auto end = std::chrono::high_resolution_clock::now();
  7422. auto elapsed =
  7423. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7424. .count();
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("Hello World!", res->body);
  7428. EXPECT_LE(elapsed, 500);
  7429. }
  7430. }
  7431. TEST(ZstdDecompressor, ChunkedDecompression) {
  7432. std::string data;
  7433. for (size_t i = 0; i < 32 * 1024; ++i) {
  7434. data.push_back(static_cast<char>('a' + i % 26));
  7435. }
  7436. std::string compressed_data;
  7437. {
  7438. httplib::detail::zstd_compressor compressor;
  7439. bool result = compressor.compress(
  7440. data.data(), data.size(),
  7441. /*last=*/true,
  7442. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7443. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7444. compressed_data_size);
  7445. return true;
  7446. });
  7447. ASSERT_TRUE(result);
  7448. }
  7449. std::string decompressed_data;
  7450. {
  7451. httplib::detail::zstd_decompressor decompressor;
  7452. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7453. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7454. size_t chunk_size = 130;
  7455. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7456. chunk_begin += chunk_size) {
  7457. size_t current_chunk_size =
  7458. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7459. bool result = decompressor.decompress(
  7460. compressed_data.data() + chunk_begin, current_chunk_size,
  7461. [&](const char *decompressed_data_chunk,
  7462. size_t decompressed_data_chunk_size) {
  7463. decompressed_data.insert(decompressed_data.size(),
  7464. decompressed_data_chunk,
  7465. decompressed_data_chunk_size);
  7466. return true;
  7467. });
  7468. ASSERT_TRUE(result);
  7469. }
  7470. }
  7471. ASSERT_EQ(data, decompressed_data);
  7472. }
  7473. TEST(ZstdDecompressor, Decompress) {
  7474. std::string original_text = "Compressed with ZSTD";
  7475. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7476. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7477. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7478. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7479. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7480. std::string decompressed_data;
  7481. {
  7482. httplib::detail::zstd_decompressor decompressor;
  7483. bool result = decompressor.decompress(
  7484. compressed_data.data(), compressed_data.size(),
  7485. [&](const char *decompressed_data_chunk,
  7486. size_t decompressed_data_chunk_size) {
  7487. decompressed_data.insert(decompressed_data.size(),
  7488. decompressed_data_chunk,
  7489. decompressed_data_chunk_size);
  7490. return true;
  7491. });
  7492. ASSERT_TRUE(result);
  7493. }
  7494. ASSERT_EQ(original_text, decompressed_data);
  7495. }
  7496. #endif
  7497. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7498. // separate chunks so that the server sees each part in its own read(). Used to
  7499. // place a read boundary at a specific offset of a request body.
  7500. static bool send_request_in_parts(time_t read_timeout_sec,
  7501. const std::vector<std::string> &parts,
  7502. std::string *resp = nullptr,
  7503. int port = PORT) {
  7504. auto error = Error::Success;
  7505. auto client_sock = detail::create_client_socket(
  7506. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7507. /*connection_timeout_sec=*/5, 0,
  7508. /*read_timeout_sec=*/5, 0,
  7509. /*write_timeout_sec=*/5, 0, std::string(), error);
  7510. if (client_sock == INVALID_SOCKET) { return false; }
  7511. auto ret = detail::process_client_socket(
  7512. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7513. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7514. for (size_t i = 0; i < parts.size(); i++) {
  7515. const auto &part = parts[i];
  7516. if (part.size() !=
  7517. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7518. return false;
  7519. }
  7520. if (i + 1 < parts.size()) {
  7521. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7522. }
  7523. }
  7524. char buf[512];
  7525. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7526. while (line_reader.getline()) {
  7527. if (resp) { *resp += line_reader.ptr(); }
  7528. }
  7529. return true;
  7530. });
  7531. detail::close_socket(client_sock);
  7532. return ret;
  7533. }
  7534. // Sends a raw request to a server listening at HOST:PORT.
  7535. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7536. std::string *resp = nullptr, int port = PORT) {
  7537. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7538. }
  7539. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7540. Server svr;
  7541. std::string header_value;
  7542. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7543. header_value = req.get_header_value("foo");
  7544. res.set_content("ok", "text/plain");
  7545. });
  7546. thread t = thread([&] { svr.listen(HOST, PORT); });
  7547. auto se = detail::scope_exit([&] {
  7548. svr.stop();
  7549. t.join();
  7550. ASSERT_FALSE(svr.is_running());
  7551. });
  7552. svr.wait_until_ready();
  7553. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7554. // like characters are not treated the same - use vertical tab and escape.
  7555. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7556. "foo: \t \v bar \x1B\t \r\n"
  7557. "Connection: close\r\n"
  7558. "\r\n";
  7559. std::string res;
  7560. ASSERT_TRUE(send_request(5, req, &res));
  7561. EXPECT_EQ(header_value, "");
  7562. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7563. }
  7564. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7565. Server svr;
  7566. std::string received;
  7567. svr.Get("/order", [&](const Request &req, Response &res) {
  7568. received = entries_to_string(req.headers);
  7569. res.set_content("ok", "text/plain");
  7570. });
  7571. auto port = svr.bind_to_any_port(HOST);
  7572. thread t = thread([&] { svr.listen_after_bind(); });
  7573. auto se = detail::scope_exit([&] {
  7574. svr.stop();
  7575. t.join();
  7576. ASSERT_FALSE(svr.is_running());
  7577. });
  7578. svr.wait_until_ready();
  7579. const std::string req = "GET /order HTTP/1.1\r\n"
  7580. "X-First: 1\r\n"
  7581. "X-Dup: a\r\n"
  7582. "X-Second: 2\r\n"
  7583. "X-Dup: b\r\n"
  7584. "Connection: close\r\n"
  7585. "\r\n";
  7586. std::string res;
  7587. ASSERT_TRUE(send_request(5, req, &res, port));
  7588. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7589. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7590. }
  7591. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7592. Server svr;
  7593. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7594. res.set_header("Set-Cookie", "first=1");
  7595. res.set_header("X-Between", "y");
  7596. res.set_header("Set-Cookie", "second=2");
  7597. res.set_content("ok", "text/plain");
  7598. });
  7599. auto port = svr.bind_to_any_port(HOST);
  7600. thread t = thread([&] { svr.listen_after_bind(); });
  7601. auto se = detail::scope_exit([&] {
  7602. svr.stop();
  7603. t.join();
  7604. ASSERT_FALSE(svr.is_running());
  7605. });
  7606. svr.wait_until_ready();
  7607. Client cli(HOST, port);
  7608. auto res = cli.Get("/cookies");
  7609. ASSERT_TRUE(res);
  7610. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7611. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7612. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7613. }
  7614. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7615. Server svr;
  7616. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7617. auto i = new int(0);
  7618. res.set_header("Trailer", "X-Safe, X-Reflected");
  7619. res.set_chunked_content_provider(
  7620. "text/plain",
  7621. [i](size_t /*offset*/, DataSink &sink) {
  7622. if (*i == 0) {
  7623. sink.os << "body";
  7624. } else {
  7625. Headers trailer;
  7626. // A valid trailer that must survive.
  7627. trailer.emplace("X-Safe", "safe");
  7628. // Attacker-controlled value carrying CR/LF (response splitting).
  7629. trailer.emplace("X-Reflected",
  7630. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7631. // Attacker-controlled name carrying CR/LF.
  7632. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7633. sink.done_with_trailer(trailer);
  7634. }
  7635. (*i)++;
  7636. return true;
  7637. },
  7638. [i](bool /*success*/) { delete i; });
  7639. });
  7640. thread t = thread([&] { svr.listen(HOST, PORT); });
  7641. auto se = detail::scope_exit([&] {
  7642. svr.stop();
  7643. t.join();
  7644. ASSERT_FALSE(svr.is_running());
  7645. });
  7646. svr.wait_until_ready();
  7647. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7648. "Host: " + HOST +
  7649. "\r\n"
  7650. "Connection: close\r\n"
  7651. "\r\n";
  7652. std::string res;
  7653. ASSERT_TRUE(send_request(5, req, &res));
  7654. // The injected fields must not appear anywhere in the raw response.
  7655. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7656. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7657. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7658. // Invalid trailers are dropped entirely, matching set_header().
  7659. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7660. // The valid trailer still passes through.
  7661. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7662. }
  7663. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7664. Server svr;
  7665. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7666. // res.headers is a public field an application can populate directly,
  7667. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7668. // A valid header that must survive.
  7669. res.headers.emplace("X-Safe", "safe");
  7670. // Attacker-controlled value carrying CR/LF (response splitting).
  7671. res.headers.emplace("X-Reflected",
  7672. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7673. // Attacker-controlled name carrying CR/LF.
  7674. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7675. res.set_content("body", "text/plain");
  7676. });
  7677. thread t = thread([&] { svr.listen(HOST, PORT); });
  7678. auto se = detail::scope_exit([&] {
  7679. svr.stop();
  7680. t.join();
  7681. ASSERT_FALSE(svr.is_running());
  7682. });
  7683. svr.wait_until_ready();
  7684. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7685. "Host: " + HOST +
  7686. "\r\n"
  7687. "Connection: close\r\n"
  7688. "\r\n";
  7689. std::string res;
  7690. ASSERT_TRUE(send_request(5, req, &res));
  7691. // The injected fields must not appear anywhere in the raw response.
  7692. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7693. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7694. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7695. // Invalid headers are dropped entirely, matching set_header().
  7696. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7697. // The valid header still passes through.
  7698. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7699. }
  7700. // Forward declaration: in split builds split.py strips `inline` and moves the
  7701. // definition into httplib.cc, so detail::write_request_line is not visible from
  7702. // the public httplib.h. Re-declaring it here lets the tests link against the
  7703. // symbol in both header-only and split builds.
  7704. namespace httplib {
  7705. namespace detail {
  7706. ssize_t write_request_line(Stream &strm, const std::string &method,
  7707. const std::string &path);
  7708. } // namespace detail
  7709. } // namespace httplib
  7710. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7711. // A well-formed target is written verbatim.
  7712. {
  7713. detail::BufferStream strm;
  7714. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7715. EXPECT_GT(n, 0);
  7716. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7717. }
  7718. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7719. // otherwise it splits the request line and injects a header or a whole
  7720. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7721. // when path encoding is disabled.
  7722. const std::string evil_targets[] = {
  7723. "/a\r\nInjected: pwned",
  7724. "/a\rInjected",
  7725. "/a\nInjected",
  7726. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7727. };
  7728. for (const auto &evil : evil_targets) {
  7729. detail::BufferStream strm;
  7730. auto n = detail::write_request_line(strm, "GET", evil);
  7731. EXPECT_LT(n, 0);
  7732. EXPECT_TRUE(strm.get_buffer().empty());
  7733. }
  7734. }
  7735. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7736. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7737. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7738. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7739. // client must fail cleanly with Error::Write instead of putting a
  7740. // request-line-less, header-injecting request on the wire.
  7741. Server svr;
  7742. svr.Get("/a", [](const Request &, Response &res) {
  7743. res.set_content("ok", "text/plain");
  7744. });
  7745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7746. auto se = detail::scope_exit([&] {
  7747. svr.stop();
  7748. thread.join();
  7749. ASSERT_FALSE(svr.is_running());
  7750. });
  7751. svr.wait_until_ready();
  7752. {
  7753. Client cli(HOST, PORT);
  7754. cli.set_path_encode(false);
  7755. // The request is rejected before anything is written, so the connection
  7756. // stays silent and the subsequent response read would otherwise block for
  7757. // the full default read timeout. Shorten it -- the assertion is on the
  7758. // error, not the timeout.
  7759. cli.set_read_timeout(1, 0);
  7760. auto res = cli.Get("/a\r\nInjected: pwned");
  7761. EXPECT_FALSE(res);
  7762. EXPECT_EQ(Error::Write, res.error());
  7763. }
  7764. }
  7765. // Sends a raw request and verifies that there isn't a crash or exception.
  7766. static void test_raw_request(const std::string &req,
  7767. std::string *out = nullptr) {
  7768. Server svr;
  7769. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7770. res.set_content("ok", "text/plain");
  7771. });
  7772. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7773. res.set_content("ok", "text/plain");
  7774. });
  7775. svr.Get("/header_field_value_check",
  7776. [&](const Request & /*req*/, Response &res) {
  7777. res.set_content("ok", "text/plain");
  7778. });
  7779. svr.CustomRoute("PROPFIND", "/dav",
  7780. [&](const Request & /*req*/, Response &res) {
  7781. res.status = StatusCode::MultiStatus_207;
  7782. });
  7783. // Server read timeout must be longer than the client read timeout for the
  7784. // bug to reproduce, probably to force the server to process a request
  7785. // without a trailing blank line.
  7786. const time_t client_read_timeout_sec = 1;
  7787. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7788. bool listen_thread_ok = false;
  7789. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7790. auto se = detail::scope_exit([&] {
  7791. svr.stop();
  7792. t.join();
  7793. ASSERT_FALSE(svr.is_running());
  7794. EXPECT_TRUE(listen_thread_ok);
  7795. });
  7796. svr.wait_until_ready();
  7797. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7798. }
  7799. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7800. // A certain header line causes an exception if the header property is parsed
  7801. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7802. test_raw_request(
  7803. "GET /hi HTTP/1.1\r\n"
  7804. " : "
  7805. " "
  7806. " ");
  7807. }
  7808. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7809. // A certain header line causes an exception if the header property *name* is
  7810. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7811. // greedy matcher and requires backtracking when there are a lot of ":"
  7812. // characters.
  7813. // This occurs with libc++ but not libstdc++.
  7814. test_raw_request(
  7815. "GET /hi HTTP/1.1\r\n"
  7816. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7817. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7818. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7819. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7820. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7821. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7822. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7823. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7824. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7825. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7826. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7827. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7828. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7829. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7830. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7831. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7832. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7833. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7834. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7835. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7836. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7837. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7838. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7839. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7840. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7841. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7842. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7843. "&&&%%%");
  7844. }
  7845. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7846. // Make sure this doesn't crash the server.
  7847. // In a previous version of the header line regex, the "\r" rendered the line
  7848. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7849. // a new position where the leading white space ended and the field value
  7850. // began.
  7851. // The crash occurs with libc++ but not libstdc++.
  7852. test_raw_request("GET /hi HTTP/1.1\r\n"
  7853. "a:" +
  7854. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7855. "\r\n"
  7856. "\r\n");
  7857. }
  7858. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7859. std::string out;
  7860. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7861. "Content-Type: text/plain\r\n"
  7862. "Transfer-Encoding: chunked\r\n"
  7863. "\r\n"
  7864. "nothex\r\n",
  7865. &out);
  7866. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7867. }
  7868. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7869. std::string out;
  7870. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7871. "Content-Type: text/plain\r\n"
  7872. "Transfer-Encoding: chunked\r\n"
  7873. "\r\n"
  7874. "3\r\n"
  7875. "xyz\r\n"
  7876. "NaN\r\n",
  7877. &out);
  7878. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7879. }
  7880. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7881. std::string out;
  7882. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7883. "Content-Type: text/plain\r\n"
  7884. "Transfer-Encoding: chunked\r\n"
  7885. "\r\n"
  7886. // Length is too large for 64 bits.
  7887. "1ffffffffffffffff\r\n"
  7888. "xyz\r\n",
  7889. &out);
  7890. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7891. }
  7892. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7893. test_raw_request("GET /hi HTTP/1.1\r\n"
  7894. "Content-Type: text/plain\r\n\r");
  7895. }
  7896. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7897. std::string out;
  7898. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7900. }
  7901. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7902. Server svr;
  7903. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7904. EXPECT_TRUE(!req.remote_addr.empty());
  7905. });
  7906. thread t = thread([&] { svr.listen(HOST, PORT); });
  7907. auto se = detail::scope_exit([&] {
  7908. svr.stop();
  7909. t.join();
  7910. ASSERT_FALSE(svr.is_running());
  7911. });
  7912. svr.wait_until_ready();
  7913. // Send an invalid request line to trigger Bad Request
  7914. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7915. std::string out;
  7916. ASSERT_TRUE(send_request(5, bad_req, &out));
  7917. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7918. }
  7919. // A custom method with neither Content-Length nor Transfer-Encoding must be
  7920. // answered right away rather than blocking on a read that waits for EOF.
  7921. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  7922. std::string out;
  7923. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  7924. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  7925. }
  7926. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  7927. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  7928. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7929. for (const auto *method : methods) {
  7930. Server svr;
  7931. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7932. EXPECT_FALSE(svr.is_valid()) << method;
  7933. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  7934. }
  7935. }
  7936. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  7937. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  7938. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  7939. for (const auto *method : methods) {
  7940. Server svr;
  7941. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7942. EXPECT_FALSE(svr.is_valid()) << method;
  7943. }
  7944. }
  7945. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  7946. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  7947. "COPY", "MOVE", "LOCK",
  7948. "UNLOCK", "REPORT", "SUBSCRIBE"};
  7949. Server svr;
  7950. for (const auto *method : methods) {
  7951. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7952. }
  7953. EXPECT_TRUE(svr.is_valid());
  7954. }
  7955. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  7956. Server svr;
  7957. svr.CustomRoute("POST", "/x",
  7958. [](const Request &, Response &, const ContentReader &) {});
  7959. EXPECT_FALSE(svr.is_valid());
  7960. }
  7961. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  7962. Server svr;
  7963. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  7964. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  7965. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  7966. EXPECT_FALSE(svr.is_valid());
  7967. }
  7968. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  7969. Server svr;
  7970. auto captured = Error::Success;
  7971. svr.set_error_logger(
  7972. [&](const Error &err, const Request * /*req*/) { captured = err; });
  7973. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  7974. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  7975. }
  7976. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7977. std::string out;
  7978. std::string request(
  7979. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7980. test_raw_request(request, &out);
  7981. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7982. }
  7983. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7984. std::string out;
  7985. std::string request(
  7986. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7987. test_raw_request(request, &out);
  7988. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7989. }
  7990. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7991. std::string out;
  7992. std::string request(
  7993. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7994. test_raw_request(request, &out);
  7995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7996. }
  7997. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7998. std::string out;
  7999. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8000. "Test: \r\n\r\n",
  8001. &out);
  8002. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8003. }
  8004. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8005. Server svr;
  8006. std::string x_custom;
  8007. std::string cookie;
  8008. std::string xff;
  8009. std::string x_unicode;
  8010. std::string x_iis;
  8011. svr.Get("/check", [&](const Request &req, Response &res) {
  8012. x_custom = req.get_header_value("X-Custom");
  8013. cookie = req.get_header_value("Cookie");
  8014. xff = req.get_header_value("X-Forwarded-For");
  8015. x_unicode = req.get_header_value("X-Unicode");
  8016. x_iis = req.get_header_value("X-IIS");
  8017. res.set_content("ok", "text/plain");
  8018. });
  8019. thread t = thread([&] { svr.listen(HOST, PORT); });
  8020. auto se = detail::scope_exit([&] {
  8021. svr.stop();
  8022. t.join();
  8023. ASSERT_FALSE(svr.is_running());
  8024. });
  8025. svr.wait_until_ready();
  8026. const std::string req = "GET /check HTTP/1.1\r\n"
  8027. "Host: localhost\r\n"
  8028. "X-Custom: a%0D%0AInjected: b\r\n"
  8029. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8030. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8031. "X-Unicode: %E3%81%82\r\n"
  8032. "X-IIS: %u00E9\r\n"
  8033. "Connection: close\r\n"
  8034. "\r\n";
  8035. std::string res;
  8036. ASSERT_TRUE(send_request(5, req, &res));
  8037. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8038. // Every value must be returned verbatim (wire form), with no decoding.
  8039. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8040. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8041. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8042. EXPECT_EQ("%E3%81%82", x_unicode);
  8043. EXPECT_EQ("%u00E9", x_iis);
  8044. }
  8045. // Applications that previously relied on automatic percent-decoding can
  8046. // reproduce the old behavior by explicitly calling decode_path_component()
  8047. // or, for RFC 3986 conformance, decode_uri_component().
  8048. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8049. Server svr;
  8050. std::string decoded;
  8051. svr.Get("/check", [&](const Request &req, Response &res) {
  8052. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8053. res.set_content("ok", "text/plain");
  8054. });
  8055. thread t = thread([&] { svr.listen(HOST, PORT); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. t.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. const std::string req = "GET /check HTTP/1.1\r\n"
  8063. "Host: localhost\r\n"
  8064. "X-Custom: hello%20world\r\n"
  8065. "Connection: close\r\n"
  8066. "\r\n";
  8067. std::string res;
  8068. ASSERT_TRUE(send_request(5, req, &res));
  8069. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8070. EXPECT_EQ("hello world", decoded);
  8071. }
  8072. // Regression test for #2033. Browsers send Referer values that include
  8073. // percent-encoded characters such as %0A inside the URL. Decoding the
  8074. // header value would either trip the post-decode CR/LF/NUL guard (the
  8075. // original bug, returning 400) or, after that guard was relaxed, silently
  8076. // store a literal LF — both unacceptable. The wire form must round-trip.
  8077. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8078. Server svr;
  8079. std::string referer;
  8080. svr.Get("/check", [&](const Request &req, Response &res) {
  8081. referer = req.get_header_value("Referer");
  8082. res.set_content("ok", "text/plain");
  8083. });
  8084. thread t = thread([&] { svr.listen(HOST, PORT); });
  8085. auto se = detail::scope_exit([&] {
  8086. svr.stop();
  8087. t.join();
  8088. ASSERT_FALSE(svr.is_running());
  8089. });
  8090. svr.wait_until_ready();
  8091. const std::string req = "GET /check HTTP/1.1\r\n"
  8092. "Host: localhost\r\n"
  8093. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8094. "Connection: close\r\n"
  8095. "\r\n";
  8096. std::string res;
  8097. ASSERT_TRUE(send_request(5, req, &res));
  8098. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8099. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8100. }
  8101. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8102. Server svr;
  8103. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8104. res.set_header("Cache-Control", "no-cache");
  8105. res.set_chunked_content_provider(
  8106. "text/event-stream", [](size_t offset, DataSink &sink) {
  8107. std::string s = "data:";
  8108. s += std::to_string(offset);
  8109. s += "\n\n";
  8110. auto ret = sink.write(s.data(), s.size());
  8111. EXPECT_TRUE(ret);
  8112. std::this_thread::sleep_for(std::chrono::seconds(1));
  8113. return true;
  8114. });
  8115. });
  8116. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8117. svr.wait_until_ready();
  8118. Client client(HOST, PORT);
  8119. const Headers headers = {{"Accept", "text/event-stream"}};
  8120. auto get_thread = std::thread([&client, &headers]() {
  8121. auto res = client.Get(
  8122. "/events", headers,
  8123. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8124. });
  8125. auto se = detail::scope_exit([&] {
  8126. svr.stop();
  8127. get_thread.join();
  8128. listen_thread.join();
  8129. ASSERT_FALSE(svr.is_running());
  8130. });
  8131. // Give GET time to get a few messages.
  8132. std::this_thread::sleep_for(std::chrono::seconds(2));
  8133. }
  8134. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8135. httplib::Server svr;
  8136. svr.Post("/hi",
  8137. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8138. res.status = StatusCode::OK_200;
  8139. });
  8140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8141. svr.wait_until_ready();
  8142. Client cli(HOST, PORT);
  8143. auto res = cli.Post("/hi", "data", "text/plain");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. svr.stop();
  8147. thread.join();
  8148. ASSERT_FALSE(svr.is_running());
  8149. res = cli.Post("/hi", "data", "text/plain");
  8150. ASSERT_FALSE(res);
  8151. }
  8152. TEST(ServerStopTest, ListenFailure) {
  8153. Server svr;
  8154. auto t = thread([&]() {
  8155. auto ret = svr.listen("????", PORT);
  8156. EXPECT_FALSE(ret);
  8157. });
  8158. svr.wait_until_ready();
  8159. svr.stop();
  8160. t.join();
  8161. }
  8162. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8163. TEST(ServerStopTest, Decommision) {
  8164. Server svr;
  8165. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8166. for (int i = 0; i < 4; i++) {
  8167. auto is_even = !(i % 2);
  8168. std::thread t{[&] {
  8169. try {
  8170. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8171. if (is_even) {
  8172. throw std::runtime_error("Some thing that happens to go wrong.");
  8173. }
  8174. svr.listen(HOST, PORT);
  8175. } catch (...) { svr.decommission(); }
  8176. }};
  8177. svr.wait_until_ready();
  8178. // Server is up
  8179. {
  8180. Client cli(HOST, PORT);
  8181. auto res = cli.Get("/hi");
  8182. if (is_even) {
  8183. EXPECT_FALSE(res);
  8184. } else {
  8185. EXPECT_TRUE(res);
  8186. EXPECT_EQ("hi...", res->body);
  8187. }
  8188. }
  8189. svr.stop();
  8190. t.join();
  8191. // Server is down...
  8192. {
  8193. Client cli(HOST, PORT);
  8194. auto res = cli.Get("/hi");
  8195. EXPECT_FALSE(res);
  8196. }
  8197. }
  8198. }
  8199. #endif
  8200. // Helper function for string body upload progress tests
  8201. template <typename SetupHandler, typename ClientCall>
  8202. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8203. ClientCall &&client_call,
  8204. const string &body) {
  8205. Server svr;
  8206. setup_handler(svr);
  8207. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8208. auto se = detail::scope_exit([&] {
  8209. svr.stop();
  8210. t.join();
  8211. });
  8212. svr.wait_until_ready();
  8213. Client cli(HOST, PORT);
  8214. vector<uint64_t> progress_values;
  8215. bool progress_called = false;
  8216. auto res =
  8217. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8218. progress_values.push_back(current);
  8219. progress_called = true;
  8220. return true;
  8221. });
  8222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8223. EXPECT_EQ(200, res->status);
  8224. EXPECT_TRUE(progress_called);
  8225. }
  8226. TEST(UploadProgressTest, PostStringBodyBasic) {
  8227. TestStringBodyUploadProgress(
  8228. [](Server &svr) {
  8229. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8230. res.set_content("received", "text/plain");
  8231. });
  8232. },
  8233. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8234. return cli.Post("/test", body, "text/plain", progress_callback);
  8235. },
  8236. "test data for upload progress");
  8237. }
  8238. TEST(UploadProgressTest, PutStringBodyBasic) {
  8239. TestStringBodyUploadProgress(
  8240. [](Server &svr) {
  8241. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8242. res.set_content("put received", "text/plain");
  8243. });
  8244. },
  8245. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8246. return cli.Put("/test", body, "text/plain", progress_callback);
  8247. },
  8248. "put test data for upload progress");
  8249. }
  8250. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8251. TestStringBodyUploadProgress(
  8252. [](Server &svr) {
  8253. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8254. res.set_content("patch received", "text/plain");
  8255. });
  8256. },
  8257. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8258. return cli.Patch("/test", body, "text/plain", progress_callback);
  8259. },
  8260. "patch test data for upload progress");
  8261. }
  8262. // Helper function for content provider upload progress tests
  8263. template <typename SetupHandler, typename ClientCall>
  8264. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8265. ClientCall &&client_call) {
  8266. Server svr;
  8267. setup_handler(svr);
  8268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8269. auto se = detail::scope_exit([&] {
  8270. svr.stop();
  8271. t.join();
  8272. });
  8273. svr.wait_until_ready();
  8274. Client cli(HOST, PORT);
  8275. vector<uint64_t> progress_values;
  8276. auto res =
  8277. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8278. progress_values.push_back(current);
  8279. return true;
  8280. });
  8281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8282. EXPECT_EQ(200, res->status);
  8283. EXPECT_FALSE(progress_values.empty());
  8284. }
  8285. TEST(UploadProgressTest, PostContentProviderProgress) {
  8286. TestContentProviderUploadProgress(
  8287. [](Server &svr) {
  8288. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8289. res.set_content("provider received", "text/plain");
  8290. });
  8291. },
  8292. [](Client &cli, UploadProgress progress_callback) {
  8293. return cli.Post(
  8294. "/test", 10,
  8295. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8296. sink.os << "test data";
  8297. return true;
  8298. },
  8299. "text/plain", progress_callback);
  8300. });
  8301. }
  8302. // Helper function for multipart upload progress tests
  8303. template <typename SetupHandler, typename ClientCall>
  8304. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8305. ClientCall &&client_call,
  8306. const string &endpoint) {
  8307. Server svr;
  8308. setup_handler(svr);
  8309. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8310. auto se = detail::scope_exit([&] {
  8311. svr.stop();
  8312. t.join();
  8313. });
  8314. svr.wait_until_ready();
  8315. Client cli(HOST, PORT);
  8316. vector<uint64_t> progress_values;
  8317. UploadFormDataItems items = {
  8318. {"field1", "value1", "", ""},
  8319. {"field2", "longer value for progress tracking test", "", ""},
  8320. {"file1", "file content data for upload progress", "test.txt",
  8321. "text/plain"}};
  8322. auto res = client_call(cli, endpoint, items,
  8323. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8324. progress_values.push_back(current);
  8325. return true;
  8326. });
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(200, res->status);
  8329. EXPECT_FALSE(progress_values.empty());
  8330. }
  8331. TEST(UploadProgressTest, PostMultipartProgress) {
  8332. TestMultipartUploadProgress(
  8333. [](Server &svr) {
  8334. svr.Post("/multipart", [](const Request &req, Response &res) {
  8335. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8336. res.set_content("multipart received", "text/plain");
  8337. });
  8338. },
  8339. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8340. UploadProgress progress_callback) {
  8341. return cli.Post(endpoint, items, progress_callback);
  8342. },
  8343. "/multipart");
  8344. }
  8345. // Helper function for basic download progress tests
  8346. template <typename SetupHandler, typename ClientCall>
  8347. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8348. ClientCall &&client_call, const string &endpoint,
  8349. size_t expected_content_size) {
  8350. Server svr;
  8351. setup_handler(svr);
  8352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8353. auto se = detail::scope_exit([&] {
  8354. svr.stop();
  8355. t.join();
  8356. });
  8357. svr.wait_until_ready();
  8358. Client cli(HOST, PORT);
  8359. vector<uint64_t> progress_values;
  8360. auto res = client_call(cli, endpoint,
  8361. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8362. progress_values.push_back(current);
  8363. return true;
  8364. });
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(200, res->status);
  8367. EXPECT_FALSE(progress_values.empty());
  8368. EXPECT_EQ(expected_content_size, res->body.size());
  8369. }
  8370. TEST(DownloadProgressTest, GetBasic) {
  8371. TestBasicDownloadProgress(
  8372. [](Server &svr) {
  8373. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8374. string content(1000, 'D');
  8375. res.set_content(content, "text/plain");
  8376. });
  8377. },
  8378. [](Client &cli, const string &endpoint,
  8379. DownloadProgress progress_callback) {
  8380. return cli.Get(endpoint, progress_callback);
  8381. },
  8382. "/download", 1000u);
  8383. }
  8384. // Helper function for content receiver download progress tests
  8385. template <typename SetupHandler, typename ClientCall>
  8386. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8387. ClientCall &&client_call,
  8388. const string &endpoint,
  8389. size_t expected_content_size) {
  8390. Server svr;
  8391. setup_handler(svr);
  8392. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8393. auto se = detail::scope_exit([&] {
  8394. svr.stop();
  8395. t.join();
  8396. });
  8397. svr.wait_until_ready();
  8398. Client cli(HOST, PORT);
  8399. vector<uint64_t> progress_values;
  8400. string received_body;
  8401. auto res = client_call(
  8402. cli, endpoint,
  8403. [&](const char *data, size_t data_length) -> bool {
  8404. received_body.append(data, data_length);
  8405. return true;
  8406. },
  8407. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8408. progress_values.push_back(current);
  8409. return true;
  8410. });
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(200, res->status);
  8413. EXPECT_FALSE(progress_values.empty());
  8414. EXPECT_EQ(expected_content_size, received_body.size());
  8415. EXPECT_TRUE(res->body.empty());
  8416. }
  8417. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8418. TestContentReceiverDownloadProgress(
  8419. [](Server &svr) {
  8420. svr.Get("/download-receiver",
  8421. [](const Request & /*req*/, Response &res) {
  8422. string content(2000, 'R');
  8423. res.set_content(content, "text/plain");
  8424. });
  8425. },
  8426. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8427. DownloadProgress progress_callback) {
  8428. return cli.Get(endpoint, content_receiver, progress_callback);
  8429. },
  8430. "/download-receiver", 2000u);
  8431. }
  8432. TEST(StreamingTest, NoContentLengthStreaming) {
  8433. Server svr;
  8434. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8435. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8436. if (offset < 6) {
  8437. sink.os << (offset < 3 ? "a" : "b");
  8438. } else {
  8439. sink.done();
  8440. }
  8441. return true;
  8442. });
  8443. });
  8444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8445. auto listen_se = detail::scope_exit([&] {
  8446. svr.stop();
  8447. listen_thread.join();
  8448. ASSERT_FALSE(svr.is_running());
  8449. });
  8450. svr.wait_until_ready();
  8451. Client client(HOST, PORT);
  8452. auto get_thread = std::thread([&client]() {
  8453. std::string s;
  8454. auto res =
  8455. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8456. s += std::string(data, len);
  8457. return true;
  8458. });
  8459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8460. EXPECT_EQ(StatusCode::OK_200, res->status);
  8461. EXPECT_EQ("aaabbb", s);
  8462. });
  8463. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8464. // Give GET time to get a few messages.
  8465. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8466. }
  8467. TEST(MountTest, Unmount) {
  8468. Server svr;
  8469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8470. auto se = detail::scope_exit([&] {
  8471. svr.stop();
  8472. listen_thread.join();
  8473. ASSERT_FALSE(svr.is_running());
  8474. });
  8475. svr.wait_until_ready();
  8476. Client cli("localhost", PORT);
  8477. svr.set_mount_point("/mount2", "./www2");
  8478. auto res = cli.Get("/");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8481. res = cli.Get("/mount2/dir/test.html");
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::OK_200, res->status);
  8484. svr.set_mount_point("/", "./www");
  8485. res = cli.Get("/dir/");
  8486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. svr.remove_mount_point("/");
  8489. res = cli.Get("/dir/");
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8492. svr.remove_mount_point("/mount2");
  8493. res = cli.Get("/mount2/dir/test.html");
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8496. }
  8497. TEST(MountTest, PathSegmentBoundary) {
  8498. Server svr;
  8499. svr.set_mount_point("/mount2", "./www2");
  8500. svr.set_mount_point("/", "./www");
  8501. auto port = svr.bind_to_any_port(HOST);
  8502. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8503. auto se = detail::scope_exit([&] {
  8504. svr.stop();
  8505. listen_thread.join();
  8506. ASSERT_FALSE(svr.is_running());
  8507. });
  8508. svr.wait_until_ready();
  8509. Client cli(HOST, port);
  8510. auto res = cli.Get("/mount2/dir/test.html");
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(StatusCode::OK_200, res->status);
  8513. // "/mount2" must not match part-way through a path segment.
  8514. res = cli.Get("/mount2dir/test.html");
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8517. // A mount point ending in '/' keeps matching every path below it.
  8518. res = cli.Get("/dir/test.html");
  8519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8520. EXPECT_EQ(StatusCode::OK_200, res->status);
  8521. }
  8522. TEST(MountTest, Redicect) {
  8523. Server svr;
  8524. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8525. auto se = detail::scope_exit([&] {
  8526. svr.stop();
  8527. listen_thread.join();
  8528. ASSERT_FALSE(svr.is_running());
  8529. });
  8530. svr.set_mount_point("/", "./www");
  8531. svr.wait_until_ready();
  8532. Client cli("localhost", PORT);
  8533. auto res = cli.Get("/dir/");
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ(StatusCode::OK_200, res->status);
  8536. res = cli.Get("/dir");
  8537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8538. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8539. res = cli.Get("/file");
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. res = cli.Get("/file/");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8545. cli.set_follow_location(true);
  8546. res = cli.Get("/dir");
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ(StatusCode::OK_200, res->status);
  8549. }
  8550. TEST(MountTest, MultibytesPathName) {
  8551. Server svr;
  8552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8553. auto se = detail::scope_exit([&] {
  8554. svr.stop();
  8555. listen_thread.join();
  8556. ASSERT_FALSE(svr.is_running());
  8557. });
  8558. svr.set_mount_point("/", "./www");
  8559. svr.wait_until_ready();
  8560. Client cli("localhost", PORT);
  8561. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8563. EXPECT_EQ(StatusCode::OK_200, res->status);
  8564. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8565. }
  8566. #ifdef _WIN32
  8567. // Issue #2435: mmap::open() must succeed even when another handle holds
  8568. // the file open for writing (e.g. an active log file).
  8569. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8570. const char *path = "mmap_concurrent_writer_test.txt";
  8571. const char *content = "hello";
  8572. {
  8573. std::ofstream f(path, std::ios::binary);
  8574. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8575. }
  8576. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8577. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8578. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8579. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8580. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8581. detail::mmap m(path);
  8582. ASSERT_TRUE(m.is_open());
  8583. EXPECT_EQ(strlen(content), m.size());
  8584. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8585. }
  8586. #endif
  8587. #ifndef _WIN32
  8588. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8589. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8590. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8591. TEST(MmapTest, FailedMappingIsNotOpen) {
  8592. const char *path = "./mmap_failed_mapping_test_dir";
  8593. ASSERT_EQ(0, ::mkdir(path, 0755));
  8594. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8595. detail::mmap m(path);
  8596. EXPECT_FALSE(m.is_open());
  8597. EXPECT_EQ(0U, m.size());
  8598. EXPECT_NE(static_cast<const void *>(m.data()),
  8599. static_cast<const void *>(MAP_FAILED));
  8600. }
  8601. #endif
  8602. TEST(KeepAliveTest, ReadTimeout) {
  8603. Server svr;
  8604. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8605. std::this_thread::sleep_for(std::chrono::seconds(2));
  8606. res.set_content("a", "text/plain");
  8607. });
  8608. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8609. res.set_content("b", "text/plain");
  8610. });
  8611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8612. auto se = detail::scope_exit([&] {
  8613. svr.stop();
  8614. listen_thread.join();
  8615. ASSERT_FALSE(svr.is_running());
  8616. });
  8617. svr.wait_until_ready();
  8618. Client cli("localhost", PORT);
  8619. cli.set_keep_alive(true);
  8620. cli.set_read_timeout(std::chrono::seconds(1));
  8621. auto resa = cli.Get("/a");
  8622. ASSERT_FALSE(resa);
  8623. EXPECT_EQ(Error::Read, resa.error());
  8624. auto resb = cli.Get("/b");
  8625. ASSERT_TRUE(resb);
  8626. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8627. EXPECT_EQ("b", resb->body);
  8628. }
  8629. TEST(KeepAliveTest, MaxCount) {
  8630. size_t keep_alive_max_count = 3;
  8631. Server svr;
  8632. svr.set_keep_alive_max_count(keep_alive_max_count);
  8633. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8634. res.set_content("Hello World!", "text/plain");
  8635. });
  8636. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8637. auto se = detail::scope_exit([&] {
  8638. svr.stop();
  8639. listen_thread.join();
  8640. ASSERT_FALSE(svr.is_running());
  8641. });
  8642. svr.wait_until_ready();
  8643. Client cli(HOST, PORT);
  8644. cli.set_keep_alive(true);
  8645. for (size_t i = 0; i < 5; i++) {
  8646. auto result = cli.Get("/hi");
  8647. ASSERT_TRUE(result);
  8648. EXPECT_EQ(StatusCode::OK_200, result->status);
  8649. if (i == keep_alive_max_count - 1) {
  8650. EXPECT_EQ("close", result->get_header_value("Connection"));
  8651. } else {
  8652. EXPECT_FALSE(result->has_header("Connection"));
  8653. }
  8654. }
  8655. }
  8656. TEST(KeepAliveTest, Issue1041) {
  8657. Server svr;
  8658. svr.set_keep_alive_timeout(3);
  8659. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8660. res.set_content("Hello World!", "text/plain");
  8661. });
  8662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8663. auto se = detail::scope_exit([&] {
  8664. svr.stop();
  8665. listen_thread.join();
  8666. ASSERT_FALSE(svr.is_running());
  8667. });
  8668. svr.wait_until_ready();
  8669. Client cli(HOST, PORT);
  8670. cli.set_keep_alive(true);
  8671. auto result = cli.Get("/hi");
  8672. ASSERT_TRUE(result);
  8673. EXPECT_EQ(StatusCode::OK_200, result->status);
  8674. std::this_thread::sleep_for(std::chrono::seconds(5));
  8675. result = cli.Get("/hi");
  8676. ASSERT_TRUE(result);
  8677. EXPECT_EQ(StatusCode::OK_200, result->status);
  8678. }
  8679. TEST(KeepAliveTest, Issue1959) {
  8680. Server svr;
  8681. svr.set_keep_alive_timeout(5);
  8682. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8683. res.set_content("a", "text/plain");
  8684. });
  8685. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8686. auto se = detail::scope_exit([&] {
  8687. if (!svr.is_running()) return;
  8688. svr.stop();
  8689. listen_thread.join();
  8690. ASSERT_FALSE(svr.is_running());
  8691. });
  8692. svr.wait_until_ready();
  8693. Client cli("localhost", PORT);
  8694. cli.set_keep_alive(true);
  8695. using namespace std::chrono;
  8696. auto start = steady_clock::now();
  8697. cli.Get("/a");
  8698. svr.stop();
  8699. listen_thread.join();
  8700. auto end = steady_clock::now();
  8701. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8702. EXPECT_LT(elapsed, 5000);
  8703. }
  8704. #ifdef CPPHTTPLIB_SSL_ENABLED
  8705. TEST(KeepAliveTest, SSLClientReconnection) {
  8706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8707. ASSERT_TRUE(svr.is_valid());
  8708. svr.set_keep_alive_timeout(1);
  8709. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8710. res.set_content("Hello World!", "text/plain");
  8711. });
  8712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8713. auto se = detail::scope_exit([&] {
  8714. svr.stop();
  8715. listen_thread.join();
  8716. ASSERT_FALSE(svr.is_running());
  8717. });
  8718. svr.wait_until_ready();
  8719. SSLClient cli(HOST, PORT);
  8720. cli.enable_server_certificate_verification(false);
  8721. cli.set_keep_alive(true);
  8722. auto result = cli.Get("/hi");
  8723. ASSERT_TRUE(result);
  8724. EXPECT_EQ(StatusCode::OK_200, result->status);
  8725. result = cli.Get("/hi");
  8726. ASSERT_TRUE(result);
  8727. EXPECT_EQ(StatusCode::OK_200, result->status);
  8728. std::this_thread::sleep_for(std::chrono::seconds(2));
  8729. // Recoonect
  8730. result = cli.Get("/hi");
  8731. ASSERT_TRUE(result);
  8732. EXPECT_EQ(StatusCode::OK_200, result->status);
  8733. result = cli.Get("/hi");
  8734. ASSERT_TRUE(result);
  8735. EXPECT_EQ(StatusCode::OK_200, result->status);
  8736. }
  8737. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8739. ASSERT_TRUE(svr.is_valid());
  8740. svr.set_keep_alive_timeout(1);
  8741. std::string content = "reconnect";
  8742. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8743. res.set_content("Hello World!", "text/plain");
  8744. });
  8745. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8746. auto se = detail::scope_exit([&] {
  8747. svr.stop();
  8748. listen_thread.join();
  8749. ASSERT_FALSE(svr.is_running());
  8750. });
  8751. svr.wait_until_ready();
  8752. SSLClient cli(HOST, PORT);
  8753. cli.enable_server_certificate_verification(false);
  8754. cli.set_keep_alive(true);
  8755. auto result = cli.Post(
  8756. "/hi", content.size(),
  8757. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8758. sink.write(content.c_str(), content.size());
  8759. return true;
  8760. },
  8761. "text/plain");
  8762. ASSERT_TRUE(result);
  8763. EXPECT_EQ(200, result->status);
  8764. std::this_thread::sleep_for(std::chrono::seconds(2));
  8765. // Recoonect
  8766. result = cli.Post(
  8767. "/hi", content.size(),
  8768. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8769. sink.write(content.c_str(), content.size());
  8770. return true;
  8771. },
  8772. "text/plain");
  8773. ASSERT_TRUE(result);
  8774. EXPECT_EQ(200, result->status);
  8775. result = cli.Post(
  8776. "/hi", content.size(),
  8777. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8778. sink.write(content.c_str(), content.size());
  8779. return true;
  8780. },
  8781. "text/plain");
  8782. ASSERT_TRUE(result);
  8783. EXPECT_EQ(200, result->status);
  8784. }
  8785. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8786. using namespace httplib::tls;
  8787. {
  8788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8789. ASSERT_TRUE(svr.is_valid());
  8790. svr.Get("/sni", [&](const Request &req, Response &res) {
  8791. std::string expected = req.sni();
  8792. EXPECT_EQ(expected, req.get_param_value("expected"));
  8793. res.set_content("ok", "text/plain");
  8794. });
  8795. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. listen_thread.join();
  8799. ASSERT_FALSE(svr.is_running());
  8800. });
  8801. svr.wait_until_ready();
  8802. {
  8803. SSLClient cli("localhost", PORT);
  8804. cli.enable_server_certificate_verification(false);
  8805. auto res = cli.Get("/sni?expected=localhost");
  8806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8807. }
  8808. {
  8809. SSLClient cli("::1", PORT);
  8810. cli.enable_server_certificate_verification(false);
  8811. auto res = cli.Get("/sni?expected=");
  8812. // NOTE: This may fail if the server is listening on IPv4 only
  8813. // (e.g., when localhost resolves to 127.0.0.1 only)
  8814. if (res) {
  8815. EXPECT_EQ(StatusCode::OK_200, res->status);
  8816. } else {
  8817. EXPECT_EQ(Error::Connection, res.error());
  8818. }
  8819. }
  8820. }
  8821. }
  8822. #endif
  8823. TEST(ClientProblemDetectionTest, ContentProvider) {
  8824. Server svr;
  8825. size_t content_length = 1024 * 1024;
  8826. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8827. res.set_content_provider(
  8828. content_length, "text/plain",
  8829. [&](size_t offset, size_t length, DataSink &sink) {
  8830. auto out_len = std::min(length, static_cast<size_t>(1024));
  8831. std::string out(out_len, '@');
  8832. sink.write(out.data(), out_len);
  8833. return offset < 4096;
  8834. },
  8835. [](bool success) { ASSERT_FALSE(success); });
  8836. });
  8837. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8838. res.set_content_provider(
  8839. 0, "text/plain",
  8840. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8841. EXPECT_TRUE(false);
  8842. return true;
  8843. },
  8844. [](bool success) { ASSERT_FALSE(success); });
  8845. });
  8846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8847. auto se = detail::scope_exit([&] {
  8848. svr.stop();
  8849. listen_thread.join();
  8850. ASSERT_FALSE(svr.is_running());
  8851. });
  8852. svr.wait_until_ready();
  8853. Client cli("localhost", PORT);
  8854. {
  8855. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8856. size_t /*data_length*/) { return false; });
  8857. ASSERT_FALSE(res);
  8858. }
  8859. {
  8860. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8861. size_t /*data_length*/) { return false; });
  8862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8863. }
  8864. }
  8865. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8866. Server svr;
  8867. svr.set_error_handler([](Request const &, Response &res) -> void {
  8868. res.set_chunked_content_provider(
  8869. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8870. sink.os << "hello";
  8871. sink.os << "world";
  8872. sink.done();
  8873. return true;
  8874. });
  8875. });
  8876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8877. auto se = detail::scope_exit([&] {
  8878. svr.stop();
  8879. listen_thread.join();
  8880. ASSERT_FALSE(svr.is_running());
  8881. });
  8882. svr.wait_until_ready();
  8883. Client cli("localhost", PORT);
  8884. auto res = cli.Get("/");
  8885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8887. EXPECT_EQ("helloworld", res->body);
  8888. }
  8889. TEST(LongPollingTest, ClientCloseDetection) {
  8890. Server svr;
  8891. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8892. res.set_chunked_content_provider(
  8893. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8894. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8895. sink.os << "hello";
  8896. auto count = 10;
  8897. while (count > 0 && sink.is_writable()) {
  8898. this_thread::sleep_for(chrono::milliseconds(10));
  8899. count--;
  8900. }
  8901. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8902. return true;
  8903. });
  8904. });
  8905. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8906. auto se = detail::scope_exit([&] {
  8907. svr.stop();
  8908. listen_thread.join();
  8909. ASSERT_FALSE(svr.is_running());
  8910. });
  8911. svr.wait_until_ready();
  8912. Client cli("localhost", PORT);
  8913. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8914. EXPECT_EQ("hello", string(data, data_length));
  8915. return false; // close the socket immediately.
  8916. });
  8917. ASSERT_FALSE(res);
  8918. }
  8919. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8920. Server svr;
  8921. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8922. res.set_chunked_content_provider(
  8923. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8924. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8925. sink.os << "hello";
  8926. EXPECT_TRUE(sink.os.good());
  8927. // Wait for the client to close the connection
  8928. auto count = 10;
  8929. while (count > 0 && sink.is_writable()) {
  8930. this_thread::sleep_for(chrono::milliseconds(10));
  8931. count--;
  8932. }
  8933. // After client disconnect, write repeatedly until the socket
  8934. // write actually fails (small writes may be absorbed by the
  8935. // kernel buffer)
  8936. std::string chunk(1024, 'x');
  8937. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8938. sink.os << chunk;
  8939. }
  8940. EXPECT_TRUE(sink.os.fail());
  8941. return true;
  8942. });
  8943. });
  8944. auto port = svr.bind_to_any_port("localhost");
  8945. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8946. auto se = detail::scope_exit([&] {
  8947. svr.stop();
  8948. listen_thread.join();
  8949. ASSERT_FALSE(svr.is_running());
  8950. });
  8951. svr.wait_until_ready();
  8952. Client cli("localhost", port);
  8953. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8954. EXPECT_EQ("hello", string(data, data_length));
  8955. return false; // close the socket immediately.
  8956. });
  8957. ASSERT_FALSE(res);
  8958. }
  8959. TEST(GetWithParametersTest, GetWithParameters) {
  8960. Server svr;
  8961. svr.Get("/", [&](const Request &req, Response &) {
  8962. EXPECT_EQ("world", req.get_param_value("hello"));
  8963. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8964. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8965. });
  8966. svr.Get("/params", [&](const Request &req, Response &) {
  8967. EXPECT_EQ("world", req.get_param_value("hello"));
  8968. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8969. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8970. });
  8971. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8972. EXPECT_EQ("resource-id", req.matches[1]);
  8973. EXPECT_EQ("foo", req.get_param_value("param1"));
  8974. EXPECT_EQ("bar", req.get_param_value("param2"));
  8975. });
  8976. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8977. EXPECT_EQ("user-id", req.path_params.at("id"));
  8978. EXPECT_EQ("foo", req.get_param_value("param1"));
  8979. EXPECT_EQ("bar", req.get_param_value("param2"));
  8980. });
  8981. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8982. auto se = detail::scope_exit([&] {
  8983. svr.stop();
  8984. listen_thread.join();
  8985. ASSERT_FALSE(svr.is_running());
  8986. });
  8987. svr.wait_until_ready();
  8988. {
  8989. Client cli(HOST, PORT);
  8990. Params params;
  8991. params.emplace("hello", "world");
  8992. params.emplace("hello2", "world2");
  8993. params.emplace("hello3", "world3");
  8994. auto res = cli.Get("/", params, Headers{});
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. }
  8998. {
  8999. Client cli(HOST, PORT);
  9000. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9002. EXPECT_EQ(StatusCode::OK_200, res->status);
  9003. }
  9004. {
  9005. Client cli(HOST, PORT);
  9006. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. {
  9011. Client cli(HOST, PORT);
  9012. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9014. EXPECT_EQ(StatusCode::OK_200, res->status);
  9015. }
  9016. }
  9017. TEST(GetWithParametersTest, GetWithParameters2) {
  9018. Server svr;
  9019. svr.Get("/", [&](const Request &req, Response &res) {
  9020. auto text = req.get_param_value("hello");
  9021. res.set_content(text, "text/plain");
  9022. });
  9023. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9024. auto se = detail::scope_exit([&] {
  9025. svr.stop();
  9026. listen_thread.join();
  9027. ASSERT_FALSE(svr.is_running());
  9028. });
  9029. svr.wait_until_ready();
  9030. Client cli("localhost", PORT);
  9031. Params params;
  9032. params.emplace("hello", "world");
  9033. std::string body;
  9034. auto res = cli.Get("/", params, Headers{},
  9035. [&](const char *data, size_t data_length) {
  9036. body.append(data, data_length);
  9037. return true;
  9038. });
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(StatusCode::OK_200, res->status);
  9041. EXPECT_EQ("world", body);
  9042. }
  9043. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9044. Server svr;
  9045. svr.Get("/search", [&](const Request &req, Response &res) {
  9046. auto q = req.get_param_value("q");
  9047. res.set_content(q, "text/plain");
  9048. });
  9049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. svr.stop();
  9052. listen_thread.join();
  9053. ASSERT_FALSE(svr.is_running());
  9054. });
  9055. svr.wait_until_ready();
  9056. Client cli("localhost", PORT);
  9057. // Verify that Get(path, params) works without requiring Headers argument
  9058. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ(StatusCode::OK_200, res->status);
  9061. EXPECT_EQ("cpp-httplib", res->body);
  9062. }
  9063. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9064. auto host = "httpbingo.org";
  9065. auto path = std::string{"/range/32"};
  9066. #ifdef CPPHTTPLIB_SSL_ENABLED
  9067. SSLClient cli(host);
  9068. #else
  9069. Client cli(host);
  9070. #endif
  9071. cli.set_default_headers({make_range_header({{1, 10}})});
  9072. cli.set_connection_timeout(5);
  9073. {
  9074. auto res = cli.Get(path);
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ("bcdefghijk", res->body);
  9077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9078. }
  9079. {
  9080. auto res = cli.Get(path);
  9081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9082. EXPECT_EQ("bcdefghijk", res->body);
  9083. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9084. }
  9085. }
  9086. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9087. Server svr;
  9088. svr.set_default_headers({{"Hello", "World"}});
  9089. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9090. res.set_content("ok", "text/plain");
  9091. });
  9092. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9093. auto se = detail::scope_exit([&] {
  9094. svr.stop();
  9095. listen_thread.join();
  9096. ASSERT_FALSE(svr.is_running());
  9097. });
  9098. svr.wait_until_ready();
  9099. Client cli("localhost", PORT);
  9100. auto res = cli.Get("/");
  9101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9102. EXPECT_EQ(StatusCode::OK_200, res->status);
  9103. EXPECT_EQ("ok", res->body);
  9104. EXPECT_EQ("World", res->get_header_value("Hello"));
  9105. }
  9106. #ifdef CPPHTTPLIB_SSL_ENABLED
  9107. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9109. ASSERT_TRUE(svr.is_valid());
  9110. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9111. std::this_thread::sleep_for(std::chrono::seconds(2));
  9112. res.set_content("a", "text/plain");
  9113. });
  9114. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9115. res.set_content("b", "text/plain");
  9116. });
  9117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9118. auto se = detail::scope_exit([&] {
  9119. svr.stop();
  9120. listen_thread.join();
  9121. ASSERT_FALSE(svr.is_running());
  9122. });
  9123. svr.wait_until_ready();
  9124. SSLClient cli("localhost", PORT);
  9125. cli.enable_server_certificate_verification(false);
  9126. cli.set_keep_alive(true);
  9127. cli.set_read_timeout(std::chrono::seconds(1));
  9128. auto resa = cli.Get("/a");
  9129. ASSERT_TRUE(!resa);
  9130. EXPECT_EQ(Error::Read, resa.error());
  9131. auto resb = cli.Get("/b");
  9132. ASSERT_TRUE(resb);
  9133. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9134. EXPECT_EQ("b", resb->body);
  9135. }
  9136. #endif
  9137. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9138. protected:
  9139. ServerTestWithAI_PASSIVE()
  9140. : cli_(HOST, PORT)
  9141. #ifdef CPPHTTPLIB_SSL_ENABLED
  9142. ,
  9143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9144. #endif
  9145. {
  9146. #ifdef CPPHTTPLIB_SSL_ENABLED
  9147. cli_.enable_server_certificate_verification(false);
  9148. #endif
  9149. }
  9150. virtual void SetUp() {
  9151. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9152. res.set_content("Hello World!", "text/plain");
  9153. });
  9154. t_ = thread(
  9155. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9156. svr_.wait_until_ready();
  9157. }
  9158. virtual void TearDown() {
  9159. svr_.stop();
  9160. t_.join();
  9161. }
  9162. #ifdef CPPHTTPLIB_SSL_ENABLED
  9163. SSLClient cli_;
  9164. SSLServer svr_;
  9165. #else
  9166. Client cli_;
  9167. Server svr_;
  9168. #endif
  9169. thread t_;
  9170. };
  9171. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9172. auto res = cli_.Get("/hi");
  9173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9174. EXPECT_EQ(StatusCode::OK_200, res->status);
  9175. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9176. EXPECT_EQ("Hello World!", res->body);
  9177. }
  9178. class ServerUpDownTest : public ::testing::Test {
  9179. protected:
  9180. ServerUpDownTest() : cli_(HOST, PORT) {}
  9181. virtual void SetUp() {
  9182. t_ = thread([&]() {
  9183. svr_.bind_to_any_port(HOST);
  9184. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9185. ASSERT_TRUE(svr_.listen_after_bind());
  9186. });
  9187. svr_.wait_until_ready();
  9188. }
  9189. virtual void TearDown() {
  9190. svr_.stop();
  9191. t_.join();
  9192. }
  9193. Client cli_;
  9194. Server svr_;
  9195. thread t_;
  9196. };
  9197. TEST_F(ServerUpDownTest, QuickStartStop) {
  9198. // Should not crash, especially when run with
  9199. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9200. }
  9201. class PayloadMaxLengthTest : public ::testing::Test {
  9202. protected:
  9203. PayloadMaxLengthTest()
  9204. : cli_(HOST, PORT)
  9205. #ifdef CPPHTTPLIB_SSL_ENABLED
  9206. ,
  9207. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9208. #endif
  9209. {
  9210. #ifdef CPPHTTPLIB_SSL_ENABLED
  9211. cli_.enable_server_certificate_verification(false);
  9212. #endif
  9213. }
  9214. virtual void SetUp() {
  9215. svr_.set_payload_max_length(8);
  9216. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9217. res.set_content("test", "text/plain");
  9218. });
  9219. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9220. svr_.wait_until_ready();
  9221. }
  9222. virtual void TearDown() {
  9223. svr_.stop();
  9224. t_.join();
  9225. }
  9226. #ifdef CPPHTTPLIB_SSL_ENABLED
  9227. SSLClient cli_;
  9228. SSLServer svr_;
  9229. #else
  9230. Client cli_;
  9231. Server svr_;
  9232. #endif
  9233. thread t_;
  9234. };
  9235. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9236. auto res = cli_.Post("/test", "123456789", "text/plain");
  9237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9238. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9239. res = cli_.Post("/test", "12345678", "text/plain");
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. }
  9243. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9244. // Test chunked encoding with payload exceeding the 8-byte limit
  9245. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9246. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9248. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9249. }
  9250. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9251. // Test chunked encoding with payload within the 8-byte limit
  9252. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9253. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9255. EXPECT_EQ(StatusCode::OK_200, res->status);
  9256. }
  9257. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9258. // Test using send_request to send chunked data exceeding payload limit
  9259. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9260. "Host: " +
  9261. std::string(HOST) + ":" + std::to_string(PORT) +
  9262. "\r\n"
  9263. "Transfer-Encoding: chunked\r\n"
  9264. "Connection: close\r\n"
  9265. "\r\n"
  9266. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9267. "0123456789\r\n"
  9268. "0\r\n" // End chunk
  9269. "\r\n";
  9270. std::string response;
  9271. bool result = send_request(1, chunked_request, &response);
  9272. if (!result) {
  9273. // If send_request fails, it might be because the server closed the
  9274. // connection due to payload limit enforcement, which is acceptable
  9275. SUCCEED()
  9276. << "Server rejected oversized chunked request (connection closed)";
  9277. } else {
  9278. // If we got a response, check if it's an error response or connection was
  9279. // closed early Short response length indicates connection was closed due to
  9280. // payload limit
  9281. if (response.length() <= 10) {
  9282. SUCCEED() << "Server closed connection for oversized chunked request";
  9283. } else {
  9284. // Check for error status codes
  9285. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9286. response.find("Payload Too Large") != std::string::npos ||
  9287. response.find("400") != std::string::npos);
  9288. }
  9289. }
  9290. }
  9291. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9292. // Test request without Content-Length header exceeding payload limit
  9293. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9294. "Host: " +
  9295. std::string(HOST) + ":" +
  9296. std::to_string(PORT) +
  9297. "\r\n"
  9298. "Connection: close\r\n"
  9299. "\r\n";
  9300. // Add payload exceeding the 8-byte limit
  9301. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9302. request_without_content_length += large_payload;
  9303. std::string response;
  9304. bool result = send_request(1, request_without_content_length, &response);
  9305. if (!result) {
  9306. // If send_request fails, server likely closed connection due to payload
  9307. // limit
  9308. SUCCEED() << "Server rejected oversized request without Content-Length "
  9309. "(connection closed)";
  9310. } else {
  9311. // Check if server responded with error or closed connection early
  9312. if (response.length() <= 10) {
  9313. SUCCEED() << "Server closed connection for oversized request without "
  9314. "Content-Length";
  9315. } else {
  9316. // Check for error status codes
  9317. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9318. response.find("Payload Too Large") != std::string::npos ||
  9319. response.find("400") != std::string::npos);
  9320. }
  9321. }
  9322. }
  9323. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9324. // Test request without Content-Length header within payload limit
  9325. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9326. "Host: " +
  9327. std::string(HOST) + ":" +
  9328. std::to_string(PORT) +
  9329. "\r\n"
  9330. "Connection: close\r\n"
  9331. "\r\n";
  9332. // Add payload within the 8-byte limit
  9333. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9334. request_without_content_length += small_payload;
  9335. std::string response;
  9336. bool result = send_request(1, request_without_content_length, &response);
  9337. // For requests without Content-Length, the server may have different behavior
  9338. // The key is that it should not reject due to payload limit for small
  9339. // payloads
  9340. if (result) {
  9341. // Check for any HTTP response (success or error, but not connection closed)
  9342. if (response.length() > 10) {
  9343. SUCCEED()
  9344. << "Server processed request without Content-Length within limit";
  9345. } else {
  9346. // Short response might indicate connection closed, which is acceptable
  9347. SUCCEED() << "Server closed connection for request without "
  9348. "Content-Length (acceptable behavior)";
  9349. }
  9350. } else {
  9351. // Connection failure might be due to protocol requirements
  9352. SUCCEED() << "Connection issue with request without Content-Length "
  9353. "(environment-specific)";
  9354. }
  9355. }
  9356. class LargePayloadMaxLengthTest : public ::testing::Test {
  9357. protected:
  9358. LargePayloadMaxLengthTest()
  9359. : cli_(HOST, PORT)
  9360. #ifdef CPPHTTPLIB_SSL_ENABLED
  9361. ,
  9362. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9363. #endif
  9364. {
  9365. #ifdef CPPHTTPLIB_SSL_ENABLED
  9366. cli_.enable_server_certificate_verification(false);
  9367. #endif
  9368. }
  9369. virtual void SetUp() {
  9370. // Set 10MB payload limit
  9371. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9372. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9373. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9374. res.set_content("Large payload test", "text/plain");
  9375. });
  9376. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9377. svr_.wait_until_ready();
  9378. }
  9379. virtual void TearDown() {
  9380. svr_.stop();
  9381. t_.join();
  9382. }
  9383. #ifdef CPPHTTPLIB_SSL_ENABLED
  9384. SSLClient cli_;
  9385. SSLServer svr_;
  9386. #else
  9387. Client cli_;
  9388. Server svr_;
  9389. #endif
  9390. thread t_;
  9391. };
  9392. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9393. // Test chunked encoding with payload within 10MB limit
  9394. std::string medium_payload(5 * 1024 * 1024,
  9395. 'A'); // 5MB payload, within 10MB limit
  9396. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9398. EXPECT_EQ(StatusCode::OK_200, res->status);
  9399. }
  9400. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9401. // Test chunked encoding with payload exceeding 10MB limit
  9402. std::string large_payload(12 * 1024 * 1024,
  9403. 'B'); // 12MB payload, exceeds 10MB limit
  9404. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9405. // Server may either return 413 or close the connection
  9406. if (res) {
  9407. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9408. } else {
  9409. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9410. }
  9411. }
  9412. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9413. // Test request without Content-Length header within 10MB limit
  9414. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9415. "Host: " +
  9416. std::string(HOST) + ":" +
  9417. std::to_string(PORT) +
  9418. "\r\n"
  9419. "Connection: close\r\n"
  9420. "\r\n";
  9421. // Add 1MB payload (within 10MB limit)
  9422. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9423. request_without_content_length += medium_payload;
  9424. std::string response;
  9425. bool result = send_request(5, request_without_content_length, &response);
  9426. if (result) {
  9427. // Should get a proper HTTP response for payloads within limit
  9428. if (response.length() > 10) {
  9429. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9430. "10MB limit";
  9431. } else {
  9432. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9433. "Content-Length)";
  9434. }
  9435. } else {
  9436. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9437. }
  9438. }
  9439. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9440. // Test request without Content-Length header exceeding 10MB limit
  9441. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9442. "Host: " +
  9443. std::string(HOST) + ":" +
  9444. std::to_string(PORT) +
  9445. "\r\n"
  9446. "Connection: close\r\n"
  9447. "\r\n";
  9448. // Add 12MB payload (exceeds 10MB limit)
  9449. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9450. request_without_content_length += large_payload;
  9451. std::string response;
  9452. bool result = send_request(10, request_without_content_length, &response);
  9453. if (!result) {
  9454. // Server should close connection due to payload limit
  9455. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9456. "(connection closed)";
  9457. } else {
  9458. // Check for error response
  9459. if (response.length() <= 10) {
  9460. SUCCEED()
  9461. << "Server closed connection for 12MB request exceeding 10MB limit";
  9462. } else {
  9463. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9464. response.find("Payload Too Large") != std::string::npos ||
  9465. response.find("400") != std::string::npos);
  9466. }
  9467. }
  9468. }
  9469. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9470. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9471. // path.
  9472. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9473. Server svr;
  9474. const size_t LIMIT = 64 * 1024; // 64KB
  9475. svr.set_payload_max_length(LIMIT);
  9476. size_t total = 0;
  9477. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9478. const ContentReader &content_reader) {
  9479. content_reader([&](const char * /*data*/, size_t len) {
  9480. total += len;
  9481. return true;
  9482. });
  9483. res.status = 200;
  9484. res.set_content("stream_ok", "text/plain");
  9485. });
  9486. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9487. auto se = detail::scope_exit([&] {
  9488. svr.stop();
  9489. thread.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. // Prepare 256KB raw data and gzip-compress it
  9494. std::string raw(256 * 1024, 'A');
  9495. std::string gz;
  9496. {
  9497. z_stream zs{};
  9498. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9499. Z_DEFAULT_STRATEGY);
  9500. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9501. zs.avail_in = static_cast<uInt>(raw.size());
  9502. char outbuf[4096];
  9503. int ret;
  9504. do {
  9505. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9506. zs.avail_out = sizeof(outbuf);
  9507. ret = deflate(&zs, Z_FINISH);
  9508. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9509. } while (ret != Z_STREAM_END);
  9510. deflateEnd(&zs);
  9511. }
  9512. Client cli(HOST, PORT);
  9513. cli.set_connection_timeout(std::chrono::seconds(5));
  9514. Headers headers = {{"Content-Encoding", "gzip"}};
  9515. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9516. "application/octet-stream");
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. // Server must reject oversized decompressed payloads with 413.
  9519. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9520. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9521. EXPECT_LE(total, LIMIT);
  9522. }
  9523. #ifndef CPPHTTPLIB_SSL_ENABLED
  9524. // For a request with neither Content-Length nor Transfer-Encoding, the
  9525. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9526. // compressed wire bytes straight to the ContentReader without ever routing
  9527. // them through the decompressor, so payload_max_length_ only bounded the
  9528. // compressed size on the wire, not the decompressed size.
  9529. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9530. Server svr;
  9531. const size_t LIMIT = 64 * 1024; // 64KB
  9532. svr.set_payload_max_length(LIMIT);
  9533. size_t total = 0;
  9534. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9535. const ContentReader &content_reader) {
  9536. content_reader([&](const char * /*data*/, size_t len) {
  9537. total += len;
  9538. return true;
  9539. });
  9540. res.status = 200;
  9541. res.set_content("stream_ok", "text/plain");
  9542. });
  9543. auto port = svr.bind_to_any_port(HOST);
  9544. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9545. auto se = detail::scope_exit([&] {
  9546. svr.stop();
  9547. thread.join();
  9548. ASSERT_FALSE(svr.is_running());
  9549. });
  9550. svr.wait_until_ready();
  9551. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9552. // StreamingGzipDecompression test above.
  9553. std::string raw(256 * 1024, 'A');
  9554. std::string gz;
  9555. {
  9556. httplib::detail::gzip_compressor compressor;
  9557. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9558. [&](const char *chunk, size_t len) {
  9559. gz.append(chunk, len);
  9560. return true;
  9561. });
  9562. ASSERT_TRUE(result);
  9563. }
  9564. // Send the gzip body over raw TCP with neither Content-Length nor
  9565. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9566. // kicks in.
  9567. std::string req = "POST /stream HTTP/1.1\r\n"
  9568. "Host: " +
  9569. std::string(HOST) + ":" + std::to_string(port) +
  9570. "\r\n"
  9571. "Content-Encoding: gzip\r\n"
  9572. "Connection: close\r\n"
  9573. "\r\n" +
  9574. gz;
  9575. std::string response;
  9576. ASSERT_TRUE(send_request(5, req, &response, port));
  9577. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9578. EXPECT_LE(total, LIMIT);
  9579. }
  9580. #endif
  9581. #endif
  9582. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9583. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9584. // the payload must be passed through untouched instead of being rejected.
  9585. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9586. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9587. Server svr;
  9588. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9589. res.set_content(body, "image/jpeg");
  9590. res.set_header("Content-Encoding", "UTF-8");
  9591. });
  9592. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9593. res.set_content(body, "image/jpeg");
  9594. res.set_header("Content-Encoding", "identity");
  9595. });
  9596. svr.Post("/echo", [](const Request &req, Response &res) {
  9597. res.set_content(req.body, "image/jpeg");
  9598. });
  9599. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9600. auto se = detail::scope_exit([&] {
  9601. svr.stop();
  9602. t.join();
  9603. ASSERT_FALSE(svr.is_running());
  9604. });
  9605. svr.wait_until_ready();
  9606. Client cli(HOST, PORT);
  9607. {
  9608. auto res = cli.Get("/image");
  9609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9610. EXPECT_EQ(StatusCode::OK_200, res->status);
  9611. EXPECT_EQ(body, res->body);
  9612. }
  9613. {
  9614. auto res = cli.Get("/identity");
  9615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9616. EXPECT_EQ(StatusCode::OK_200, res->status);
  9617. EXPECT_EQ(body, res->body);
  9618. }
  9619. {
  9620. // The same applies to a request body reaching the server.
  9621. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9622. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9624. EXPECT_EQ(StatusCode::OK_200, res->status);
  9625. EXPECT_EQ(body, res->body);
  9626. }
  9627. }
  9628. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9629. // gzip-encoded response even when the build has no zlib support.
  9630. static const char GZIPPED_HELLO_WORLD[] = {
  9631. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9632. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9633. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9634. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9635. // A content coding is a whole token, not something the field value merely
  9636. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9637. // as "fibre" look like Brotli, and turned a multi-coding value like
  9638. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9639. // it was never meant to see.
  9640. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9641. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9642. Server svr;
  9643. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9644. res.set_content(body, "image/jpeg");
  9645. res.set_header("Content-Encoding", "fibre");
  9646. });
  9647. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9648. res.set_content(body, "image/jpeg");
  9649. res.set_header("Content-Encoding", "gzip, br");
  9650. });
  9651. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9652. res.set_content(body, "image/jpeg");
  9653. res.set_header("Content-Encoding", "x-zstd-ish");
  9654. });
  9655. auto port = svr.bind_to_any_port(HOST);
  9656. thread t = thread([&]() { svr.listen_after_bind(); });
  9657. auto se = detail::scope_exit([&] {
  9658. svr.stop();
  9659. t.join();
  9660. ASSERT_FALSE(svr.is_running());
  9661. });
  9662. svr.wait_until_ready();
  9663. Client cli(HOST, port);
  9664. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9665. auto res = cli.Get(path);
  9666. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9667. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9668. // Not a coding we recognize, so the payload comes back untouched
  9669. EXPECT_EQ(body, res->body) << path;
  9670. }
  9671. }
  9672. // A content coding cpp-httplib recognizes but was not built with must be
  9673. // reported as such. Handing the still-compressed payload back to the caller
  9674. // would silently corrupt it.
  9675. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9676. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9677. Server svr;
  9678. // "image/jpeg" keeps the server from applying a content coding of its own,
  9679. // so the hand-crafted Content-Encoding below survives.
  9680. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9681. res.set_content(gzipped, "image/jpeg");
  9682. res.set_header("Content-Encoding", "gzip");
  9683. });
  9684. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9685. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9686. res.set_content(gzipped, "image/jpeg");
  9687. res.set_header("Content-Encoding", "GZIP");
  9688. });
  9689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9690. auto se = detail::scope_exit([&] {
  9691. svr.stop();
  9692. t.join();
  9693. ASSERT_FALSE(svr.is_running());
  9694. });
  9695. svr.wait_until_ready();
  9696. Client cli(HOST, PORT);
  9697. {
  9698. auto res = cli.Get("/gzipped");
  9699. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9701. EXPECT_EQ("Hello World!", res->body);
  9702. #else
  9703. ASSERT_FALSE(res);
  9704. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9705. #endif
  9706. }
  9707. {
  9708. // open_stream() must behave the same way.
  9709. auto handle = cli.open_stream("GET", "/gzipped");
  9710. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9711. ASSERT_TRUE(handle.is_valid());
  9712. std::string received;
  9713. char buf[256];
  9714. ssize_t n;
  9715. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9716. received.append(buf, static_cast<size_t>(n));
  9717. }
  9718. EXPECT_EQ("Hello World!", received);
  9719. #else
  9720. EXPECT_FALSE(handle.is_valid());
  9721. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9722. #endif
  9723. }
  9724. {
  9725. // A differently-cased coding must not be mistaken for an unknown one, or
  9726. // the body would be handed back still compressed.
  9727. auto res = cli.Get("/gzipped-uppercase");
  9728. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9730. EXPECT_EQ("Hello World!", res->body);
  9731. #else
  9732. ASSERT_FALSE(res);
  9733. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9734. #endif
  9735. }
  9736. }
  9737. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9738. // the same message as the comma-joined one, so both have to be read the same
  9739. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9740. // single gzip coding, and a body the sender says was encoded twice was handed
  9741. // back after one pass, still compressed but presented as decoded.
  9742. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9743. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9744. Server svr;
  9745. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9746. res.set_content(body, "image/jpeg");
  9747. res.headers.emplace("Content-Encoding", "gzip");
  9748. res.headers.emplace("Content-Encoding", "gzip");
  9749. });
  9750. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9751. res.set_content(body, "image/jpeg");
  9752. res.set_header("Content-Encoding", "gzip, gzip");
  9753. });
  9754. auto port = svr.bind_to_any_port(HOST);
  9755. thread t = thread([&]() { svr.listen_after_bind(); });
  9756. auto se = detail::scope_exit([&] {
  9757. svr.stop();
  9758. t.join();
  9759. ASSERT_FALSE(svr.is_running());
  9760. });
  9761. svr.wait_until_ready();
  9762. Client cli(HOST, port);
  9763. // Two codings is not something cpp-httplib decodes, so both representations
  9764. // take the pass-through path rather than one of them being gunzipped once.
  9765. for (const char *path : {"/split", "/joined"}) {
  9766. auto res = cli.Get(path);
  9767. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9768. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9769. EXPECT_EQ(body, res->body) << path;
  9770. }
  9771. }
  9772. // Regression test for DoS vulnerability: a malicious server sending a response
  9773. // without Content-Length header must not cause unbounded memory consumption on
  9774. // the client side. The client should stop reading after a reasonable limit,
  9775. // similar to the server-side set_payload_max_length protection.
  9776. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9777. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9778. #ifndef _WIN32
  9779. signal(SIGPIPE, SIG_IGN);
  9780. #endif
  9781. auto server_thread = std::thread([] {
  9782. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9784. default_socket_options(srv);
  9785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9787. sockaddr_in addr{};
  9788. addr.sin_family = AF_INET;
  9789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9791. int opt = 1;
  9792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9793. #ifdef _WIN32
  9794. reinterpret_cast<const char *>(&opt),
  9795. #else
  9796. &opt,
  9797. #endif
  9798. sizeof(opt));
  9799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9800. ::listen(srv, 1);
  9801. sockaddr_in cli_addr{};
  9802. socklen_t cli_len = sizeof(cli_addr);
  9803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9804. if (cli != INVALID_SOCKET) {
  9805. char buf[4096];
  9806. ::recv(cli, buf, sizeof(buf), 0);
  9807. // Malicious response: no Content-Length, no chunked encoding
  9808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9809. "Connection: close\r\n"
  9810. "\r\n";
  9811. ::send(cli,
  9812. #ifdef _WIN32
  9813. static_cast<const char *>(response_header.c_str()),
  9814. static_cast<int>(response_header.size()),
  9815. #else
  9816. response_header.c_str(), response_header.size(),
  9817. #endif
  9818. 0);
  9819. // Send 10MB of data
  9820. std::string chunk(64 * 1024, 'A');
  9821. size_t total_sent = 0;
  9822. while (total_sent < MALICIOUS_DATA_SIZE) {
  9823. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9824. auto sent = ::send(cli,
  9825. #ifdef _WIN32
  9826. static_cast<const char *>(chunk.c_str()),
  9827. static_cast<int>(to_send),
  9828. #else
  9829. chunk.c_str(), to_send,
  9830. #endif
  9831. 0);
  9832. if (sent <= 0) break;
  9833. total_sent += static_cast<size_t>(sent);
  9834. }
  9835. detail::close_socket(cli);
  9836. }
  9837. detail::close_socket(srv);
  9838. });
  9839. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9840. size_t total_read = 0;
  9841. {
  9842. Client cli("127.0.0.1", PORT + 2);
  9843. cli.set_read_timeout(5, 0);
  9844. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9845. auto stream = cli.open_stream("GET", "/malicious");
  9846. ASSERT_TRUE(stream.is_valid());
  9847. char buffer[64 * 1024];
  9848. ssize_t n;
  9849. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9850. total_read += static_cast<size_t>(n);
  9851. }
  9852. } // StreamHandle and Client destroyed here, closing the socket
  9853. server_thread.join();
  9854. // With set_payload_max_length, the client must stop reading before consuming
  9855. // all 10MB. The read loop should be cut off at or near the configured limit.
  9856. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9857. << "Client read " << total_read << " bytes, exceeding the configured "
  9858. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9859. }
  9860. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9861. // the entire response body without truncation.
  9862. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9863. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9864. #ifndef _WIN32
  9865. signal(SIGPIPE, SIG_IGN);
  9866. #endif
  9867. auto server_thread = std::thread([] {
  9868. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9869. default_socket_options(srv);
  9870. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9871. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9872. sockaddr_in addr{};
  9873. addr.sin_family = AF_INET;
  9874. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9875. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9876. int opt = 1;
  9877. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9878. #ifdef _WIN32
  9879. reinterpret_cast<const char *>(&opt),
  9880. #else
  9881. &opt,
  9882. #endif
  9883. sizeof(opt));
  9884. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9885. ::listen(srv, 1);
  9886. sockaddr_in cli_addr{};
  9887. socklen_t cli_len = sizeof(cli_addr);
  9888. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9889. if (cli != INVALID_SOCKET) {
  9890. char buf[4096];
  9891. ::recv(cli, buf, sizeof(buf), 0);
  9892. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9893. "Connection: close\r\n"
  9894. "\r\n";
  9895. ::send(cli,
  9896. #ifdef _WIN32
  9897. static_cast<const char *>(response_header.c_str()),
  9898. static_cast<int>(response_header.size()),
  9899. #else
  9900. response_header.c_str(), response_header.size(),
  9901. #endif
  9902. 0);
  9903. std::string chunk(64 * 1024, 'A');
  9904. size_t total_sent = 0;
  9905. while (total_sent < DATA_SIZE) {
  9906. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9907. auto sent = ::send(cli,
  9908. #ifdef _WIN32
  9909. static_cast<const char *>(chunk.c_str()),
  9910. static_cast<int>(to_send),
  9911. #else
  9912. chunk.c_str(), to_send,
  9913. #endif
  9914. 0);
  9915. if (sent <= 0) break;
  9916. total_sent += static_cast<size_t>(sent);
  9917. }
  9918. #ifdef _WIN32
  9919. ::shutdown(cli, SD_SEND);
  9920. #else
  9921. ::shutdown(cli, SHUT_WR);
  9922. #endif
  9923. // Drain until the client closes its end, ensuring all data is delivered
  9924. char drain[1024];
  9925. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9926. detail::close_socket(cli);
  9927. }
  9928. detail::close_socket(srv);
  9929. });
  9930. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9931. size_t total_read = 0;
  9932. {
  9933. Client cli("127.0.0.1", PORT + 2);
  9934. cli.set_read_timeout(5, 0);
  9935. cli.set_payload_max_length(0); // 0 means no limit
  9936. auto stream = cli.open_stream("GET", "/data");
  9937. ASSERT_TRUE(stream.is_valid());
  9938. char buffer[64 * 1024];
  9939. ssize_t n;
  9940. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9941. total_read += static_cast<size_t>(n);
  9942. }
  9943. }
  9944. server_thread.join();
  9945. EXPECT_EQ(total_read, DATA_SIZE)
  9946. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9947. << " bytes without truncation, but only read " << total_read << " bytes.";
  9948. }
  9949. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9950. // enormous Content-Length must not cause the client to pre-allocate a huge
  9951. // response body buffer. The reservation is capped at payload_max_length_, and
  9952. // the read itself fails when the body exceeds the limit.
  9953. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9954. #ifndef _WIN32
  9955. signal(SIGPIPE, SIG_IGN);
  9956. #endif
  9957. auto server_thread = std::thread([] {
  9958. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9959. default_socket_options(srv);
  9960. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9961. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9962. sockaddr_in addr{};
  9963. addr.sin_family = AF_INET;
  9964. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9965. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9966. int opt = 1;
  9967. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9968. #ifdef _WIN32
  9969. reinterpret_cast<const char *>(&opt),
  9970. #else
  9971. &opt,
  9972. #endif
  9973. sizeof(opt));
  9974. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9975. ::listen(srv, 1);
  9976. sockaddr_in cli_addr{};
  9977. socklen_t cli_len = sizeof(cli_addr);
  9978. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9979. if (cli != INVALID_SOCKET) {
  9980. char buf[4096];
  9981. ::recv(cli, buf, sizeof(buf), 0);
  9982. // Malicious response: claim a 20GB body but send only a tiny payload.
  9983. std::string response = "HTTP/1.1 200 OK\r\n"
  9984. "Content-Length: 20000000000\r\n"
  9985. "\r\n"
  9986. "abc";
  9987. ::send(cli,
  9988. #ifdef _WIN32
  9989. static_cast<const char *>(response.c_str()),
  9990. static_cast<int>(response.size()),
  9991. #else
  9992. response.c_str(), response.size(),
  9993. #endif
  9994. 0);
  9995. detail::close_socket(cli);
  9996. }
  9997. detail::close_socket(srv);
  9998. });
  9999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10000. {
  10001. Client cli("127.0.0.1", PORT + 2);
  10002. cli.set_read_timeout(5, 0);
  10003. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10004. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10005. // (server claims more bytes than payload_max_length permits), but it must
  10006. // not exhaust memory before getting there.
  10007. auto res = cli.Get("/malicious");
  10008. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10009. }
  10010. server_thread.join();
  10011. }
  10012. // Verify that content_receiver bypasses the default payload_max_length,
  10013. // allowing streaming downloads larger than 100MB without requiring an explicit
  10014. // set_payload_max_length call.
  10015. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10016. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10017. #ifndef _WIN32
  10018. signal(SIGPIPE, SIG_IGN);
  10019. #endif
  10020. auto server_thread = std::thread([] {
  10021. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10022. default_socket_options(srv);
  10023. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10025. sockaddr_in addr{};
  10026. addr.sin_family = AF_INET;
  10027. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10028. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10029. int opt = 1;
  10030. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10031. #ifdef _WIN32
  10032. reinterpret_cast<const char *>(&opt),
  10033. #else
  10034. &opt,
  10035. #endif
  10036. sizeof(opt));
  10037. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10038. ::listen(srv, 1);
  10039. sockaddr_in cli_addr{};
  10040. socklen_t cli_len = sizeof(cli_addr);
  10041. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10042. if (cli != INVALID_SOCKET) {
  10043. char buf[4096];
  10044. ::recv(cli, buf, sizeof(buf), 0);
  10045. // Response with Content-Length larger than default 100MB limit
  10046. auto content_length = std::to_string(DATA_SIZE);
  10047. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10048. "Content-Length: " +
  10049. content_length +
  10050. "\r\n"
  10051. "Connection: close\r\n"
  10052. "\r\n";
  10053. ::send(cli,
  10054. #ifdef _WIN32
  10055. static_cast<const char *>(response_header.c_str()),
  10056. static_cast<int>(response_header.size()),
  10057. #else
  10058. response_header.c_str(), response_header.size(),
  10059. #endif
  10060. 0);
  10061. std::string chunk(64 * 1024, 'A');
  10062. size_t total_sent = 0;
  10063. while (total_sent < DATA_SIZE) {
  10064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10065. auto sent = ::send(cli,
  10066. #ifdef _WIN32
  10067. static_cast<const char *>(chunk.c_str()),
  10068. static_cast<int>(to_send),
  10069. #else
  10070. chunk.c_str(), to_send,
  10071. #endif
  10072. 0);
  10073. if (sent <= 0) break;
  10074. total_sent += static_cast<size_t>(sent);
  10075. }
  10076. detail::close_socket(cli);
  10077. }
  10078. detail::close_socket(srv);
  10079. });
  10080. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10081. size_t total_received = 0;
  10082. {
  10083. Client cli("127.0.0.1", PORT + 2);
  10084. cli.set_read_timeout(10, 0);
  10085. // Do NOT call set_payload_max_length — use the default 100MB limit
  10086. auto res =
  10087. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10088. total_received += data_length;
  10089. return true;
  10090. });
  10091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10092. EXPECT_EQ(StatusCode::OK_200, res->status);
  10093. }
  10094. server_thread.join();
  10095. EXPECT_EQ(total_received, DATA_SIZE)
  10096. << "With content_receiver, the client should read all " << DATA_SIZE
  10097. << " bytes despite the default 100MB payload_max_length, but only read "
  10098. << total_received << " bytes.";
  10099. }
  10100. // Verify that an explicit set_payload_max_length smaller than the response is
  10101. // enforced even when a content_receiver is used.
  10102. TEST(ClientVulnerabilityTest,
  10103. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10105. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10106. #ifndef _WIN32
  10107. signal(SIGPIPE, SIG_IGN);
  10108. #endif
  10109. auto server_thread = std::thread([] {
  10110. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10111. default_socket_options(srv);
  10112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10113. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10114. sockaddr_in addr{};
  10115. addr.sin_family = AF_INET;
  10116. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10117. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10118. int opt = 1;
  10119. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10120. #ifdef _WIN32
  10121. reinterpret_cast<const char *>(&opt),
  10122. #else
  10123. &opt,
  10124. #endif
  10125. sizeof(opt));
  10126. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10127. ::listen(srv, 1);
  10128. sockaddr_in cli_addr{};
  10129. socklen_t cli_len = sizeof(cli_addr);
  10130. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10131. if (cli != INVALID_SOCKET) {
  10132. char buf[4096];
  10133. ::recv(cli, buf, sizeof(buf), 0);
  10134. auto content_length = std::to_string(DATA_SIZE);
  10135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10136. "Content-Length: " +
  10137. content_length +
  10138. "\r\n"
  10139. "Connection: close\r\n"
  10140. "\r\n";
  10141. ::send(cli,
  10142. #ifdef _WIN32
  10143. static_cast<const char *>(response_header.c_str()),
  10144. static_cast<int>(response_header.size()),
  10145. #else
  10146. response_header.c_str(), response_header.size(),
  10147. #endif
  10148. 0);
  10149. std::string chunk(64 * 1024, 'A');
  10150. size_t total_sent = 0;
  10151. while (total_sent < DATA_SIZE) {
  10152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10153. auto sent = ::send(cli,
  10154. #ifdef _WIN32
  10155. static_cast<const char *>(chunk.c_str()),
  10156. static_cast<int>(to_send),
  10157. #else
  10158. chunk.c_str(), to_send,
  10159. #endif
  10160. 0);
  10161. if (sent <= 0) break;
  10162. total_sent += static_cast<size_t>(sent);
  10163. }
  10164. detail::close_socket(cli);
  10165. }
  10166. detail::close_socket(srv);
  10167. });
  10168. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10169. size_t total_received = 0;
  10170. {
  10171. Client cli("127.0.0.1", PORT + 2);
  10172. cli.set_read_timeout(10, 0);
  10173. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10174. auto res =
  10175. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10176. total_received += data_length;
  10177. return true;
  10178. });
  10179. // Should fail because 200MB exceeds the explicit 150MB limit
  10180. EXPECT_FALSE(res);
  10181. }
  10182. server_thread.join();
  10183. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10184. << "Client with content_receiver should respect the explicit "
  10185. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10186. << total_received << " bytes.";
  10187. }
  10188. // Verify that an explicit set_payload_max_length larger than the response
  10189. // allows the content_receiver to read all data successfully.
  10190. TEST(ClientVulnerabilityTest,
  10191. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10192. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10193. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10194. #ifndef _WIN32
  10195. signal(SIGPIPE, SIG_IGN);
  10196. #endif
  10197. auto server_thread = std::thread([] {
  10198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10199. default_socket_options(srv);
  10200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10202. sockaddr_in addr{};
  10203. addr.sin_family = AF_INET;
  10204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10206. int opt = 1;
  10207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10208. #ifdef _WIN32
  10209. reinterpret_cast<const char *>(&opt),
  10210. #else
  10211. &opt,
  10212. #endif
  10213. sizeof(opt));
  10214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10215. ::listen(srv, 1);
  10216. sockaddr_in cli_addr{};
  10217. socklen_t cli_len = sizeof(cli_addr);
  10218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10219. if (cli != INVALID_SOCKET) {
  10220. char buf[4096];
  10221. ::recv(cli, buf, sizeof(buf), 0);
  10222. auto content_length = std::to_string(DATA_SIZE);
  10223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10224. "Content-Length: " +
  10225. content_length +
  10226. "\r\n"
  10227. "Connection: close\r\n"
  10228. "\r\n";
  10229. ::send(cli,
  10230. #ifdef _WIN32
  10231. static_cast<const char *>(response_header.c_str()),
  10232. static_cast<int>(response_header.size()),
  10233. #else
  10234. response_header.c_str(), response_header.size(),
  10235. #endif
  10236. 0);
  10237. std::string chunk(64 * 1024, 'A');
  10238. size_t total_sent = 0;
  10239. while (total_sent < DATA_SIZE) {
  10240. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10241. auto sent = ::send(cli,
  10242. #ifdef _WIN32
  10243. static_cast<const char *>(chunk.c_str()),
  10244. static_cast<int>(to_send),
  10245. #else
  10246. chunk.c_str(), to_send,
  10247. #endif
  10248. 0);
  10249. if (sent <= 0) break;
  10250. total_sent += static_cast<size_t>(sent);
  10251. }
  10252. #ifdef _WIN32
  10253. ::shutdown(cli, SD_SEND);
  10254. #else
  10255. ::shutdown(cli, SHUT_WR);
  10256. #endif
  10257. char drain[1024];
  10258. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10259. detail::close_socket(cli);
  10260. }
  10261. detail::close_socket(srv);
  10262. });
  10263. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10264. size_t total_received = 0;
  10265. {
  10266. Client cli("127.0.0.1", PORT + 2);
  10267. cli.set_read_timeout(10, 0);
  10268. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10269. auto res =
  10270. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10271. total_received += data_length;
  10272. return true;
  10273. });
  10274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10275. EXPECT_EQ(StatusCode::OK_200, res->status);
  10276. }
  10277. server_thread.join();
  10278. EXPECT_EQ(total_received, DATA_SIZE)
  10279. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10280. << " bytes (larger than " << DATA_SIZE
  10281. << " bytes response), content_receiver should read all data, but only "
  10282. "read "
  10283. << total_received << " bytes.";
  10284. }
  10285. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10286. // Regression test for "zip bomb" attack on the client side: a malicious server
  10287. // sends a small gzip-compressed response that decompresses to a huge payload.
  10288. // The client must enforce payload_max_length on the decompressed size.
  10289. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10290. constexpr size_t DECOMPRESSED_SIZE =
  10291. 10 * 1024 * 1024; // 10MB after decompression
  10292. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10293. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10294. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10295. std::string compressed;
  10296. {
  10297. httplib::detail::gzip_compressor compressor;
  10298. bool ok =
  10299. compressor.compress(uncompressed.data(), uncompressed.size(),
  10300. /*last=*/true, [&](const char *buf, size_t len) {
  10301. compressed.append(buf, len);
  10302. return true;
  10303. });
  10304. ASSERT_TRUE(ok);
  10305. }
  10306. // Sanity: compressed data should be much smaller than the decompressed size
  10307. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10308. #ifndef _WIN32
  10309. signal(SIGPIPE, SIG_IGN);
  10310. #endif
  10311. // Set up the listening socket in the main thread so the server is guaranteed
  10312. // to be ready before the client connects (eliminates race condition).
  10313. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10314. default_socket_options(srv);
  10315. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10317. sockaddr_in addr{};
  10318. addr.sin_family = AF_INET;
  10319. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10320. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10321. int opt = 1;
  10322. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10323. #ifdef _WIN32
  10324. reinterpret_cast<const char *>(&opt),
  10325. #else
  10326. &opt,
  10327. #endif
  10328. sizeof(opt));
  10329. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10330. ASSERT_EQ(0, ::listen(srv, 1));
  10331. auto server_thread = std::thread([&compressed, srv] {
  10332. sockaddr_in cli_addr{};
  10333. socklen_t cli_len = sizeof(cli_addr);
  10334. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10335. if (cli != INVALID_SOCKET) {
  10336. // Read the full HTTP request (until \r\n\r\n)
  10337. char buf[4096];
  10338. size_t total = 0;
  10339. while (total < sizeof(buf)) {
  10340. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10341. if (n <= 0) break;
  10342. total += static_cast<size_t>(n);
  10343. // Check for end of headers
  10344. if (total >= 4) {
  10345. std::string req(buf, total);
  10346. if (req.find("\r\n\r\n") != std::string::npos) break;
  10347. }
  10348. }
  10349. // Malicious response: gzip-compressed body, no Content-Length
  10350. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10351. "Content-Encoding: gzip\r\n"
  10352. "Connection: close\r\n"
  10353. "\r\n";
  10354. ::send(cli,
  10355. #ifdef _WIN32
  10356. static_cast<const char *>(response_header.c_str()),
  10357. static_cast<int>(response_header.size()),
  10358. #else
  10359. response_header.c_str(), response_header.size(),
  10360. #endif
  10361. 0);
  10362. // Send the compressed payload (small on the wire, huge when decompressed)
  10363. size_t total_sent = 0;
  10364. while (total_sent < compressed.size()) {
  10365. auto to_send = std::min(compressed.size() - total_sent,
  10366. static_cast<size_t>(64 * 1024));
  10367. auto sent =
  10368. ::send(cli,
  10369. #ifdef _WIN32
  10370. static_cast<const char *>(compressed.c_str() + total_sent),
  10371. static_cast<int>(to_send),
  10372. #else
  10373. compressed.c_str() + total_sent, to_send,
  10374. #endif
  10375. 0);
  10376. if (sent <= 0) break;
  10377. total_sent += static_cast<size_t>(sent);
  10378. }
  10379. detail::close_socket(cli);
  10380. }
  10381. });
  10382. auto se = detail::scope_exit([&] {
  10383. detail::close_socket(srv);
  10384. server_thread.join();
  10385. });
  10386. size_t total_decompressed = 0;
  10387. {
  10388. Client cli("127.0.0.1", PORT + 3);
  10389. cli.set_read_timeout(5, 0);
  10390. cli.set_decompress(true);
  10391. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10392. auto stream = cli.open_stream("GET", "/zipbomb");
  10393. ASSERT_TRUE(stream.is_valid());
  10394. char buffer[64 * 1024];
  10395. ssize_t n;
  10396. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10397. total_decompressed += static_cast<size_t>(n);
  10398. }
  10399. }
  10400. // The decompressed size must be capped by payload_max_length. Without
  10401. // protection, the client would decompress the full 10MB from a tiny
  10402. // compressed payload, enabling a zip bomb DoS attack.
  10403. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10404. << "Client decompressed " << total_decompressed
  10405. << " bytes from a gzip response. The decompressed size should be "
  10406. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10407. }
  10408. #endif
  10409. TEST(HostAndPortPropertiesTest, NoSSL) {
  10410. httplib::Client cli("www.google.com", 1234);
  10411. ASSERT_EQ("www.google.com", cli.host());
  10412. ASSERT_EQ(1234, cli.port());
  10413. }
  10414. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10415. httplib::Client cli("www.google.com:1234");
  10416. ASSERT_EQ("www.google.com", cli.host());
  10417. ASSERT_EQ(1234, cli.port());
  10418. }
  10419. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10420. // Port number that overflows int — should not crash, client becomes invalid
  10421. httplib::Client cli("http://www.google.com:99999999999999999999");
  10422. ASSERT_FALSE(cli.is_valid());
  10423. }
  10424. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10425. // Port 99999 exceeds valid range (1-65535) — should not crash
  10426. httplib::Client cli("http://www.google.com:99999");
  10427. ASSERT_FALSE(cli.is_valid());
  10428. }
  10429. #ifdef CPPHTTPLIB_SSL_ENABLED
  10430. TEST(HostAndPortPropertiesTest, SSL) {
  10431. httplib::SSLClient cli("www.google.com");
  10432. ASSERT_EQ("www.google.com", cli.host());
  10433. ASSERT_EQ(443, cli.port());
  10434. }
  10435. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10436. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10437. std::string cert;
  10438. read_file(CA_CERT_FILE, cert);
  10439. httplib::SSLClient httplib_client("www.google.com");
  10440. // Load CA store first time
  10441. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10442. // Load CA store second time (update)
  10443. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10444. // Verify client is still valid and can make connections
  10445. httplib_client.enable_server_certificate_verification(true);
  10446. auto res = httplib_client.Get("/");
  10447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10448. // Google may return 200 or 301 depending on various factors
  10449. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10450. res->status == StatusCode::MovedPermanently_301);
  10451. }
  10452. TEST(SSLClientTest, ServerNameIndication_Online) {
  10453. auto host = "httpbingo.org";
  10454. auto path = std::string{"/get"};
  10455. SSLClient cli(host, 443);
  10456. auto res = cli.Get(path);
  10457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10458. ASSERT_EQ(StatusCode::OK_200, res->status);
  10459. }
  10460. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10461. // Use a site that will cause SSL verification failure due to self-signed cert
  10462. SSLClient cli("self-signed.badssl.com", 443);
  10463. cli.enable_server_certificate_verification(true);
  10464. auto res = cli.Get("/");
  10465. ASSERT_TRUE(!res);
  10466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10467. // Verify backend error is captured for SSLServerVerification
  10468. // This occurs when certificate verification fails
  10469. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10470. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10471. EXPECT_NE(0UL, res.ssl_backend_error());
  10472. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10473. // For OpenSSL, ssl_error is 0 for verification errors
  10474. EXPECT_EQ(0, res.ssl_error());
  10475. #if !defined(_WIN32) || \
  10476. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10477. // On non-Windows or when Windows Schannel is disabled, the error comes
  10478. // from OpenSSL's verification
  10479. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10480. res.ssl_backend_error());
  10481. #endif
  10482. #endif
  10483. }
  10484. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10485. // Use a site where hostname doesn't match the certificate
  10486. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10487. SSLClient cli("wrong.host.badssl.com", 443);
  10488. cli.enable_server_certificate_verification(true);
  10489. cli.enable_server_hostname_verification(true);
  10490. auto res = cli.Get("/");
  10491. ASSERT_TRUE(!res);
  10492. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10493. // Verify backend error is captured for hostname verification failure
  10494. EXPECT_NE(0UL, res.ssl_backend_error());
  10495. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10496. // For OpenSSL, ssl_error is 0 for verification errors
  10497. EXPECT_EQ(0, res.ssl_error());
  10498. #if !defined(_WIN32) || \
  10499. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10500. // On non-Windows or when Windows Schannel is disabled, the error comes
  10501. // from OpenSSL's hostname verification
  10502. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10503. res.ssl_backend_error());
  10504. #endif
  10505. #endif
  10506. }
  10507. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10508. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10509. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10510. SSLClient cli("www.google.com", 443);
  10511. cli.enable_server_certificate_verification(true);
  10512. auto res = cli.Get("/");
  10513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10514. }
  10515. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10516. SSLClient cli("www.google.com", 443);
  10517. cli.enable_server_certificate_verification(true);
  10518. cli.enable_windows_certificate_verification(false);
  10519. auto res = cli.Get("/");
  10520. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10521. }
  10522. #endif
  10523. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10524. Client cli("https://google.com");
  10525. auto res = cli.Get("/");
  10526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10528. }
  10529. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10530. SSLClient cli("google.com");
  10531. cli.set_ca_cert_path(CA_CERT_FILE);
  10532. auto res = cli.Get("/");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10535. }
  10536. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10537. SSLClient cli("google.com");
  10538. cli.enable_server_certificate_verification(true);
  10539. cli.set_ca_cert_path("hello");
  10540. auto res = cli.Get("/");
  10541. ASSERT_TRUE(!res);
  10542. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10543. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10544. // should be set
  10545. EXPECT_EQ(0, res.ssl_error());
  10546. // Verify backend error is captured for SSLLoadingCerts
  10547. // This error occurs when loading CA certificates fails
  10548. EXPECT_NE(0UL, res.ssl_backend_error());
  10549. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10550. // OpenSSL specific error codes:
  10551. // > openssl errstr 0x80000002
  10552. // error:80000002:system library::No such file or directory
  10553. // > openssl errstr 0xA000126
  10554. // error:0A000126:SSL routines::unexpected eof while reading
  10555. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10556. res.ssl_backend_error() == 0xA000126);
  10557. #endif
  10558. }
  10559. TEST(SSLClientTest, ServerCertificateVerification4) {
  10560. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10561. ASSERT_TRUE(svr.is_valid());
  10562. svr.Get("/test", [&](const Request &, Response &res) {
  10563. res.set_content("test", "text/plain");
  10564. svr.stop();
  10565. ASSERT_TRUE(true);
  10566. });
  10567. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10568. auto se = detail::scope_exit([&] {
  10569. t.join();
  10570. ASSERT_FALSE(svr.is_running());
  10571. });
  10572. svr.wait_until_ready();
  10573. SSLClient cli("127.0.0.1", PORT);
  10574. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10575. cli.enable_server_certificate_verification(true);
  10576. cli.set_connection_timeout(30);
  10577. auto res = cli.Get("/test");
  10578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10579. ASSERT_EQ(StatusCode::OK_200, res->status);
  10580. }
  10581. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10582. std::string cert;
  10583. read_file(CA_CERT_FILE, cert);
  10584. SSLClient cli("google.com");
  10585. cli.load_ca_cert_store(cert.data(), cert.size());
  10586. const auto res = cli.Get("/");
  10587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10588. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10589. }
  10590. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10591. // clang-format off
  10592. static constexpr char cert[] =
  10593. "GlobalSign Root CA\n"
  10594. "==================\n"
  10595. "-----BEGIN CERTIFICATE-----\n"
  10596. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10597. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10598. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10599. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10600. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10601. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10602. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10603. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10604. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10605. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10606. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10607. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10608. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10609. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10610. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10611. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10612. "-----END CERTIFICATE-----\n";
  10613. // clang-format on
  10614. SSLClient cli("google.com");
  10615. cli.load_ca_cert_store(cert, sizeof(cert));
  10616. const auto res = cli.Get("/");
  10617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10618. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10619. }
  10620. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10621. SSLClient cli("www.youtube.com");
  10622. cli.set_ca_cert_path(CA_CERT_FILE);
  10623. cli.enable_server_certificate_verification(true);
  10624. cli.set_follow_location(true);
  10625. auto res = cli.Get("/");
  10626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10627. ASSERT_EQ(StatusCode::OK_200, res->status);
  10628. }
  10629. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10630. SSLClient cli("wWw.YouTube.Com");
  10631. cli.set_ca_cert_path(CA_CERT_FILE);
  10632. cli.enable_server_certificate_verification(true);
  10633. cli.enable_server_hostname_verification(true);
  10634. cli.set_follow_location(true);
  10635. auto res = cli.Get("/");
  10636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10637. ASSERT_EQ(StatusCode::OK_200, res->status);
  10638. }
  10639. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10640. SSLClient cli("gOoGlE.COm");
  10641. cli.enable_server_certificate_verification(true);
  10642. cli.enable_server_hostname_verification(true);
  10643. cli.set_follow_location(true);
  10644. auto res = cli.Get("/");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. ASSERT_EQ(StatusCode::OK_200, res->status);
  10647. }
  10648. TEST(SSLClientTest, Issue2004_Online) {
  10649. Client client("https://google.com");
  10650. client.set_follow_location(true);
  10651. auto res = client.Get("/");
  10652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10653. ASSERT_EQ(StatusCode::OK_200, res->status);
  10654. auto body = res->body;
  10655. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10656. }
  10657. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10658. // Create SSLClient with invalid cert/key to make is_valid() return false
  10659. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10660. "nonexistent_key.pem");
  10661. // is_valid() should be false due to cert loading failure
  10662. ASSERT_FALSE(cli.is_valid());
  10663. auto res = cli.Get("/");
  10664. ASSERT_FALSE(res);
  10665. EXPECT_EQ(Error::SSLConnection, res.error());
  10666. }
  10667. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10668. // Test for Issue #2251: SSL error not properly reported when client cert
  10669. // and key paths are swapped or mismatched
  10670. // This simulates the scenario where user accidentally swaps the cert and key
  10671. // files
  10672. // Using client cert file as private key and vice versa (completely wrong)
  10673. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10674. // Should fail validation due to cert/key mismatch
  10675. ASSERT_FALSE(cli.is_valid());
  10676. // Attempt to make a request should fail with proper error
  10677. auto res = cli.Get("/");
  10678. ASSERT_FALSE(res);
  10679. EXPECT_EQ(Error::SSLConnection, res.error());
  10680. // SSL error should be recorded in the Result object (this is the key fix for
  10681. // Issue #2251)
  10682. auto backend_error = res.ssl_backend_error();
  10683. EXPECT_NE(0u, backend_error);
  10684. }
  10685. // Tests cert/key mismatch detection at the TLS context level
  10686. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10687. // Test that using mismatched cert/key causes connection failure.
  10688. // We verify this at the SSLClient level rather than through internal
  10689. // TLS API functions.
  10690. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10691. cli.enable_server_certificate_verification(false);
  10692. cli.set_connection_timeout(2);
  10693. // The mismatch should cause a connection or handshake error
  10694. auto res = cli.Get("/test");
  10695. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10696. // Either way, the request should fail
  10697. EXPECT_FALSE(res);
  10698. }
  10699. #endif
  10700. #if 0
  10701. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10702. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10703. ASSERT_TRUE(cli != nullptr);
  10704. cli->set_address_family(AF_INET6);
  10705. cli->set_interface("en0");
  10706. auto res = cli->Get("/get");
  10707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10708. ASSERT_EQ(StatusCode::OK_200, res->status);
  10709. }
  10710. #endif
  10711. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10712. #ifdef CPPHTTPLIB_SSL_ENABLED
  10713. void ClientCertPresent(
  10714. const std::string &client_cert_file,
  10715. const std::string &client_private_key_file,
  10716. const std::string &client_encrypted_private_key_pass = std::string()) {
  10717. using namespace httplib::tls;
  10718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10719. CLIENT_CA_CERT_DIR);
  10720. ASSERT_TRUE(svr.is_valid());
  10721. svr.Get("/test", [&](const Request &req, Response &res) {
  10722. res.set_content("test", "text/plain");
  10723. auto cert = req.peer_cert();
  10724. ASSERT_TRUE(static_cast<bool>(cert));
  10725. std::string common_name = cert.subject_cn();
  10726. EXPECT_EQ("Common Name", common_name);
  10727. });
  10728. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10729. auto se = detail::scope_exit([&] {
  10730. svr.stop();
  10731. t.join();
  10732. ASSERT_FALSE(svr.is_running());
  10733. });
  10734. svr.wait_until_ready();
  10735. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10736. client_encrypted_private_key_pass);
  10737. cli.enable_server_certificate_verification(false);
  10738. cli.set_connection_timeout(30);
  10739. auto res = cli.Get("/test");
  10740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10741. ASSERT_EQ(StatusCode::OK_200, res->status);
  10742. }
  10743. TEST(SSLClientServerTest, ClientCertPresent) {
  10744. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10745. }
  10746. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10747. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10748. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10749. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10750. }
  10751. // PEM memory-based constructor tests (works with all TLS backends)
  10752. void PemMemoryClientCertPresent(
  10753. const std::string &client_cert_file,
  10754. const std::string &client_private_key_file,
  10755. const std::string &client_encrypted_private_key_pass = std::string()) {
  10756. // Read PEM files into memory
  10757. std::string server_cert_pem, server_key_pem;
  10758. std::string client_ca_pem;
  10759. std::string client_cert_pem, client_key_pem;
  10760. read_file(SERVER_CERT_FILE, server_cert_pem);
  10761. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10762. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10763. read_file(client_cert_file, client_cert_pem);
  10764. read_file(client_private_key_file, client_key_pem);
  10765. // Create server with PEM memory
  10766. SSLServer::PemMemory server_pem = {
  10767. server_cert_pem.c_str(),
  10768. server_cert_pem.size(),
  10769. server_key_pem.c_str(),
  10770. server_key_pem.size(),
  10771. client_ca_pem.c_str(),
  10772. client_ca_pem.size(),
  10773. nullptr // no password for server key
  10774. };
  10775. SSLServer svr(server_pem);
  10776. ASSERT_TRUE(svr.is_valid());
  10777. svr.Get("/test", [&](const Request &, Response &res) {
  10778. res.set_content("test", "text/plain");
  10779. });
  10780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. t.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.wait_until_ready();
  10787. // Create client with PEM memory
  10788. const char *password = client_encrypted_private_key_pass.empty()
  10789. ? nullptr
  10790. : client_encrypted_private_key_pass.c_str();
  10791. SSLClient::PemMemory client_pem = {
  10792. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10793. client_key_pem.size(), password};
  10794. SSLClient cli(HOST, PORT, client_pem);
  10795. cli.enable_server_certificate_verification(false);
  10796. cli.set_connection_timeout(30);
  10797. auto res = cli.Get("/test");
  10798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10799. ASSERT_EQ(StatusCode::OK_200, res->status);
  10800. }
  10801. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10802. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10803. }
  10804. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10805. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10806. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10807. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10808. }
  10809. TEST(SSLClientServerTest, ClientCertMissing) {
  10810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10811. CLIENT_CA_CERT_DIR);
  10812. ASSERT_TRUE(svr.is_valid());
  10813. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10815. auto se = detail::scope_exit([&] {
  10816. svr.stop();
  10817. t.join();
  10818. ASSERT_FALSE(svr.is_running());
  10819. });
  10820. svr.wait_until_ready();
  10821. SSLClient cli(HOST, PORT);
  10822. cli.set_connection_timeout(30);
  10823. auto res = cli.Get("/test");
  10824. ASSERT_TRUE(!res);
  10825. // When client cert is missing and server requires it, connection fails
  10826. // Error type depends on backend implementation
  10827. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10828. res.error() == Error::SSLConnection);
  10829. // Verify backend error is captured
  10830. // Note: This test may have different error codes depending on the exact
  10831. // verification failure
  10832. EXPECT_NE(0UL, res.ssl_backend_error());
  10833. }
  10834. TEST(SSLClientServerTest, TrustDirOptional) {
  10835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10836. ASSERT_TRUE(svr.is_valid());
  10837. svr.Get("/test", [&](const Request &, Response &res) {
  10838. res.set_content("test", "text/plain");
  10839. });
  10840. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10841. auto se = detail::scope_exit([&] {
  10842. svr.stop();
  10843. t.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. });
  10846. svr.wait_until_ready();
  10847. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10848. cli.enable_server_certificate_verification(false);
  10849. cli.set_connection_timeout(30);
  10850. auto res = cli.Get("/test");
  10851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10852. ASSERT_EQ(StatusCode::OK_200, res->status);
  10853. }
  10854. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10855. class NoListenSSLServer : public SSLServer {
  10856. public:
  10857. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10858. const char *client_ca_cert_file_path,
  10859. const char *client_ca_cert_dir_path = nullptr)
  10860. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10861. client_ca_cert_dir_path),
  10862. stop_(false) {}
  10863. std::atomic_bool stop_;
  10864. private:
  10865. bool process_and_close_socket(socket_t /*sock*/) override {
  10866. // Don't create SSL context
  10867. while (!stop_.load()) {
  10868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10869. }
  10870. return true;
  10871. }
  10872. };
  10873. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10874. CLIENT_CA_CERT_FILE);
  10875. ASSERT_TRUE(svr.is_valid());
  10876. svr.Get("/test", [&](const Request &, Response &res) {
  10877. res.set_content("test", "text/plain");
  10878. });
  10879. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10880. auto se = detail::scope_exit([&] {
  10881. svr.stop_ = true;
  10882. svr.stop();
  10883. t.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. });
  10886. svr.wait_until_ready();
  10887. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10888. cli.enable_server_certificate_verification(false);
  10889. cli.set_connection_timeout(1);
  10890. auto res = cli.Get("/test");
  10891. ASSERT_TRUE(!res);
  10892. EXPECT_EQ(Error::SSLConnection, res.error());
  10893. // Timeout results in WantRead error code (maps to backend-specific value)
  10894. EXPECT_NE(0, res.ssl_error());
  10895. }
  10896. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10897. // Test SSLServer with client certificate verification using the standard
  10898. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10900. CLIENT_CA_CERT_DIR);
  10901. ASSERT_TRUE(svr.is_valid());
  10902. svr.Get("/test", [&](const Request &req, Response &res) {
  10903. res.set_content("test", "text/plain");
  10904. auto cert = req.peer_cert();
  10905. ASSERT_TRUE(static_cast<bool>(cert));
  10906. auto common_name = cert.subject_cn();
  10907. EXPECT_EQ("Common Name", common_name);
  10908. });
  10909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10910. auto se = detail::scope_exit([&] {
  10911. svr.stop();
  10912. t.join();
  10913. ASSERT_FALSE(svr.is_running());
  10914. });
  10915. svr.wait_until_ready();
  10916. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10917. cli.enable_server_certificate_verification(false);
  10918. cli.set_connection_timeout(30);
  10919. auto res = cli.Get("/test");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. ASSERT_EQ(StatusCode::OK_200, res->status);
  10922. }
  10923. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10924. // Verifies that wildcard matching and exact matching work consistently
  10925. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10926. using namespace httplib::tls;
  10927. // We need a running server to test against
  10928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10929. ASSERT_TRUE(svr.is_valid());
  10930. svr.Get("/test", [](const Request &, Response &res) {
  10931. res.set_content("ok", "text/plain");
  10932. });
  10933. thread t([&]() { svr.listen(HOST, PORT); });
  10934. auto se = detail::scope_exit([&] {
  10935. svr.stop();
  10936. t.join();
  10937. });
  10938. svr.wait_until_ready();
  10939. bool verify_callback_called = false;
  10940. bool verify_result_wrong = false;
  10941. SSLClient cli(HOST, PORT);
  10942. cli.enable_server_certificate_verification(true);
  10943. cli.set_ca_cert_path(CA_CERT_FILE);
  10944. cli.set_connection_timeout(5);
  10945. // Note: Test certificate has CN="Common Name", not "localhost"
  10946. bool verify_result_cn = false;
  10947. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10948. verify_callback_called = true;
  10949. if (!ctx.cert) return false;
  10950. // Test 1: "Common Name" should match (our test server cert CN)
  10951. verify_result_cn = ctx.check_hostname("Common Name");
  10952. // Test 2: wrong hostname should not match
  10953. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10954. return true; // Accept for the purpose of this test
  10955. });
  10956. auto res = cli.Get("/test");
  10957. // The request may succeed or fail depending on cert configuration
  10958. // but the callback should have been called
  10959. ASSERT_TRUE(verify_callback_called)
  10960. << "Verify callback should have been called";
  10961. // CN="Common Name" should match our test certificate
  10962. //
  10963. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10964. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10965. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10966. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10967. // <openssl/base.h>, which is included transitively when
  10968. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10969. #if defined(OPENSSL_IS_BORINGSSL)
  10970. EXPECT_FALSE(verify_result_cn)
  10971. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10972. #else
  10973. EXPECT_TRUE(verify_result_cn)
  10974. << "verify_hostname should match 'Common Name' (certificate CN)";
  10975. #endif
  10976. // Wrong hostname should not match
  10977. EXPECT_FALSE(verify_result_wrong)
  10978. << "verify_hostname should not match 'wronghost.example.com'";
  10979. }
  10980. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10981. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10982. // X509_check_ip behavior and must hold for every backend.
  10983. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10984. using namespace httplib::tls;
  10985. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10986. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10987. ASSERT_TRUE(svr.is_valid());
  10988. svr.Get("/test", [](const Request &, Response &res) {
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. thread t([&]() { svr.listen(HOST, PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. });
  10996. svr.wait_until_ready();
  10997. bool verify_callback_called = false;
  10998. bool ip_matched_via_cn = true;
  10999. SSLClient cli(HOST, PORT);
  11000. cli.enable_server_certificate_verification(true);
  11001. cli.set_ca_cert_path(CA_CERT_FILE);
  11002. cli.set_connection_timeout(5);
  11003. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11004. verify_callback_called = true;
  11005. if (!ctx.cert) return false;
  11006. // The IP appears only in the CN, so it must NOT be accepted.
  11007. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11008. return true; // Accept for the purpose of this test
  11009. });
  11010. cli.Get("/test");
  11011. ASSERT_TRUE(verify_callback_called)
  11012. << "Verify callback should have been called";
  11013. EXPECT_FALSE(ip_matched_via_cn)
  11014. << "An IP host must not be authenticated via the certificate CN";
  11015. }
  11016. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11017. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11018. using namespace httplib::tls;
  11019. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11020. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11021. ASSERT_TRUE(svr.is_valid());
  11022. svr.Get("/test", [](const Request &, Response &res) {
  11023. res.set_content("ok", "text/plain");
  11024. });
  11025. thread t([&]() { svr.listen(HOST, PORT); });
  11026. auto se = detail::scope_exit([&] {
  11027. svr.stop();
  11028. t.join();
  11029. });
  11030. svr.wait_until_ready();
  11031. bool verify_callback_called = false;
  11032. bool san_matched = false;
  11033. bool wrong_ipv6_matched = true;
  11034. bool cn_ipv6_matched = true;
  11035. SSLClient cli(HOST, PORT);
  11036. cli.enable_server_certificate_verification(true);
  11037. cli.set_ca_cert_path(CA_CERT_FILE);
  11038. cli.set_connection_timeout(5);
  11039. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11040. verify_callback_called = true;
  11041. if (!ctx.cert) return false;
  11042. // Matches the IPv6 iPAddress SAN.
  11043. san_matched = ctx.check_hostname("2001:db8::1");
  11044. // A different IPv6 address must not match.
  11045. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11046. // "::1" lives only in the CN, so it must not be accepted.
  11047. cn_ipv6_matched = ctx.check_hostname("::1");
  11048. return true; // Accept for the purpose of this test
  11049. });
  11050. cli.Get("/test");
  11051. ASSERT_TRUE(verify_callback_called)
  11052. << "Verify callback should have been called";
  11053. EXPECT_TRUE(san_matched)
  11054. << "verify_hostname should match an IPv6 iPAddress SAN";
  11055. EXPECT_FALSE(wrong_ipv6_matched)
  11056. << "verify_hostname should not match a non-matching IPv6 address";
  11057. EXPECT_FALSE(cn_ipv6_matched)
  11058. << "An IPv6 host must not be authenticated via the certificate CN";
  11059. }
  11060. #endif
  11061. // mbedTLS-specific callback constructor test
  11062. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11063. #ifdef CPPHTTPLIB_SSL_ENABLED
  11064. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11066. ASSERT_TRUE(svr.is_valid());
  11067. // Set up a handler to verify client certificate is present
  11068. bool client_cert_verified = false;
  11069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11070. // Verify that client certificate was provided
  11071. client_cert_verified = true;
  11072. res.set_content("success", "text/plain");
  11073. });
  11074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11075. auto se = detail::scope_exit([&] {
  11076. svr.stop();
  11077. t.join();
  11078. ASSERT_FALSE(svr.is_running());
  11079. });
  11080. svr.wait_until_ready();
  11081. // Client with certificate
  11082. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11083. cli.enable_server_certificate_verification(false);
  11084. cli.set_connection_timeout(30);
  11085. auto res = cli.Get("/test");
  11086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11087. ASSERT_EQ(StatusCode::OK_200, res->status);
  11088. ASSERT_TRUE(client_cert_verified);
  11089. EXPECT_EQ("success", res->body);
  11090. }
  11091. #endif
  11092. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11093. // backends
  11094. #ifdef CPPHTTPLIB_SSL_ENABLED
  11095. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11096. using namespace httplib::tls;
  11097. // Test that when client CA cert file is provided,
  11098. // the server properly requests and validates client certificates
  11099. // Create a server with client authentication
  11100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11101. ASSERT_TRUE(svr.is_valid());
  11102. bool handler_called = false;
  11103. svr.Get("/test", [&](const Request &req, Response &res) {
  11104. handler_called = true;
  11105. // Verify that a client certificate was provided
  11106. auto cert = req.peer_cert();
  11107. ASSERT_TRUE(static_cast<bool>(cert));
  11108. // Get the issuer name
  11109. std::string issuer_str = cert.issuer_name();
  11110. ASSERT_FALSE(issuer_str.empty());
  11111. // The client certificate should be issued by our test CA
  11112. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11113. res.set_content("authenticated", "text/plain");
  11114. });
  11115. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11116. auto se = detail::scope_exit([&] {
  11117. svr.stop();
  11118. t.join();
  11119. ASSERT_FALSE(svr.is_running());
  11120. });
  11121. svr.wait_until_ready();
  11122. // Connect with a client certificate issued by the CA
  11123. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11124. cli.enable_server_certificate_verification(false);
  11125. cli.set_connection_timeout(30);
  11126. auto res = cli.Get("/test");
  11127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11128. ASSERT_EQ(StatusCode::OK_200, res->status);
  11129. ASSERT_TRUE(handler_called);
  11130. EXPECT_EQ("authenticated", res->body);
  11131. }
  11132. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11133. using namespace httplib::tls;
  11134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11135. ASSERT_TRUE(svr.is_valid());
  11136. svr.Get("/test", [](const Request &, Response &res) {
  11137. res.set_content("ok", "text/plain");
  11138. });
  11139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11140. auto se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. t.join();
  11143. });
  11144. svr.wait_until_ready();
  11145. SSLClient cli(HOST, PORT);
  11146. cli.enable_server_certificate_verification(false);
  11147. cli.set_connection_timeout(30);
  11148. bool cert_checked = false;
  11149. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11150. if (ctx.cert) {
  11151. auto sans = ctx.sans();
  11152. // Test certificate may or may not have SANs - just verify the API
  11153. // works If SANs exist, verify the types are valid
  11154. for (const auto &san : sans) {
  11155. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11156. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11157. san.type == SanType::OTHER);
  11158. EXPECT_FALSE(san.value.empty());
  11159. }
  11160. cert_checked = true;
  11161. }
  11162. return true;
  11163. });
  11164. auto res = cli.Get("/test");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_TRUE(cert_checked);
  11167. }
  11168. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11169. using namespace httplib::tls;
  11170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11171. ASSERT_TRUE(svr.is_valid());
  11172. svr.Get("/test", [](const Request &, Response &res) {
  11173. res.set_content("ok", "text/plain");
  11174. });
  11175. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11176. auto se = detail::scope_exit([&] {
  11177. svr.stop();
  11178. t.join();
  11179. });
  11180. svr.wait_until_ready();
  11181. SSLClient cli(HOST, PORT);
  11182. cli.enable_server_certificate_verification(false);
  11183. cli.set_connection_timeout(30);
  11184. bool validity_checked = false;
  11185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11186. if (ctx.cert) {
  11187. time_t not_before = 0, not_after = 0;
  11188. bool result = ctx.validity(not_before, not_after);
  11189. EXPECT_TRUE(result);
  11190. // Verify that not_before < now < not_after for a valid cert
  11191. time_t now = time(nullptr);
  11192. EXPECT_LT(not_before, now);
  11193. EXPECT_GT(not_after, now);
  11194. validity_checked = true;
  11195. }
  11196. return true;
  11197. });
  11198. auto res = cli.Get("/test");
  11199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11200. EXPECT_TRUE(validity_checked);
  11201. }
  11202. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11203. using namespace httplib::tls;
  11204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11205. ASSERT_TRUE(svr.is_valid());
  11206. svr.Get("/test", [](const Request &, Response &res) {
  11207. res.set_content("ok", "text/plain");
  11208. });
  11209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11210. auto se = detail::scope_exit([&] {
  11211. svr.stop();
  11212. t.join();
  11213. });
  11214. svr.wait_until_ready();
  11215. SSLClient cli(HOST, PORT);
  11216. cli.enable_server_certificate_verification(false);
  11217. cli.set_connection_timeout(30);
  11218. bool serial_checked = false;
  11219. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11220. if (ctx.cert) {
  11221. std::string serial = ctx.serial();
  11222. EXPECT_FALSE(serial.empty());
  11223. // Serial should be a hex string
  11224. for (char c : serial) {
  11225. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11226. (c >= 'a' && c <= 'f'));
  11227. }
  11228. serial_checked = true;
  11229. }
  11230. return true;
  11231. });
  11232. auto res = cli.Get("/test");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. EXPECT_TRUE(serial_checked);
  11235. }
  11236. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11237. // Test 1: Valid CA file - no error should be recorded
  11238. {
  11239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11240. CLIENT_CA_CERT_FILE);
  11241. ASSERT_TRUE(svr.is_valid());
  11242. // With valid setup, last_ssl_error should be 0
  11243. EXPECT_EQ(0, svr.ssl_last_error());
  11244. }
  11245. // Test 2: Invalid CA file content
  11246. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11247. {
  11248. // Create a temporary file with completely invalid content
  11249. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11250. {
  11251. std::ofstream ofs(temp_invalid_ca);
  11252. ofs << "This is not a certificate file at all\n";
  11253. ofs << "Just plain text content\n";
  11254. }
  11255. // Create server with invalid CA file
  11256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11257. // Clean up temporary file
  11258. std::remove(temp_invalid_ca);
  11259. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11260. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11261. // Note: SSL_CTX_load_verify_locations typically fails first,
  11262. // but our error handling code path is still exercised
  11263. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11264. }
  11265. }
  11266. TEST(VerifyCallbackTest, VerifyContextFields) {
  11267. using namespace httplib::tls;
  11268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11269. ASSERT_TRUE(svr.is_valid());
  11270. svr.Get("/test", [](const Request &, Response &res) {
  11271. res.set_content("ok", "text/plain");
  11272. });
  11273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11274. auto se = detail::scope_exit([&] {
  11275. svr.stop();
  11276. t.join();
  11277. });
  11278. svr.wait_until_ready();
  11279. SSLClient cli(HOST, PORT);
  11280. cli.enable_server_certificate_verification(false);
  11281. cli.set_connection_timeout(30);
  11282. int callback_count = 0;
  11283. bool saw_leaf_cert = false;
  11284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11285. if (ctx.cert) {
  11286. callback_count++;
  11287. // We should see at least one certificate (the leaf)
  11288. std::string cn = ctx.subject_cn();
  11289. if (!cn.empty()) { saw_leaf_cert = true; }
  11290. // Verify context fields are populated
  11291. EXPECT_NE(ctx.session, nullptr);
  11292. EXPECT_GE(ctx.depth, 0);
  11293. }
  11294. return true;
  11295. });
  11296. auto res = cli.Get("/test");
  11297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11298. EXPECT_GT(callback_count, 0);
  11299. EXPECT_TRUE(saw_leaf_cert);
  11300. }
  11301. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11302. using httplib::tls::TlsError;
  11303. // Test that verify_error_to_string returns empty for success
  11304. std::string success_str = TlsError::verify_error_to_string(0);
  11305. EXPECT_TRUE(success_str.empty());
  11306. // Test that verify_error_to_string returns non-empty for error codes
  11307. // Using a common error code (certificate expired)
  11308. std::string error_str =
  11309. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11310. EXPECT_FALSE(error_str.empty());
  11311. }
  11312. TEST(SessionVerifierTest, CertificateAccepted) {
  11313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11314. ASSERT_TRUE(svr.is_valid());
  11315. svr.Get("/test", [](const Request &, Response &res) {
  11316. res.set_content("ok", "text/plain");
  11317. });
  11318. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11319. auto se = detail::scope_exit([&] {
  11320. svr.stop();
  11321. t.join();
  11322. });
  11323. svr.wait_until_ready();
  11324. SSLClient cli(HOST, PORT);
  11325. cli.enable_server_certificate_verification(false);
  11326. cli.set_connection_timeout(30);
  11327. bool callback_called = false;
  11328. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11329. EXPECT_NE(session, nullptr);
  11330. callback_called = true;
  11331. return SSLVerifierResponse::CertificateAccepted;
  11332. });
  11333. auto res = cli.Get("/test");
  11334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11335. EXPECT_EQ(200, res->status);
  11336. EXPECT_TRUE(callback_called);
  11337. }
  11338. TEST(SessionVerifierTest, CertificateRejected) {
  11339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11340. ASSERT_TRUE(svr.is_valid());
  11341. svr.Get("/test", [](const Request &, Response &res) {
  11342. res.set_content("ok", "text/plain");
  11343. });
  11344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. });
  11349. svr.wait_until_ready();
  11350. SSLClient cli(HOST, PORT);
  11351. cli.enable_server_certificate_verification(false);
  11352. cli.set_connection_timeout(30);
  11353. bool callback_called = false;
  11354. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11355. EXPECT_NE(session, nullptr);
  11356. callback_called = true;
  11357. return SSLVerifierResponse::CertificateRejected;
  11358. });
  11359. auto res = cli.Get("/test");
  11360. EXPECT_FALSE(res);
  11361. EXPECT_TRUE(callback_called);
  11362. }
  11363. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11365. ASSERT_TRUE(svr.is_valid());
  11366. svr.Get("/test", [](const Request &, Response &res) {
  11367. res.set_content("ok", "text/plain");
  11368. });
  11369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11370. auto se = detail::scope_exit([&] {
  11371. svr.stop();
  11372. t.join();
  11373. });
  11374. svr.wait_until_ready();
  11375. // NoDecisionMade with verification disabled should succeed (no default check)
  11376. SSLClient cli(HOST, PORT);
  11377. cli.enable_server_certificate_verification(false);
  11378. cli.set_connection_timeout(30);
  11379. bool callback_called = false;
  11380. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11381. EXPECT_NE(session, nullptr);
  11382. callback_called = true;
  11383. return SSLVerifierResponse::NoDecisionMade;
  11384. });
  11385. auto res = cli.Get("/test");
  11386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11387. EXPECT_EQ(200, res->status);
  11388. EXPECT_TRUE(callback_called);
  11389. }
  11390. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11392. ASSERT_TRUE(svr.is_valid());
  11393. svr.Get("/test", [](const Request &, Response &res) {
  11394. res.set_content("ok", "text/plain");
  11395. });
  11396. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11397. auto se = detail::scope_exit([&] {
  11398. svr.stop();
  11399. t.join();
  11400. });
  11401. svr.wait_until_ready();
  11402. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11403. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11404. // so we only check that the request fails, not whether the callback was
  11405. // called.
  11406. SSLClient cli(HOST, PORT);
  11407. cli.enable_server_certificate_verification(true);
  11408. cli.set_connection_timeout(30);
  11409. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11410. EXPECT_NE(session, nullptr);
  11411. return SSLVerifierResponse::NoDecisionMade;
  11412. });
  11413. auto res = cli.Get("/test");
  11414. EXPECT_FALSE(res);
  11415. }
  11416. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11417. // Test SSL server using PemMemory constructor with client CA certificates
  11418. // Read PEM files
  11419. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11420. read_file(SERVER_CERT_FILE, server_cert_pem);
  11421. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11422. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11423. // Create SSLServer with PemMemory constructor including client CA
  11424. SSLServer::PemMemory server_pem = {
  11425. server_cert_pem.c_str(),
  11426. server_cert_pem.size(),
  11427. server_key_pem.c_str(),
  11428. server_key_pem.size(),
  11429. client_ca_pem.c_str(),
  11430. client_ca_pem.size(),
  11431. nullptr // no password for server key
  11432. };
  11433. SSLServer svr(server_pem);
  11434. ASSERT_TRUE(svr.is_valid());
  11435. // No SSL error should be recorded for valid setup
  11436. EXPECT_EQ(0, svr.ssl_last_error());
  11437. // Set up server endpoints
  11438. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11439. res.set_content("ok", "text/plain");
  11440. });
  11441. // Start server in a thread
  11442. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11443. svr.wait_until_ready();
  11444. // Connect with client certificate (using constructor with paths)
  11445. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11446. cli.enable_server_certificate_verification(false);
  11447. auto res = cli.Get("/test-pem-ca");
  11448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11449. EXPECT_EQ(200, res->status);
  11450. EXPECT_EQ("ok", res->body);
  11451. svr.stop();
  11452. server_thread.join();
  11453. }
  11454. #endif
  11455. #ifdef _WIN32
  11456. TEST(CleanupTest, WSACleanup) {
  11457. int ret = WSACleanup();
  11458. ASSERT_EQ(0, ret);
  11459. }
  11460. #endif
  11461. #ifndef CPPHTTPLIB_SSL_ENABLED
  11462. TEST(NoSSLSupport, SimpleInterface) {
  11463. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11464. }
  11465. #endif
  11466. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11467. TEST(InvalidScheme, SimpleInterface) {
  11468. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11469. }
  11470. #endif
  11471. TEST(NoScheme, SimpleInterface) {
  11472. Client cli("yahoo.com:80");
  11473. ASSERT_TRUE(cli.is_valid());
  11474. }
  11475. TEST(SendAPI, SimpleInterface_Online) {
  11476. Client cli("http://yahoo.com");
  11477. Request req;
  11478. req.method = "GET";
  11479. req.path = "/";
  11480. auto res = cli.send(req);
  11481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11482. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11483. }
  11484. TEST(SendAPI, WithParamsInRequest) {
  11485. Server svr;
  11486. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11487. EXPECT_TRUE(req.has_param("test"));
  11488. EXPECT_EQ("test_value", req.get_param_value("test"));
  11489. });
  11490. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11491. auto se = detail::scope_exit([&] {
  11492. svr.stop();
  11493. t.join();
  11494. ASSERT_FALSE(svr.is_running());
  11495. });
  11496. svr.wait_until_ready();
  11497. Client cli(HOST, PORT);
  11498. {
  11499. Request req;
  11500. req.method = "GET";
  11501. req.path = "/";
  11502. req.params.emplace("test", "test_value");
  11503. auto res = cli.send(req);
  11504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11505. }
  11506. {
  11507. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11509. }
  11510. }
  11511. TEST(ClientImplMethods, GetSocketTest) {
  11512. httplib::Server svr;
  11513. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11514. res.status = StatusCode::OK_200;
  11515. });
  11516. auto port = svr.bind_to_any_port("127.0.0.1");
  11517. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11518. auto se = detail::scope_exit([&] {
  11519. svr.stop();
  11520. thread.join();
  11521. ASSERT_FALSE(svr.is_running());
  11522. });
  11523. svr.wait_until_ready();
  11524. {
  11525. httplib::Client cli("127.0.0.1", port);
  11526. cli.set_keep_alive(true);
  11527. // Use the behavior of cpp-httplib of opening the connection
  11528. // only when the first request happens. If that changes,
  11529. // this test would be obsolete.
  11530. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11531. // This also implicitly tests the server. But other tests would fail much
  11532. // earlier than this one to be considered.
  11533. auto res = cli.Get("/");
  11534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11535. EXPECT_EQ(StatusCode::OK_200, res->status);
  11536. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11537. }
  11538. }
  11539. #ifdef CPPHTTPLIB_SSL_ENABLED
  11540. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11541. Client cli("http://yahoo.com");
  11542. auto res = cli.Get("/");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11545. cli.set_follow_location(true);
  11546. res = cli.Get("/");
  11547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11548. EXPECT_EQ(StatusCode::OK_200, res->status);
  11549. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11550. }
  11551. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11552. Client cli("https://yahoo.com");
  11553. auto res = cli.Get("/");
  11554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11555. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11556. cli.set_follow_location(true);
  11557. res = cli.Get("/");
  11558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11559. EXPECT_EQ(StatusCode::OK_200, res->status);
  11560. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11561. }
  11562. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11563. Client cli("https://yahoo.com");
  11564. auto res = cli.Get("/");
  11565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11566. ASSERT_FALSE(!res);
  11567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11568. ASSERT_FALSE(res == nullptr);
  11569. ASSERT_TRUE(res != nullptr);
  11570. EXPECT_EQ(Error::Success, res.error());
  11571. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11572. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11573. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11574. cli.set_follow_location(true);
  11575. res = cli.Get("/");
  11576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11577. EXPECT_EQ(Error::Success, res.error());
  11578. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11579. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11580. EXPECT_EQ(StatusCode::OK_200, res->status);
  11581. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11582. }
  11583. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11584. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11585. Client cli("https://cdnjs.cloudflare.com");
  11586. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11587. Headers{{"Accept-Encoding", "br"}});
  11588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11589. EXPECT_EQ(StatusCode::OK_200, res->status);
  11590. EXPECT_EQ(287630U, res->body.size());
  11591. EXPECT_EQ("application/javascript; charset=utf-8",
  11592. res->get_header_value("Content-Type"));
  11593. }
  11594. #endif
  11595. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11596. #undef REDIR_HOST // Silence compiler warning
  11597. #define REDIR_HOST "https://httpbingo.org"
  11598. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11599. Client cli(REDIR_HOST);
  11600. cli.set_follow_location(true);
  11601. auto res =
  11602. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11604. EXPECT_EQ(StatusCode::OK_200, res->status);
  11605. }
  11606. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11607. Client cli(REDIR_HOST);
  11608. cli.set_follow_location(true);
  11609. Params params;
  11610. params.emplace("url", "http://example.com");
  11611. params.emplace("status_code", "302");
  11612. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11614. EXPECT_EQ(StatusCode::OK_200, res->status);
  11615. }
  11616. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11617. Client cli(REDIR_HOST);
  11618. cli.set_follow_location(true);
  11619. Params params;
  11620. params.emplace("url", "http://example.com");
  11621. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11623. EXPECT_EQ(StatusCode::OK_200, res->status);
  11624. }
  11625. TEST(HttpToHttpsRedirectTest, CertFile) {
  11626. auto ssl_port = PORT + 1;
  11627. Server svr;
  11628. ASSERT_TRUE(svr.is_valid());
  11629. svr.Get("/index", [&](const Request &, Response &res) {
  11630. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11631. "/index");
  11632. svr.stop();
  11633. });
  11634. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11635. ASSERT_TRUE(ssl_svr.is_valid());
  11636. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11637. res.set_content("test", "text/plain");
  11638. ssl_svr.stop();
  11639. });
  11640. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11641. thread t2 =
  11642. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11643. auto se = detail::scope_exit([&] {
  11644. t2.join();
  11645. t.join();
  11646. ASSERT_FALSE(svr.is_running());
  11647. });
  11648. svr.wait_until_ready();
  11649. ssl_svr.wait_until_ready();
  11650. Client cli("127.0.0.1", PORT);
  11651. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11652. cli.enable_server_certificate_verification(true);
  11653. cli.set_follow_location(true);
  11654. cli.set_connection_timeout(30);
  11655. auto res = cli.Get("/index");
  11656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11657. ASSERT_EQ(StatusCode::OK_200, res->status);
  11658. }
  11659. TEST(SSLClientRedirectTest, CertFile) {
  11660. auto ssl_port = PORT + 1;
  11661. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11662. ASSERT_TRUE(ssl_svr1.is_valid());
  11663. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11664. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11665. "/index");
  11666. ssl_svr1.stop();
  11667. });
  11668. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11669. ASSERT_TRUE(ssl_svr2.is_valid());
  11670. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11671. res.set_content("test", "text/plain");
  11672. ssl_svr2.stop();
  11673. });
  11674. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11675. thread t2 =
  11676. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11677. auto se = detail::scope_exit([&] {
  11678. t2.join();
  11679. t.join();
  11680. ASSERT_FALSE(ssl_svr1.is_running());
  11681. });
  11682. ssl_svr1.wait_until_ready();
  11683. ssl_svr2.wait_until_ready();
  11684. SSLClient cli("127.0.0.1", PORT);
  11685. std::string cert;
  11686. read_file(SERVER_CERT2_FILE, cert);
  11687. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11688. cli.enable_server_certificate_verification(true);
  11689. cli.set_follow_location(true);
  11690. cli.set_connection_timeout(30);
  11691. auto res = cli.Get("/index");
  11692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11693. ASSERT_EQ(StatusCode::OK_200, res->status);
  11694. }
  11695. #endif
  11696. #ifdef CPPHTTPLIB_SSL_ENABLED
  11697. // Test that set_ca_cert_store() skips system certs (consistent with
  11698. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11699. // should be trusted - system certs should NOT be loaded.
  11700. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11701. // Load a specific cert that is NOT a system CA cert
  11702. std::string cert;
  11703. read_file(SERVER_CERT2_FILE, cert);
  11704. SSLClient cli("google.com");
  11705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11706. cli.enable_server_certificate_verification(true);
  11707. // This should FAIL because:
  11708. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11709. // 2. System certs should NOT be loaded when custom store is set
  11710. // If system certs WERE loaded, this would succeed
  11711. auto res = cli.Get("/");
  11712. ASSERT_FALSE(res);
  11713. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11714. }
  11715. // Same as above, but through the native store handle path. Regression test:
  11716. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11717. // merged system certs into the user-provided store.
  11718. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11719. std::string cert;
  11720. read_file(SERVER_CERT2_FILE, cert);
  11721. SSLClient cli("google.com");
  11722. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11723. cli.enable_server_certificate_verification(true);
  11724. auto res = cli.Get("/");
  11725. ASSERT_FALSE(res);
  11726. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11727. }
  11728. // A custom store set via the native handle must still verify a server whose
  11729. // cert it does contain.
  11730. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11731. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11732. ASSERT_TRUE(svr.is_valid());
  11733. svr.Get("/test", [&](const Request &, Response &res) {
  11734. res.set_content("test", "text/plain");
  11735. });
  11736. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11737. auto se = detail::scope_exit([&] {
  11738. svr.stop();
  11739. t.join();
  11740. ASSERT_FALSE(svr.is_running());
  11741. });
  11742. svr.wait_until_ready();
  11743. SSLClient cli("127.0.0.1", PORT);
  11744. std::string cert;
  11745. read_file(SERVER_CERT2_FILE, cert);
  11746. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11747. cli.enable_server_certificate_verification(true);
  11748. cli.set_connection_timeout(30);
  11749. auto res = cli.Get("/test");
  11750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11751. ASSERT_EQ(StatusCode::OK_200, res->status);
  11752. }
  11753. // CA certs loaded through the universal Client must be transferred to the
  11754. // client created internally for following an HTTPS redirect. Regression test:
  11755. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11756. // the CA data for redirect transfer.
  11757. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11758. auto ssl_port = PORT + 1;
  11759. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11760. ASSERT_TRUE(ssl_svr1.is_valid());
  11761. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11762. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11763. "/index");
  11764. });
  11765. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11766. ASSERT_TRUE(ssl_svr2.is_valid());
  11767. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11768. res.set_content("test", "text/plain");
  11769. });
  11770. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11771. thread t2 =
  11772. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11773. auto se = detail::scope_exit([&] {
  11774. ssl_svr2.stop();
  11775. ssl_svr1.stop();
  11776. t2.join();
  11777. t.join();
  11778. ASSERT_FALSE(ssl_svr1.is_running());
  11779. });
  11780. ssl_svr1.wait_until_ready();
  11781. ssl_svr2.wait_until_ready();
  11782. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11783. std::string cert;
  11784. read_file(SERVER_CERT2_FILE, cert);
  11785. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11786. cli.enable_server_certificate_verification(true);
  11787. cli.set_follow_location(true);
  11788. cli.set_connection_timeout(30);
  11789. auto res = cli.Get("/index");
  11790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11791. ASSERT_EQ(StatusCode::OK_200, res->status);
  11792. }
  11793. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11794. // so a host signed by a system CA verifies even though a custom CA is set
  11795. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11796. std::string cert;
  11797. read_file(SERVER_CERT2_FILE, cert);
  11798. SSLClient cli("google.com");
  11799. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11800. cli.enable_system_ca(true);
  11801. cli.enable_server_certificate_verification(true);
  11802. auto res = cli.Get("/");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11805. }
  11806. // The custom CA remains effective when combined with the system CA
  11807. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11808. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11809. ASSERT_TRUE(svr.is_valid());
  11810. svr.Get("/test", [&](const Request &, Response &res) {
  11811. res.set_content("test", "text/plain");
  11812. });
  11813. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11814. auto se = detail::scope_exit([&] {
  11815. svr.stop();
  11816. t.join();
  11817. ASSERT_FALSE(svr.is_running());
  11818. });
  11819. svr.wait_until_ready();
  11820. SSLClient cli("127.0.0.1", PORT);
  11821. std::string cert;
  11822. read_file(SERVER_CERT2_FILE, cert);
  11823. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11824. cli.enable_system_ca(true);
  11825. cli.enable_server_certificate_verification(true);
  11826. cli.set_connection_timeout(30);
  11827. auto res = cli.Get("/test");
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. ASSERT_EQ(StatusCode::OK_200, res->status);
  11830. }
  11831. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11832. // skip chain verification entirely (only the certificate identity was
  11833. // checked), so a server presenting an untrusted certificate with a matching
  11834. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11835. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11836. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11837. ASSERT_TRUE(svr.is_valid());
  11838. svr.Get("/test", [&](const Request &, Response &res) {
  11839. res.set_content("test", "text/plain");
  11840. });
  11841. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. t.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. SSLClient cli("127.0.0.1", PORT);
  11849. std::string cert;
  11850. // A trusted CA that did not sign the server certificate. The server cert
  11851. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11852. // this connection.
  11853. read_file(CLIENT_CA_CERT_FILE, cert);
  11854. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11855. cli.enable_server_certificate_verification(true);
  11856. cli.set_connection_timeout(30);
  11857. auto res = cli.Get("/test");
  11858. ASSERT_FALSE(res);
  11859. }
  11860. // enable_system_ca(false) prevents system CA loading entirely
  11861. TEST(SSLClientTest, DisableSystemCa_Online) {
  11862. SSLClient cli("google.com");
  11863. cli.enable_system_ca(false);
  11864. cli.enable_server_certificate_verification(true);
  11865. auto res = cli.Get("/");
  11866. ASSERT_FALSE(res);
  11867. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11868. // itself when the CA chain is empty
  11869. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11870. res.error() == Error::SSLConnection);
  11871. }
  11872. // The universal Client forwards enable_system_ca()
  11873. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11874. std::string cert;
  11875. read_file(SERVER_CERT2_FILE, cert);
  11876. Client cli("https://google.com");
  11877. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11878. cli.enable_system_ca(true);
  11879. cli.enable_server_certificate_verification(true);
  11880. auto res = cli.Get("/");
  11881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11883. }
  11884. // The system CA policy must carry over to the client created internally for
  11885. // following a cross-host HTTPS redirect
  11886. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11887. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11888. ASSERT_TRUE(svr.is_valid());
  11889. svr.Get("/index", [&](const Request &, Response &res) {
  11890. res.set_redirect("https://www.google.com/");
  11891. });
  11892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11893. auto se = detail::scope_exit([&] {
  11894. svr.stop();
  11895. t.join();
  11896. ASSERT_FALSE(svr.is_running());
  11897. });
  11898. svr.wait_until_ready();
  11899. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11900. std::string cert;
  11901. read_file(SERVER_CERT2_FILE, cert);
  11902. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11903. cli.enable_system_ca(true);
  11904. cli.enable_server_certificate_verification(true);
  11905. cli.set_follow_location(true);
  11906. cli.set_connection_timeout(30);
  11907. // Receiving any response proves the redirect client completed the TLS
  11908. // handshake with a system-CA-signed host
  11909. auto res = cli.Get("/index");
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. }
  11912. TEST(MultipartFormDataTest, LargeData) {
  11913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11914. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11915. const ContentReader &content_reader) {
  11916. if (req.is_multipart_form_data()) {
  11917. std::vector<FormData> items;
  11918. content_reader(
  11919. [&](const FormData &file) {
  11920. items.push_back(file);
  11921. return true;
  11922. },
  11923. [&](const char *data, size_t data_length) {
  11924. items.back().content.append(data, data_length);
  11925. return true;
  11926. });
  11927. EXPECT_TRUE(std::string(items[0].name) == "document");
  11928. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11929. EXPECT_TRUE(items[0].filename == "2MB_data");
  11930. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11931. EXPECT_TRUE(items[1].name == "hello");
  11932. EXPECT_TRUE(items[1].content == "world");
  11933. EXPECT_TRUE(items[1].filename == "");
  11934. EXPECT_TRUE(items[1].content_type == "");
  11935. } else {
  11936. std::string body;
  11937. content_reader([&](const char *data, size_t data_length) {
  11938. body.append(data, data_length);
  11939. return true;
  11940. });
  11941. }
  11942. });
  11943. auto port = svr.bind_to_any_port(HOST);
  11944. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11945. auto se = detail::scope_exit([&] {
  11946. svr.stop();
  11947. t.join();
  11948. ASSERT_FALSE(svr.is_running());
  11949. });
  11950. svr.wait_until_ready();
  11951. {
  11952. std::string data(1024 * 1024 * 2, '.');
  11953. std::stringstream buffer;
  11954. buffer << data;
  11955. SSLClient cli(HOST, port);
  11956. cli.enable_server_certificate_verification(false);
  11957. UploadFormDataItems items{
  11958. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11959. {"hello", "world", "", ""},
  11960. };
  11961. auto res = cli.Post("/post", items);
  11962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11963. ASSERT_EQ(StatusCode::OK_200, res->status);
  11964. }
  11965. }
  11966. TEST(MultipartFormDataTest, DataProviderItems) {
  11967. std::random_device seed_gen;
  11968. std::mt19937 random(seed_gen());
  11969. std::string rand1;
  11970. rand1.resize(1000);
  11971. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11972. std::string rand2;
  11973. rand2.resize(3000);
  11974. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11976. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11977. const ContentReader &content_reader) {
  11978. ASSERT_FALSE(req.is_multipart_form_data());
  11979. std::string body;
  11980. content_reader([&](const char *data, size_t data_length) {
  11981. body.append(data, data_length);
  11982. return true;
  11983. });
  11984. EXPECT_EQ(body, "");
  11985. });
  11986. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11987. const ContentReader &content_reader) {
  11988. ASSERT_TRUE(req.is_multipart_form_data());
  11989. std::vector<FormData> items;
  11990. content_reader(
  11991. [&](const FormData &file) {
  11992. items.push_back(file);
  11993. return true;
  11994. },
  11995. [&](const char *data, size_t data_length) {
  11996. items.back().content.append(data, data_length);
  11997. return true;
  11998. });
  11999. ASSERT_TRUE(items.size() == 2);
  12000. EXPECT_EQ(std::string(items[0].name), "name1");
  12001. EXPECT_EQ(items[0].content, "Testing123");
  12002. EXPECT_EQ(items[0].filename, "filename1");
  12003. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12004. EXPECT_EQ(items[1].name, "name2");
  12005. EXPECT_EQ(items[1].content, "Testing456");
  12006. EXPECT_EQ(items[1].filename, "");
  12007. EXPECT_EQ(items[1].content_type, "");
  12008. });
  12009. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12010. const ContentReader &content_reader) {
  12011. ASSERT_TRUE(req.is_multipart_form_data());
  12012. std::vector<FormData> items;
  12013. content_reader(
  12014. [&](const FormData &file) {
  12015. items.push_back(file);
  12016. return true;
  12017. },
  12018. [&](const char *data, size_t data_length) {
  12019. items.back().content.append(data, data_length);
  12020. return true;
  12021. });
  12022. ASSERT_TRUE(items.size() == 2);
  12023. EXPECT_EQ(items[0].name, "name3");
  12024. EXPECT_EQ(items[0].content, rand1);
  12025. EXPECT_EQ(items[0].filename, "filename3");
  12026. EXPECT_EQ(items[0].content_type, "");
  12027. EXPECT_EQ(items[1].name, "name4");
  12028. EXPECT_EQ(items[1].content, rand2);
  12029. EXPECT_EQ(items[1].filename, "filename4");
  12030. EXPECT_EQ(items[1].content_type, "");
  12031. });
  12032. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12033. const ContentReader &content_reader) {
  12034. ASSERT_TRUE(req.is_multipart_form_data());
  12035. std::vector<FormData> items;
  12036. content_reader(
  12037. [&](const FormData &file) {
  12038. items.push_back(file);
  12039. return true;
  12040. },
  12041. [&](const char *data, size_t data_length) {
  12042. items.back().content.append(data, data_length);
  12043. return true;
  12044. });
  12045. ASSERT_TRUE(items.size() == 4);
  12046. EXPECT_EQ(std::string(items[0].name), "name1");
  12047. EXPECT_EQ(items[0].content, "Testing123");
  12048. EXPECT_EQ(items[0].filename, "filename1");
  12049. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12050. EXPECT_EQ(items[1].name, "name2");
  12051. EXPECT_EQ(items[1].content, "Testing456");
  12052. EXPECT_EQ(items[1].filename, "");
  12053. EXPECT_EQ(items[1].content_type, "");
  12054. EXPECT_EQ(items[2].name, "name3");
  12055. EXPECT_EQ(items[2].content, rand1);
  12056. EXPECT_EQ(items[2].filename, "filename3");
  12057. EXPECT_EQ(items[2].content_type, "");
  12058. EXPECT_EQ(items[3].name, "name4");
  12059. EXPECT_EQ(items[3].content, rand2);
  12060. EXPECT_EQ(items[3].filename, "filename4");
  12061. EXPECT_EQ(items[3].content_type, "");
  12062. });
  12063. auto port = svr.bind_to_any_port("localhost");
  12064. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12065. auto se = detail::scope_exit([&] {
  12066. svr.stop();
  12067. t.join();
  12068. ASSERT_FALSE(svr.is_running());
  12069. });
  12070. svr.wait_until_ready();
  12071. {
  12072. SSLClient cli("localhost", port);
  12073. cli.enable_server_certificate_verification(false);
  12074. UploadFormDataItems items{
  12075. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12076. {"name2", "Testing456", "", ""}, // not a file
  12077. };
  12078. {
  12079. auto res = cli.Post("/post-none", {}, {}, {});
  12080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12081. ASSERT_EQ(StatusCode::OK_200, res->status);
  12082. }
  12083. FormDataProviderItems providers;
  12084. {
  12085. auto res =
  12086. cli.Post("/post-items", {}, items, providers); // empty providers
  12087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12088. ASSERT_EQ(StatusCode::OK_200, res->status);
  12089. }
  12090. providers.push_back({"name3",
  12091. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12092. // test the offset is given correctly at each step
  12093. if (!offset)
  12094. sink.os.write(rand1.data(), 30);
  12095. else if (offset == 30)
  12096. sink.os.write(rand1.data() + 30, 300);
  12097. else if (offset == 330)
  12098. sink.os.write(rand1.data() + 330, 670);
  12099. else if (offset == rand1.size())
  12100. sink.done();
  12101. return true;
  12102. },
  12103. "filename3",
  12104. {}});
  12105. providers.push_back({"name4",
  12106. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12107. // test the offset is given correctly at each step
  12108. if (!offset)
  12109. sink.os.write(rand2.data(), 2000);
  12110. else if (offset == 2000)
  12111. sink.os.write(rand2.data() + 2000, 1);
  12112. else if (offset == 2001)
  12113. sink.os.write(rand2.data() + 2001, 999);
  12114. else if (offset == rand2.size())
  12115. sink.done();
  12116. return true;
  12117. },
  12118. "filename4",
  12119. {}});
  12120. {
  12121. auto res = cli.Post("/post-providers", {}, {}, providers);
  12122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12123. ASSERT_EQ(StatusCode::OK_200, res->status);
  12124. }
  12125. {
  12126. auto res = cli.Post("/post-both", {}, items, providers);
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. ASSERT_EQ(StatusCode::OK_200, res->status);
  12129. }
  12130. }
  12131. }
  12132. TEST(MultipartFormDataTest, BadHeader) {
  12133. Server svr;
  12134. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12135. res.set_content("ok", "text/plain");
  12136. });
  12137. thread t = thread([&] { svr.listen(HOST, PORT); });
  12138. auto se = detail::scope_exit([&] {
  12139. svr.stop();
  12140. t.join();
  12141. ASSERT_FALSE(svr.is_running());
  12142. });
  12143. svr.wait_until_ready();
  12144. const std::string body =
  12145. "This is the preamble. It is to be ignored, though it\r\n"
  12146. "is a handy place for composition agents to include an\r\n"
  12147. "explanatory note to non-MIME conformant readers.\r\n"
  12148. "\r\n"
  12149. "\r\n"
  12150. "--simple boundary\r\n"
  12151. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12152. ": BAD...\r\n"
  12153. "\r\n"
  12154. "value1\r\n"
  12155. "--simple boundary\r\n"
  12156. "Content-Disposition: form-data; name=\"field2\"; "
  12157. "filename=\"example.txt\"\r\n"
  12158. "\r\n"
  12159. "value2\r\n"
  12160. "--simple boundary--\r\n"
  12161. "This is the epilogue. It is also to be ignored.\r\n";
  12162. std::string content_type =
  12163. R"(multipart/form-data; boundary="simple boundary")";
  12164. Client cli(HOST, PORT);
  12165. auto res = cli.Post("/post", body, content_type.c_str());
  12166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12168. }
  12169. TEST(MultipartFormDataTest, WithPreamble) {
  12170. Server svr;
  12171. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12172. res.set_content("ok", "text/plain");
  12173. });
  12174. thread t = thread([&] { svr.listen(HOST, PORT); });
  12175. auto se = detail::scope_exit([&] {
  12176. svr.stop();
  12177. t.join();
  12178. ASSERT_FALSE(svr.is_running());
  12179. });
  12180. svr.wait_until_ready();
  12181. const std::string body =
  12182. "This is the preamble. It is to be ignored, though it\r\n"
  12183. "is a handy place for composition agents to include an\r\n"
  12184. "explanatory note to non-MIME conformant readers.\r\n"
  12185. "\r\n"
  12186. "\r\n"
  12187. "--simple boundary\r\n"
  12188. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12189. "\r\n"
  12190. "value1\r\n"
  12191. "--simple boundary\r\n"
  12192. "Content-Disposition: form-data; name=\"field2\"; "
  12193. "filename=\"example.txt\"\r\n"
  12194. "\r\n"
  12195. "value2\r\n"
  12196. "--simple boundary--\r\n"
  12197. "This is the epilogue. It is also to be ignored.\r\n";
  12198. std::string content_type =
  12199. R"(multipart/form-data; boundary="simple boundary")";
  12200. Client cli(HOST, PORT);
  12201. auto res = cli.Post("/post", body, content_type.c_str());
  12202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12203. EXPECT_EQ(StatusCode::OK_200, res->status);
  12204. }
  12205. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12207. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12208. const ContentReader &content_reader) {
  12209. if (req.is_multipart_form_data()) {
  12210. std::vector<FormData> items;
  12211. content_reader(
  12212. [&](const FormData &file) {
  12213. items.push_back(file);
  12214. return true;
  12215. },
  12216. [&](const char *data, size_t data_length) {
  12217. items.back().content.append(data, data_length);
  12218. return true;
  12219. });
  12220. EXPECT_TRUE(std::string(items[0].name) == "document");
  12221. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12222. EXPECT_TRUE(items[0].filename == "2MB_data");
  12223. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12224. EXPECT_TRUE(items[1].name == "hello");
  12225. EXPECT_TRUE(items[1].content == "world");
  12226. EXPECT_TRUE(items[1].filename == "");
  12227. EXPECT_TRUE(items[1].content_type == "");
  12228. } else {
  12229. std::string body;
  12230. content_reader([&](const char *data, size_t data_length) {
  12231. body.append(data, data_length);
  12232. return true;
  12233. });
  12234. }
  12235. });
  12236. auto port = svr.bind_to_any_port("localhost");
  12237. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. {
  12245. std::string data(1024 * 1024 * 2, '.');
  12246. std::stringstream buffer;
  12247. buffer << data;
  12248. SSLClient cli("localhost", port);
  12249. cli.enable_server_certificate_verification(false);
  12250. UploadFormDataItems items{
  12251. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12252. {"hello", "world", "", ""},
  12253. };
  12254. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12256. ASSERT_EQ(StatusCode::OK_200, res->status);
  12257. }
  12258. }
  12259. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12260. std::string data(1024 * 1024 * 2, '&');
  12261. std::stringstream buffer;
  12262. buffer << data;
  12263. Client cli("https://localhost:8080");
  12264. UploadFormDataItems items{
  12265. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12266. {"hello", "world", "", ""},
  12267. };
  12268. for (const char &c : " \t\r\n") {
  12269. auto res =
  12270. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12271. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12272. ASSERT_FALSE(res);
  12273. }
  12274. }
  12275. TEST(MultipartFormDataTest, PutFormData) {
  12276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12277. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12278. const ContentReader &content_reader) {
  12279. if (req.is_multipart_form_data()) {
  12280. std::vector<FormData> items;
  12281. content_reader(
  12282. [&](const FormData &file) {
  12283. items.push_back(file);
  12284. return true;
  12285. },
  12286. [&](const char *data, size_t data_length) {
  12287. items.back().content.append(data, data_length);
  12288. return true;
  12289. });
  12290. EXPECT_TRUE(std::string(items[0].name) == "document");
  12291. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12292. EXPECT_TRUE(items[0].filename == "2MB_data");
  12293. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12294. EXPECT_TRUE(items[1].name == "hello");
  12295. EXPECT_TRUE(items[1].content == "world");
  12296. EXPECT_TRUE(items[1].filename == "");
  12297. EXPECT_TRUE(items[1].content_type == "");
  12298. } else {
  12299. std::string body;
  12300. content_reader([&](const char *data, size_t data_length) {
  12301. body.append(data, data_length);
  12302. return true;
  12303. });
  12304. }
  12305. });
  12306. auto port = svr.bind_to_any_port("localhost");
  12307. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12308. auto se = detail::scope_exit([&] {
  12309. svr.stop();
  12310. t.join();
  12311. ASSERT_FALSE(svr.is_running());
  12312. });
  12313. svr.wait_until_ready();
  12314. {
  12315. std::string data(1024 * 1024 * 2, '&');
  12316. std::stringstream buffer;
  12317. buffer << data;
  12318. SSLClient cli("localhost", port);
  12319. cli.enable_server_certificate_verification(false);
  12320. UploadFormDataItems items{
  12321. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12322. {"hello", "world", "", ""},
  12323. };
  12324. auto res = cli.Put("/put", items);
  12325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12326. ASSERT_EQ(StatusCode::OK_200, res->status);
  12327. }
  12328. }
  12329. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12331. svr.Put("/put_customboundary",
  12332. [&](const Request &req, const Response & /*res*/,
  12333. const ContentReader &content_reader) {
  12334. if (req.is_multipart_form_data()) {
  12335. std::vector<FormData> items;
  12336. content_reader(
  12337. [&](const FormData &file) {
  12338. items.push_back(file);
  12339. return true;
  12340. },
  12341. [&](const char *data, size_t data_length) {
  12342. items.back().content.append(data, data_length);
  12343. return true;
  12344. });
  12345. EXPECT_TRUE(std::string(items[0].name) == "document");
  12346. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12347. EXPECT_TRUE(items[0].filename == "2MB_data");
  12348. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12349. EXPECT_TRUE(items[1].name == "hello");
  12350. EXPECT_TRUE(items[1].content == "world");
  12351. EXPECT_TRUE(items[1].filename == "");
  12352. EXPECT_TRUE(items[1].content_type == "");
  12353. } else {
  12354. std::string body;
  12355. content_reader([&](const char *data, size_t data_length) {
  12356. body.append(data, data_length);
  12357. return true;
  12358. });
  12359. }
  12360. });
  12361. auto port = svr.bind_to_any_port("localhost");
  12362. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12363. auto se = detail::scope_exit([&] {
  12364. svr.stop();
  12365. t.join();
  12366. ASSERT_FALSE(svr.is_running());
  12367. });
  12368. svr.wait_until_ready();
  12369. {
  12370. std::string data(1024 * 1024 * 2, '&');
  12371. std::stringstream buffer;
  12372. buffer << data;
  12373. SSLClient cli("localhost", port);
  12374. cli.enable_server_certificate_verification(false);
  12375. UploadFormDataItems items{
  12376. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12377. {"hello", "world", "", ""},
  12378. };
  12379. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12381. ASSERT_EQ(StatusCode::OK_200, res->status);
  12382. }
  12383. }
  12384. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12385. std::string data(1024 * 1024 * 2, '&');
  12386. std::stringstream buffer;
  12387. buffer << data;
  12388. Client cli("https://localhost:8080");
  12389. cli.enable_server_certificate_verification(false);
  12390. UploadFormDataItems items{
  12391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12392. {"hello", "world", "", ""},
  12393. };
  12394. for (const char &c : " \t\r\n") {
  12395. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12396. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12397. ASSERT_FALSE(res);
  12398. }
  12399. }
  12400. TEST(MultipartFormDataTest, AlternateFilename) {
  12401. auto handled = false;
  12402. Server svr;
  12403. svr.Post("/test", [&](const Request &req, Response &res) {
  12404. ASSERT_EQ(2u, req.form.files.size());
  12405. ASSERT_EQ(1u, req.form.fields.size());
  12406. // Test files
  12407. const auto &file1 = req.form.get_file("file1");
  12408. ASSERT_EQ("file1", file1.name);
  12409. ASSERT_EQ("A.txt", file1.filename);
  12410. ASSERT_EQ("text/plain", file1.content_type);
  12411. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12412. const auto &file2 = req.form.get_file("file2");
  12413. ASSERT_EQ("file2", file2.name);
  12414. ASSERT_EQ("a.html", file2.filename);
  12415. ASSERT_EQ("text/html", file2.content_type);
  12416. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12417. file2.content);
  12418. // Test text field
  12419. const auto &text = req.form.get_field("text");
  12420. ASSERT_EQ("text default", text);
  12421. res.set_content("ok", "text/plain");
  12422. handled = true;
  12423. });
  12424. thread t = thread([&] { svr.listen(HOST, PORT); });
  12425. auto se = detail::scope_exit([&] {
  12426. svr.stop();
  12427. t.join();
  12428. ASSERT_FALSE(svr.is_running());
  12429. ASSERT_TRUE(handled);
  12430. });
  12431. svr.wait_until_ready();
  12432. auto req = "POST /test HTTP/1.1\r\n"
  12433. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12434. "Content-Length: 399\r\n"
  12435. "\r\n"
  12436. "----------\r\n"
  12437. "Content-Disposition: form-data; name=\"text\"\r\n"
  12438. "\r\n"
  12439. "text default\r\n"
  12440. "----------\r\n"
  12441. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12442. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12443. "Content-Type: text/plain\r\n"
  12444. "\r\n"
  12445. "Content of a.txt.\r\n"
  12446. "\r\n"
  12447. "----------\r\n"
  12448. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12449. "\"a.html\"\r\n"
  12450. "Content-Type: text/html\r\n"
  12451. "\r\n"
  12452. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12453. "\r\n"
  12454. "------------\r\n";
  12455. ASSERT_TRUE(send_request(1, req));
  12456. }
  12457. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12458. auto handled = false;
  12459. Server svr;
  12460. svr.Post("/test", [&](const Request &req, Response &res) {
  12461. // Case-insensitive "utf-8''" prefix with a long value
  12462. const auto &file = req.form.get_file("file1");
  12463. ASSERT_EQ("file1", file.name);
  12464. // 8000 chars exercises both the Content-Disposition parser and the
  12465. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12466. // Prior to the fix, std::regex_match on this header would cause O(N)
  12467. // stack recursion in libstdc++, leading to SIGSEGV.
  12468. std::string expected_filename(8000, 'A');
  12469. ASSERT_EQ(expected_filename, file.filename);
  12470. res.set_content("ok", "text/plain");
  12471. handled = true;
  12472. });
  12473. thread t = thread([&] { svr.listen(HOST, PORT); });
  12474. auto se = detail::scope_exit([&] {
  12475. svr.stop();
  12476. t.join();
  12477. ASSERT_FALSE(svr.is_running());
  12478. ASSERT_TRUE(handled);
  12479. });
  12480. svr.wait_until_ready();
  12481. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12482. // Regression test for GHSA-qq6v-r583-3h69
  12483. std::string long_filename(8000, 'A');
  12484. std::string body = "----------\r\n"
  12485. "Content-Disposition: form-data; name=\"file1\"; "
  12486. "filename*=\"Utf-8''" +
  12487. long_filename +
  12488. "\"\r\n"
  12489. "\r\n"
  12490. "hello\r\n"
  12491. "------------\r\n";
  12492. auto req = "POST /test HTTP/1.1\r\n"
  12493. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12494. "Content-Length: " +
  12495. std::to_string(body.size()) + "\r\n\r\n" + body;
  12496. ASSERT_TRUE(send_request(1, req));
  12497. }
  12498. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12499. auto handled = false;
  12500. Server svr;
  12501. svr.Post("/test", [&](const Request &req, Response &) {
  12502. ASSERT_EQ(2u, req.form.fields.size());
  12503. const auto &text1 = req.form.get_field("text1");
  12504. ASSERT_EQ("text1", text1);
  12505. const auto &text2 = req.form.get_field("text2");
  12506. ASSERT_EQ("text2", text2);
  12507. handled = true;
  12508. });
  12509. thread t = thread([&] { svr.listen(HOST, PORT); });
  12510. auto se = detail::scope_exit([&] {
  12511. svr.stop();
  12512. t.join();
  12513. ASSERT_FALSE(svr.is_running());
  12514. ASSERT_TRUE(handled);
  12515. });
  12516. svr.wait_until_ready();
  12517. auto req = "POST /test HTTP/1.1\r\n"
  12518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12519. "Content-Length: 146\r\n"
  12520. "\r\n----------\r\n"
  12521. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12522. "\r\n"
  12523. "text1"
  12524. "\r\n----------\r\n"
  12525. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12526. "\r\n"
  12527. "text2"
  12528. "\r\n------------";
  12529. std::string response;
  12530. ASSERT_TRUE(send_request(1, req, &response));
  12531. ASSERT_EQ("200", response.substr(9, 3));
  12532. }
  12533. TEST(MultipartFormDataTest, ContentLength) {
  12534. auto handled = false;
  12535. Server svr;
  12536. svr.Post("/test", [&](const Request &req, Response &) {
  12537. ASSERT_EQ(2u, req.form.fields.size());
  12538. const auto &text1 = req.form.get_field("text1");
  12539. ASSERT_EQ("text1", text1);
  12540. const auto &text2 = req.form.get_field("text2");
  12541. ASSERT_EQ("text2", text2);
  12542. handled = true;
  12543. });
  12544. thread t = thread([&] { svr.listen(HOST, PORT); });
  12545. auto se = detail::scope_exit([&] {
  12546. svr.stop();
  12547. t.join();
  12548. ASSERT_FALSE(svr.is_running());
  12549. ASSERT_TRUE(handled);
  12550. });
  12551. svr.wait_until_ready();
  12552. auto req = "POST /test HTTP/1.1\r\n"
  12553. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12554. "Content-Length: 167\r\n"
  12555. "\r\n----------\r\n"
  12556. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12557. "Content-Length: 5\r\n"
  12558. "\r\n"
  12559. "text1"
  12560. "\r\n----------\r\n"
  12561. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12562. "\r\n"
  12563. "text2"
  12564. "\r\n------------\r\n";
  12565. std::string response;
  12566. ASSERT_TRUE(send_request(1, req, &response));
  12567. ASSERT_EQ("200", response.substr(9, 3));
  12568. }
  12569. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12570. auto handled = false;
  12571. Server svr;
  12572. svr.Post("/test", [&](const Request &req, Response &) {
  12573. ASSERT_EQ(2u, req.form.fields.size());
  12574. const auto &text1 = req.form.get_field("text1");
  12575. ASSERT_EQ("text1", text1);
  12576. // TODO: Add header access for text fields if needed
  12577. const auto &text2 = req.form.get_field("text2");
  12578. ASSERT_EQ("text2", text2);
  12579. // TODO: Header access for text fields needs to be implemented
  12580. // auto &headers = it->second.headers;
  12581. // ASSERT_EQ(3U, headers.size());
  12582. // auto custom_header = headers.find("x-whatever");
  12583. // ASSERT_TRUE(custom_header != headers.end());
  12584. // ASSERT_NE("customvalue", custom_header->second);
  12585. // ASSERT_EQ("CustomValue", custom_header->second);
  12586. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12587. handled = true;
  12588. });
  12589. thread t = thread([&] { svr.listen(HOST, PORT); });
  12590. auto se = detail::scope_exit([&] {
  12591. svr.stop();
  12592. t.join();
  12593. ASSERT_FALSE(svr.is_running());
  12594. ASSERT_TRUE(handled);
  12595. });
  12596. svr.wait_until_ready();
  12597. auto req = "POST /test HTTP/1.1\r\n"
  12598. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12599. "Content-Length: 232\r\n"
  12600. "\r\n----------\r\n"
  12601. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12602. "Content-Length: 5\r\n"
  12603. "X-Test: 1\r\n"
  12604. "\r\n"
  12605. "text1"
  12606. "\r\n----------\r\n"
  12607. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12608. "Content-Type: text/plain\r\n"
  12609. "X-Whatever: CustomValue\r\n"
  12610. "\r\n"
  12611. "text2"
  12612. "\r\n------------\r\n"
  12613. "That should be disregarded. Not even read";
  12614. std::string response;
  12615. ASSERT_TRUE(send_request(1, req, &response));
  12616. ASSERT_EQ("200", response.substr(9, 3));
  12617. }
  12618. TEST(MultipartFormDataTest, LargeHeader) {
  12619. auto handled = false;
  12620. Server svr;
  12621. svr.Post("/test", [&](const Request &req, Response &) {
  12622. ASSERT_EQ(1u, req.form.fields.size());
  12623. const auto &text = req.form.get_field("name1");
  12624. ASSERT_EQ("text1", text);
  12625. handled = true;
  12626. });
  12627. thread t = thread([&] { svr.listen(HOST, PORT); });
  12628. auto se = detail::scope_exit([&] {
  12629. svr.stop();
  12630. t.join();
  12631. ASSERT_FALSE(svr.is_running());
  12632. ASSERT_TRUE(handled);
  12633. });
  12634. svr.wait_until_ready();
  12635. auto boundary = std::string("cpp-httplib-multipart-data");
  12636. std::string content = "--" + boundary +
  12637. "\r\n"
  12638. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12639. "\r\n"
  12640. "text1\r\n"
  12641. "--" +
  12642. boundary + "--\r\n";
  12643. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12644. "Content-Type: multipart/form-data;boundary=" +
  12645. boundary +
  12646. "\r\n"
  12647. "Content-Length: " +
  12648. std::to_string(content.size()) +
  12649. "\r\n"
  12650. "Dummy-Header: ";
  12651. std::string header_suffix = "\r\n"
  12652. "\r\n";
  12653. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12654. size_t header_dummy_size =
  12655. read_buff_size -
  12656. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12657. auto header_dummy = std::string(header_dummy_size, '@');
  12658. auto req = header_prefix + header_dummy + header_suffix + content;
  12659. std::string response;
  12660. ASSERT_TRUE(send_request(1, req, &response));
  12661. ASSERT_EQ("200", response.substr(9, 3));
  12662. }
  12663. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12664. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12665. // (not chunked Transfer-Encoding) after the streaming refactor.
  12666. auto handled = false;
  12667. Server svr;
  12668. svr.Post("/upload", [&](const Request &req, Response &res) {
  12669. auto cl_it = req.headers.find("Content-Length");
  12670. EXPECT_TRUE(cl_it != req.headers.end());
  12671. auto te_it = req.headers.find("Transfer-Encoding");
  12672. EXPECT_TRUE(te_it == req.headers.end());
  12673. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12674. res.set_content("ok", "text/plain");
  12675. handled = true;
  12676. });
  12677. auto port = svr.bind_to_any_port(HOST);
  12678. auto t = thread([&] { svr.listen_after_bind(); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. t.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. ASSERT_TRUE(handled);
  12684. });
  12685. svr.wait_until_ready();
  12686. UploadFormDataItems items = {
  12687. {"field1", "hello", "", "text/plain"},
  12688. {"file1", "world", "test.txt", "application/octet-stream"},
  12689. };
  12690. Client cli(HOST, port);
  12691. auto res = cli.Post("/upload", {}, items);
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. EXPECT_EQ(StatusCode::OK_200, res->status);
  12694. }
  12695. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12696. // Verify that make_multipart_content_provider coalesces many small segments
  12697. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12698. constexpr size_t kItemCount = 1000;
  12699. UploadFormDataItems items;
  12700. items.reserve(kItemCount);
  12701. for (size_t i = 0; i < kItemCount; i++) {
  12702. items.push_back(
  12703. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12704. }
  12705. const std::string boundary = "----test-boundary";
  12706. auto content_length = detail::get_multipart_content_length(items, boundary);
  12707. auto provider = detail::make_multipart_content_provider(items, boundary);
  12708. // Drive the provider the same way write_content_with_progress does
  12709. size_t write_count = 0;
  12710. size_t total_bytes = 0;
  12711. DataSink sink;
  12712. size_t offset = 0;
  12713. sink.write = [&](const char *d, size_t l) -> bool {
  12714. (void)d;
  12715. write_count++;
  12716. total_bytes += l;
  12717. offset += l;
  12718. return true;
  12719. };
  12720. sink.is_writable = []() -> bool { return true; };
  12721. while (offset < content_length) {
  12722. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12723. }
  12724. EXPECT_EQ(content_length, total_bytes);
  12725. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12726. // With buffering into 64KB blocks, write_count should be much smaller.
  12727. auto segment_count = 3 * kItemCount + 1;
  12728. EXPECT_LT(write_count, segment_count / 10);
  12729. }
  12730. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12731. // Integration test: send many UploadFormDataItems and verify the server
  12732. // receives all of them correctly (#2410).
  12733. constexpr size_t kItemCount = 500;
  12734. auto handled = false;
  12735. Server svr;
  12736. svr.Post("/upload", [&](const Request &req, Response &res) {
  12737. EXPECT_EQ(kItemCount, req.form.fields.size());
  12738. for (size_t i = 0; i < kItemCount; i++) {
  12739. auto key = "field" + std::to_string(i);
  12740. auto val = "value" + std::to_string(i);
  12741. auto it = req.form.fields.find(key);
  12742. if (it != req.form.fields.end()) {
  12743. EXPECT_EQ(val, it->second.content);
  12744. } else {
  12745. ADD_FAILURE() << "Missing field: " << key;
  12746. }
  12747. }
  12748. res.set_content("ok", "text/plain");
  12749. handled = true;
  12750. });
  12751. auto port = svr.bind_to_any_port(HOST);
  12752. auto t = thread([&] { svr.listen_after_bind(); });
  12753. auto se = detail::scope_exit([&] {
  12754. svr.stop();
  12755. t.join();
  12756. ASSERT_FALSE(svr.is_running());
  12757. ASSERT_TRUE(handled);
  12758. });
  12759. svr.wait_until_ready();
  12760. UploadFormDataItems items;
  12761. items.reserve(kItemCount);
  12762. for (size_t i = 0; i < kItemCount; i++) {
  12763. items.push_back(
  12764. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12765. }
  12766. Client cli(HOST, port);
  12767. auto res = cli.Post("/upload", items);
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12769. EXPECT_EQ(StatusCode::OK_200, res->status);
  12770. }
  12771. TEST(MultipartFormDataTest, MakeFileProvider) {
  12772. // Verify make_file_provider sends a file's contents correctly.
  12773. const std::string file_content(4096, 'Z');
  12774. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12775. {
  12776. std::ofstream ofs(tmp_path, std::ios::binary);
  12777. ofs.write(file_content.data(),
  12778. static_cast<std::streamsize>(file_content.size()));
  12779. }
  12780. auto handled = false;
  12781. Server svr;
  12782. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12783. const ContentReader &content_reader) {
  12784. ASSERT_TRUE(req.is_multipart_form_data());
  12785. std::vector<FormData> items;
  12786. content_reader(
  12787. [&](const FormData &file) {
  12788. items.push_back(file);
  12789. return true;
  12790. },
  12791. [&](const char *data, size_t data_length) {
  12792. items.back().content.append(data, data_length);
  12793. return true;
  12794. });
  12795. ASSERT_EQ(1u, items.size());
  12796. EXPECT_EQ("myfile", items[0].name);
  12797. EXPECT_EQ("data.bin", items[0].filename);
  12798. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12799. EXPECT_EQ(file_content, items[0].content);
  12800. handled = true;
  12801. });
  12802. auto port = svr.bind_to_any_port(HOST);
  12803. auto t = thread([&] { svr.listen_after_bind(); });
  12804. auto se = detail::scope_exit([&] {
  12805. svr.stop();
  12806. t.join();
  12807. ASSERT_FALSE(svr.is_running());
  12808. ASSERT_TRUE(handled);
  12809. std::remove(tmp_path.c_str());
  12810. });
  12811. svr.wait_until_ready();
  12812. FormDataProviderItems providers;
  12813. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12814. "application/octet-stream"));
  12815. Client cli(HOST, port);
  12816. auto res = cli.Post("/upload", {}, {}, providers);
  12817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12818. EXPECT_EQ(StatusCode::OK_200, res->status);
  12819. }
  12820. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12821. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12822. // (100) headers is rejected with a 400 Bad Request response.
  12823. Server svr;
  12824. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12825. res.set_content("ok", "text/plain");
  12826. });
  12827. thread t = thread([&] { svr.listen(HOST, PORT); });
  12828. auto se = detail::scope_exit([&] {
  12829. svr.stop();
  12830. t.join();
  12831. ASSERT_FALSE(svr.is_running());
  12832. });
  12833. svr.wait_until_ready();
  12834. // Build a multipart part with 101 custom headers (exceeding
  12835. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12836. std::stringstream body;
  12837. body << "--simpleboundary\r\n"
  12838. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12839. for (int i = 0; i < 101; i++) {
  12840. body << "X-Custom-Header-" << i << ": value\r\n";
  12841. }
  12842. body << "\r\n"
  12843. << "value1\r\n"
  12844. << "--simpleboundary--\r\n";
  12845. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12846. Client cli(HOST, PORT);
  12847. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12849. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12850. }
  12851. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  12852. // A body that never contains the declared boundary must not be accumulated
  12853. // while the parser waits for it. Buffering it would also make every read
  12854. // rescan everything seen so far, which is quadratic in the body size.
  12855. Server svr;
  12856. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12857. res.set_content("ok", "text/plain");
  12858. });
  12859. auto port = svr.bind_to_any_port(HOST);
  12860. thread t = thread([&] { svr.listen_after_bind(); });
  12861. auto se = detail::scope_exit([&] {
  12862. svr.stop();
  12863. t.join();
  12864. ASSERT_FALSE(svr.is_running());
  12865. });
  12866. svr.wait_until_ready();
  12867. Client cli(HOST, port);
  12868. cli.set_read_timeout(60, 0);
  12869. cli.set_write_timeout(60, 0);
  12870. // '-' is the worst case: it matches the first character of the boundary, so
  12871. // every position has to be checked against it.
  12872. auto post_dashes = [&](size_t size) {
  12873. const std::string body(size, '-');
  12874. auto start = std::chrono::steady_clock::now();
  12875. auto res =
  12876. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  12877. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  12878. std::chrono::steady_clock::now() - start)
  12879. .count();
  12880. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  12881. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  12882. return ms;
  12883. };
  12884. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  12885. // Windows.
  12886. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  12887. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  12888. // Comparing the two sizes rather than checking an absolute duration keeps
  12889. // this meaningful across build types and CI load, both of which move the
  12890. // absolute numbers by more than an order of magnitude. Four times the bytes
  12891. // costs about four times the time when parsing is linear, and about sixteen
  12892. // times when the body is buffered and rescanned.
  12893. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  12894. EXPECT_LT(ms_16mb, ms_4mb * 10)
  12895. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  12896. << "ms, which suggests the body is being buffered and rescanned";
  12897. }
  12898. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  12899. // A boundary can only be followed by CRLF or by "--", so anything else is
  12900. // malformed no matter what comes next. The parser must say so right away
  12901. // instead of buffering the rest of the declared body.
  12902. Server svr;
  12903. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12904. res.set_content("ok", "text/plain");
  12905. });
  12906. auto port = svr.bind_to_any_port(HOST);
  12907. thread t = thread([&] { svr.listen_after_bind(); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. // Announce a 1 MB body but send only the malformed prefix. A parser that
  12915. // buffers instead of failing would still be waiting for the remaining bytes.
  12916. const std::string body = "--zzzz\r\n"
  12917. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12918. "\r\n"
  12919. "text1"
  12920. "\r\n--zzzzXX";
  12921. const std::string req = "POST /post HTTP/1.1\r\n"
  12922. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  12923. "Content-Length: 1048576\r\n"
  12924. "\r\n" +
  12925. body;
  12926. std::string response;
  12927. ASSERT_TRUE(send_request(3, req, &response, port));
  12928. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  12929. EXPECT_EQ("400", response.substr(9, 3));
  12930. }
  12931. // Posts a multipart body split into two writes, so that the server sees the
  12932. // split at whatever offset the caller chose, and expects the single "text1"
  12933. // field to come through.
  12934. static void expect_split_multipart_ok(const std::string &body1,
  12935. const std::string &body2) {
  12936. auto handled = false;
  12937. Server svr;
  12938. svr.Post("/post", [&](const Request &req, Response &) {
  12939. EXPECT_EQ(1u, req.form.fields.size());
  12940. EXPECT_EQ("text1", req.form.get_field("text1"));
  12941. handled = true;
  12942. });
  12943. auto port = svr.bind_to_any_port(HOST);
  12944. thread t = thread([&] { svr.listen_after_bind(); });
  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. // "Connection: close" makes the server close once it has answered, so the
  12953. // response drain ends immediately instead of idling until the read timeout.
  12954. const std::string head =
  12955. "POST /post HTTP/1.1\r\n"
  12956. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  12957. "Connection: close\r\n"
  12958. "Content-Length: " +
  12959. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  12960. std::string response;
  12961. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  12962. ASSERT_GE(response.size(), 12u) << "no response";
  12963. EXPECT_EQ("200", response.substr(9, 3));
  12964. }
  12965. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  12966. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  12967. // ignored, including when it does not arrive in the same read as the
  12968. // close-delimiter itself.
  12969. expect_split_multipart_ok("--zzzz\r\n"
  12970. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12971. "\r\n"
  12972. "text1"
  12973. "\r\n--zzzz--",
  12974. "\r\nthis epilogue must be ignored\r\n");
  12975. }
  12976. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  12977. // The initial boundary may be preceded by a preamble of any length and may
  12978. // straddle a read boundary. Discarding data while waiting for it must not
  12979. // throw away a partial boundary sitting at the end of the buffer.
  12980. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  12981. "zz\r\n"
  12982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12983. "\r\n"
  12984. "text1"
  12985. "\r\n--zzzz--\r\n");
  12986. }
  12987. TEST(MakeFileBodyTest, Basic) {
  12988. const std::string file_content(4096, 'Z');
  12989. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12990. {
  12991. std::ofstream ofs(tmp_path, std::ios::binary);
  12992. ofs.write(file_content.data(),
  12993. static_cast<std::streamsize>(file_content.size()));
  12994. }
  12995. auto handled = false;
  12996. Server svr;
  12997. svr.Post("/upload", [&](const Request &req, Response &res) {
  12998. EXPECT_EQ(file_content, req.body);
  12999. handled = true;
  13000. res.status = StatusCode::OK_200;
  13001. });
  13002. auto port = svr.bind_to_any_port(HOST);
  13003. auto t = thread([&] { svr.listen_after_bind(); });
  13004. auto se = detail::scope_exit([&] {
  13005. svr.stop();
  13006. t.join();
  13007. ASSERT_FALSE(svr.is_running());
  13008. ASSERT_TRUE(handled);
  13009. std::remove(tmp_path.c_str());
  13010. });
  13011. svr.wait_until_ready();
  13012. auto fb = make_file_body(tmp_path);
  13013. ASSERT_GT(fb.first, 0u);
  13014. Client cli(HOST, port);
  13015. auto res =
  13016. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13018. EXPECT_EQ(StatusCode::OK_200, res->status);
  13019. }
  13020. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13021. static constexpr unsigned int number_of_tasks{1000000};
  13022. std::atomic_uint count{0};
  13023. std::unique_ptr<TaskQueue> task_queue{
  13024. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13025. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13026. auto queued = task_queue->enqueue(
  13027. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13028. EXPECT_TRUE(queued);
  13029. }
  13030. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13031. task_queue->shutdown();
  13032. #else
  13033. EXPECT_NO_THROW(task_queue->shutdown());
  13034. #endif
  13035. EXPECT_EQ(number_of_tasks, count.load());
  13036. }
  13037. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13038. static constexpr unsigned int number_of_tasks{1000000};
  13039. static constexpr unsigned int qlimit{2};
  13040. unsigned int queued_count{0};
  13041. std::atomic_uint count{0};
  13042. std::unique_ptr<TaskQueue> task_queue{
  13043. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13044. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13045. if (task_queue->enqueue(
  13046. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13047. queued_count++;
  13048. }
  13049. }
  13050. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13051. task_queue->shutdown();
  13052. #else
  13053. EXPECT_NO_THROW(task_queue->shutdown());
  13054. #endif
  13055. EXPECT_EQ(queued_count, count.load());
  13056. EXPECT_TRUE(queued_count <= number_of_tasks);
  13057. EXPECT_TRUE(queued_count >= qlimit);
  13058. }
  13059. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13060. // Use a short idle timeout so a dynamic thread spawns, times out and
  13061. // exits during the test, and the pool keeps working afterwards.
  13062. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13063. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13064. /*idle_timeout_sec=*/1}};
  13065. std::atomic_uint count{0};
  13066. std::condition_variable cv;
  13067. std::mutex mtx;
  13068. bool release = false;
  13069. // Block the base thread so the second task spawns a dynamic thread.
  13070. EXPECT_TRUE(task_queue->enqueue([&] {
  13071. std::unique_lock<std::mutex> lock(mtx);
  13072. while (!release) {
  13073. cv.wait(lock);
  13074. }
  13075. count++;
  13076. }));
  13077. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13078. // Let the dynamic thread finish its task and exceed the idle timeout.
  13079. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13080. {
  13081. std::unique_lock<std::mutex> lock(mtx);
  13082. release = true;
  13083. }
  13084. cv.notify_all();
  13085. // The pool must still accept and run tasks after the dynamic thread exited.
  13086. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13087. task_queue->shutdown();
  13088. EXPECT_EQ(3u, count.load());
  13089. }
  13090. TEST(TaskQueueTest, MaxQueuedRequests) {
  13091. static constexpr unsigned int qlimit{3};
  13092. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13093. std::condition_variable sem_cv;
  13094. std::mutex sem_mtx;
  13095. int credits = 0;
  13096. bool queued;
  13097. /* Fill up the queue with tasks that will block until we give them credits to
  13098. * complete. */
  13099. for (unsigned int n = 0; n <= qlimit;) {
  13100. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13101. std::unique_lock<std::mutex> lock(sem_mtx);
  13102. while (credits <= 0) {
  13103. sem_cv.wait(lock);
  13104. }
  13105. /* Consume the credit and signal the test code if they are all gone. */
  13106. if (--credits == 0) { sem_cv.notify_one(); }
  13107. });
  13108. if (n < qlimit) {
  13109. /* The first qlimit enqueues must succeed. */
  13110. EXPECT_TRUE(queued);
  13111. } else {
  13112. /* The last one will succeed only when the worker thread
  13113. * starts and dequeues the first blocking task. Although
  13114. * not necessary for the correctness of this test, we sleep for
  13115. * a short while to avoid busy waiting. */
  13116. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13117. }
  13118. if (queued) { n++; }
  13119. }
  13120. /* Further enqueues must fail since the queue is full. */
  13121. for (auto i = 0; i < 4; i++) {
  13122. queued = task_queue->enqueue([] {});
  13123. EXPECT_FALSE(queued);
  13124. }
  13125. /* Give the credits to allow the previous tasks to complete. */
  13126. {
  13127. std::unique_lock<std::mutex> lock(sem_mtx);
  13128. credits += qlimit + 1;
  13129. }
  13130. sem_cv.notify_all();
  13131. /* Wait for all the credits to be consumed. */
  13132. {
  13133. std::unique_lock<std::mutex> lock(sem_mtx);
  13134. while (credits > 0) {
  13135. sem_cv.wait(lock);
  13136. }
  13137. }
  13138. /* Check that we are able again to enqueue at least qlimit tasks. */
  13139. for (unsigned int i = 0; i < qlimit; i++) {
  13140. queued = task_queue->enqueue([] {});
  13141. EXPECT_TRUE(queued);
  13142. }
  13143. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13144. task_queue->shutdown();
  13145. #else
  13146. EXPECT_NO_THROW(task_queue->shutdown());
  13147. #endif
  13148. }
  13149. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13150. Server svr;
  13151. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13152. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13153. });
  13154. svr.Get("/hello", [](const Request &req, Response &res) {
  13155. res.set_content(req.get_param_value("key"), "text/plain");
  13156. });
  13157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13158. auto se = detail::scope_exit([&] {
  13159. svr.stop();
  13160. thread.join();
  13161. ASSERT_FALSE(svr.is_running());
  13162. });
  13163. svr.wait_until_ready();
  13164. {
  13165. Client cli(HOST, PORT);
  13166. cli.set_follow_location(true);
  13167. auto res = cli.Get("/");
  13168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13169. EXPECT_EQ(StatusCode::OK_200, res->status);
  13170. EXPECT_EQ("val&key2=val2", res->body);
  13171. }
  13172. }
  13173. #endif
  13174. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13175. Server svr;
  13176. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13177. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13178. });
  13179. svr.Get("/hello", [](const Request &req, Response &res) {
  13180. res.set_content(req.get_param_value("key"), "text/plain");
  13181. });
  13182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13183. auto se = detail::scope_exit([&] {
  13184. svr.stop();
  13185. thread.join();
  13186. ASSERT_FALSE(svr.is_running());
  13187. });
  13188. svr.wait_until_ready();
  13189. {
  13190. Client cli(HOST, PORT);
  13191. cli.set_follow_location(true);
  13192. auto res = cli.Get("/");
  13193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13194. EXPECT_EQ(StatusCode::OK_200, res->status);
  13195. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13196. }
  13197. }
  13198. TEST(RedirectTest, RedirectWithPlusInPath) {
  13199. Server svr;
  13200. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13201. res.set_redirect("/a+b");
  13202. });
  13203. // Route pattern uses regex; escape + as \\+
  13204. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13205. res.set_content(req.path, "text/plain");
  13206. });
  13207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. thread.join();
  13211. ASSERT_FALSE(svr.is_running());
  13212. });
  13213. svr.wait_until_ready();
  13214. {
  13215. Client cli(HOST, PORT);
  13216. cli.set_follow_location(true);
  13217. auto res = cli.Get("/");
  13218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13219. EXPECT_EQ(StatusCode::OK_200, res->status);
  13220. EXPECT_EQ("/a+b", res->body);
  13221. }
  13222. }
  13223. #ifdef CPPHTTPLIB_SSL_ENABLED
  13224. TEST(RedirectTest, Issue2185_Online) {
  13225. SSLClient client("github.com");
  13226. client.set_follow_location(true);
  13227. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13228. "Coollab-Windows.zip");
  13229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13230. EXPECT_EQ(StatusCode::OK_200, res->status);
  13231. EXPECT_EQ(9920427U, res->body.size());
  13232. }
  13233. #endif
  13234. TEST(VulnerabilityTest, CRLFInjection) {
  13235. Server svr;
  13236. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13237. res.set_content("Hello 1", "text/plain");
  13238. });
  13239. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13240. res.set_content("Hello 2", "text/plain");
  13241. });
  13242. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13243. res.set_content("Hello 3", "text/plain");
  13244. });
  13245. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13246. res.set_content("Hello 4", "text/plain");
  13247. });
  13248. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13249. for (const auto &x : req.headers) {
  13250. auto key = x.first;
  13251. EXPECT_STRNE("evil", key.c_str());
  13252. }
  13253. });
  13254. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13255. auto se = detail::scope_exit([&] {
  13256. svr.stop();
  13257. thread.join();
  13258. ASSERT_FALSE(svr.is_running());
  13259. });
  13260. svr.wait_until_ready();
  13261. {
  13262. Client cli(HOST, PORT);
  13263. cli.Post("/test1", "A=B",
  13264. "application/x-www-form-urlencoded\r\nevil: hello1");
  13265. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13266. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13267. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13268. }
  13269. }
  13270. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13271. auto server_thread = std::thread([] {
  13272. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13273. default_socket_options(srv);
  13274. sockaddr_in addr{};
  13275. addr.sin_family = AF_INET;
  13276. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13277. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13278. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13279. ::listen(srv, 1);
  13280. sockaddr_in cli_addr{};
  13281. socklen_t cli_len = sizeof(cli_addr);
  13282. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13283. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13284. std::string buf_all;
  13285. char buf[2048];
  13286. ssize_t n;
  13287. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13288. buf_all.append(buf, static_cast<size_t>(n));
  13289. size_t pos;
  13290. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13291. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13292. auto e = request_block.find("\r\n");
  13293. if (e != std::string::npos) {
  13294. auto request_line = request_block.substr(0, e);
  13295. std::string msg =
  13296. "CRLF injection detected in request line: '" + request_line + "'";
  13297. EXPECT_FALSE(true) << msg;
  13298. }
  13299. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13300. ::send(cli,
  13301. #ifdef _WIN32
  13302. static_cast<const char *>(resp.c_str()),
  13303. static_cast<int>(resp.size()),
  13304. #else
  13305. resp.c_str(), resp.size(),
  13306. #endif
  13307. 0);
  13308. buf_all.erase(0, pos + 4);
  13309. }
  13310. }
  13311. detail::close_socket(cli);
  13312. detail::close_socket(srv);
  13313. });
  13314. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13315. auto cli = Client("127.0.0.1", PORT + 1);
  13316. auto headers = Headers{
  13317. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13318. {"Connection", "keep-alive"}};
  13319. auto res = cli.Get("/hi", headers);
  13320. EXPECT_FALSE(res);
  13321. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13322. server_thread.join();
  13323. }
  13324. TEST(PathParamsTest, StaticMatch) {
  13325. const auto pattern = "/users/all";
  13326. detail::PathParamsMatcher matcher(pattern);
  13327. Request request;
  13328. request.path = "/users/all";
  13329. ASSERT_TRUE(matcher.match(request));
  13330. std::unordered_map<std::string, std::string> expected_params = {};
  13331. EXPECT_EQ(request.path_params, expected_params);
  13332. }
  13333. TEST(PathParamsTest, StaticMismatch) {
  13334. const auto pattern = "/users/all";
  13335. detail::PathParamsMatcher matcher(pattern);
  13336. Request request;
  13337. request.path = "/users/1";
  13338. ASSERT_FALSE(matcher.match(request));
  13339. }
  13340. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13341. const auto pattern = "/users/:id/subscriptions";
  13342. detail::PathParamsMatcher matcher(pattern);
  13343. Request request;
  13344. request.path = "/users/42/subscriptions";
  13345. ASSERT_TRUE(matcher.match(request));
  13346. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13347. EXPECT_EQ(request.path_params, expected_params);
  13348. }
  13349. TEST(PathParamsTest, SingleParamInTheEnd) {
  13350. const auto pattern = "/users/:id";
  13351. detail::PathParamsMatcher matcher(pattern);
  13352. Request request;
  13353. request.path = "/users/24";
  13354. ASSERT_TRUE(matcher.match(request));
  13355. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13356. EXPECT_EQ(request.path_params, expected_params);
  13357. }
  13358. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13359. const auto pattern = "/users/:id/";
  13360. detail::PathParamsMatcher matcher(pattern);
  13361. Request request;
  13362. request.path = "/users/42/";
  13363. ASSERT_TRUE(matcher.match(request));
  13364. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13365. EXPECT_EQ(request.path_params, expected_params);
  13366. }
  13367. TEST(PathParamsTest, EmptyParam) {
  13368. const auto pattern = "/users/:id/";
  13369. detail::PathParamsMatcher matcher(pattern);
  13370. Request request;
  13371. request.path = "/users//";
  13372. ASSERT_TRUE(matcher.match(request));
  13373. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13374. EXPECT_EQ(request.path_params, expected_params);
  13375. }
  13376. TEST(PathParamsTest, FragmentMismatch) {
  13377. const auto pattern = "/users/:id/";
  13378. detail::PathParamsMatcher matcher(pattern);
  13379. Request request;
  13380. request.path = "/admins/24/";
  13381. ASSERT_FALSE(matcher.match(request));
  13382. }
  13383. TEST(PathParamsTest, ExtraFragments) {
  13384. const auto pattern = "/users/:id";
  13385. detail::PathParamsMatcher matcher(pattern);
  13386. Request request;
  13387. request.path = "/users/42/subscriptions";
  13388. ASSERT_FALSE(matcher.match(request));
  13389. }
  13390. TEST(PathParamsTest, MissingTrailingParam) {
  13391. const auto pattern = "/users/:id";
  13392. detail::PathParamsMatcher matcher(pattern);
  13393. Request request;
  13394. request.path = "/users";
  13395. ASSERT_FALSE(matcher.match(request));
  13396. }
  13397. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13398. const auto pattern = "/users/:id/subscriptions";
  13399. detail::PathParamsMatcher matcher(pattern);
  13400. Request request;
  13401. request.path = "/users/subscriptions";
  13402. ASSERT_FALSE(matcher.match(request));
  13403. }
  13404. TEST(PathParamsTest, MultipleParams) {
  13405. const auto pattern = "/users/:userid/subscriptions/:subid";
  13406. detail::PathParamsMatcher matcher(pattern);
  13407. Request request;
  13408. request.path = "/users/42/subscriptions/2";
  13409. ASSERT_TRUE(matcher.match(request));
  13410. std::unordered_map<std::string, std::string> expected_params = {
  13411. {"userid", "42"}, {"subid", "2"}};
  13412. EXPECT_EQ(request.path_params, expected_params);
  13413. }
  13414. TEST(PathParamsTest, SequenceOfParams) {
  13415. const auto pattern = "/values/:x/:y/:z";
  13416. detail::PathParamsMatcher matcher(pattern);
  13417. Request request;
  13418. request.path = "/values/1/2/3";
  13419. ASSERT_TRUE(matcher.match(request));
  13420. std::unordered_map<std::string, std::string> expected_params = {
  13421. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13422. EXPECT_EQ(request.path_params, expected_params);
  13423. }
  13424. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13425. const auto pattern = "/prefix:suffix";
  13426. detail::PathParamsMatcher matcher(pattern);
  13427. Request request;
  13428. request.path = "/prefix:suffix";
  13429. ASSERT_TRUE(matcher.match(request));
  13430. const std::unordered_map<std::string, std::string> expected_params = {};
  13431. EXPECT_EQ(request.path_params, expected_params);
  13432. }
  13433. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13434. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13435. // calling thread's stack on a long enough path for a quantified pattern;
  13436. // RegexMatcher must refuse to run regex matching on paths beyond
  13437. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13438. detail::RegexMatcher matcher("/files/(.*)");
  13439. Request within_limit;
  13440. within_limit.path = "/files/" + std::string(10, 'A');
  13441. EXPECT_TRUE(matcher.match(within_limit));
  13442. Request over_limit;
  13443. over_limit.path =
  13444. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13445. EXPECT_FALSE(matcher.match(over_limit));
  13446. }
  13447. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13448. Server svr;
  13449. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13450. res.set_content("ok", "text/plain");
  13451. });
  13452. auto port = svr.bind_to_any_port(HOST);
  13453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13454. auto se = detail::scope_exit([&] {
  13455. svr.stop();
  13456. thread.join();
  13457. ASSERT_FALSE(svr.is_running());
  13458. });
  13459. svr.wait_until_ready();
  13460. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13461. // request URI limit; this used to be able to crash the process.
  13462. std::string path =
  13463. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13464. std::string req = "GET " + path +
  13465. " HTTP/1.1\r\n"
  13466. "Host: " +
  13467. std::string(HOST) + ":" + std::to_string(port) +
  13468. "\r\n"
  13469. "Connection: close\r\n"
  13470. "\r\n";
  13471. std::string response;
  13472. ASSERT_TRUE(send_request(5, req, &response, port));
  13473. EXPECT_NE(std::string::npos, response.find("404"));
  13474. }
  13475. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13476. Server svr;
  13477. auto handler = [](const Request & /*req*/, Response &res) {
  13478. res.set_content("hit", "text/plain");
  13479. };
  13480. // No regex metacharacter, so this one is compared literally
  13481. svr.Get("/literal/route", handler);
  13482. // '.' is a regex metacharacter, so this one must keep regex semantics
  13483. svr.Get("/a.c", handler);
  13484. auto port = svr.bind_to_any_port(HOST);
  13485. std::thread t([&]() { svr.listen_after_bind(); });
  13486. auto se = detail::scope_exit([&] {
  13487. svr.stop();
  13488. t.join();
  13489. ASSERT_FALSE(svr.is_running());
  13490. });
  13491. svr.wait_until_ready();
  13492. Client cli(HOST, port);
  13493. struct {
  13494. const char *path;
  13495. int status;
  13496. } cases[] = {
  13497. {"/literal/route", StatusCode::OK_200},
  13498. {"/literal/routes", StatusCode::NotFound_404},
  13499. {"/literal/rout", StatusCode::NotFound_404},
  13500. {"/abc", StatusCode::OK_200},
  13501. {"/a.c", StatusCode::OK_200},
  13502. };
  13503. for (const auto &x : cases) {
  13504. auto res = cli.Get(x.path);
  13505. ASSERT_TRUE(res) << x.path;
  13506. EXPECT_EQ(x.status, res->status) << x.path;
  13507. }
  13508. }
  13509. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13510. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13511. // from exhausting the stack, so it must only constrain routes that actually
  13512. // run a regular expression. A literal route is matched by comparison and
  13513. // stays usable at any length.
  13514. Server svr;
  13515. const std::string pattern =
  13516. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13517. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13518. res.set_content("hit", "text/plain");
  13519. });
  13520. auto port = svr.bind_to_any_port(HOST);
  13521. std::thread t([&]() { svr.listen_after_bind(); });
  13522. auto se = detail::scope_exit([&] {
  13523. svr.stop();
  13524. t.join();
  13525. ASSERT_FALSE(svr.is_running());
  13526. });
  13527. svr.wait_until_ready();
  13528. Client cli(HOST, port);
  13529. auto res = cli.Get(pattern);
  13530. ASSERT_TRUE(res);
  13531. EXPECT_EQ(StatusCode::OK_200, res->status);
  13532. }
  13533. TEST(ParseUrlTest, VariousPatterns) {
  13534. {
  13535. detail::UrlComponents uc;
  13536. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13537. EXPECT_EQ("http", uc.scheme);
  13538. EXPECT_EQ("example.com", uc.host);
  13539. EXPECT_EQ("8080", uc.port);
  13540. EXPECT_EQ("/path", uc.path);
  13541. EXPECT_EQ("?q=1", uc.query);
  13542. }
  13543. {
  13544. detail::UrlComponents uc;
  13545. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13546. EXPECT_EQ("https", uc.scheme);
  13547. EXPECT_EQ("example.com", uc.host);
  13548. EXPECT_TRUE(uc.port.empty());
  13549. EXPECT_EQ("/path", uc.path);
  13550. }
  13551. {
  13552. detail::UrlComponents uc;
  13553. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13554. EXPECT_EQ("::1", uc.host);
  13555. EXPECT_EQ("8080", uc.port);
  13556. EXPECT_EQ("/path", uc.path);
  13557. }
  13558. {
  13559. detail::UrlComponents uc;
  13560. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13561. }
  13562. {
  13563. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13564. // the path while the connection still targets the bracketed host.
  13565. detail::UrlComponents uc;
  13566. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13567. }
  13568. {
  13569. detail::UrlComponents uc;
  13570. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13571. }
  13572. {
  13573. detail::UrlComponents uc;
  13574. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13575. EXPECT_EQ("::1", uc.host);
  13576. EXPECT_TRUE(uc.port.empty());
  13577. EXPECT_EQ("/path", uc.path);
  13578. }
  13579. {
  13580. detail::UrlComponents uc;
  13581. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13582. EXPECT_TRUE(uc.scheme.empty());
  13583. EXPECT_EQ("example.com", uc.host);
  13584. EXPECT_EQ("/path", uc.path);
  13585. EXPECT_EQ("?q=1", uc.query);
  13586. }
  13587. {
  13588. detail::UrlComponents uc;
  13589. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13590. EXPECT_TRUE(uc.host.empty());
  13591. EXPECT_EQ("/path", uc.path);
  13592. EXPECT_EQ("?q=1", uc.query);
  13593. }
  13594. {
  13595. detail::UrlComponents uc;
  13596. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13597. EXPECT_EQ("example.com", uc.host);
  13598. EXPECT_EQ("8080", uc.port);
  13599. }
  13600. {
  13601. // Unix socket path — must not be parsed as host
  13602. detail::UrlComponents uc;
  13603. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13604. EXPECT_TRUE(uc.host.empty());
  13605. }
  13606. {
  13607. detail::UrlComponents uc;
  13608. ASSERT_TRUE(detail::parse_url("", uc));
  13609. EXPECT_TRUE(uc.host.empty());
  13610. EXPECT_TRUE(uc.path.empty());
  13611. }
  13612. {
  13613. detail::UrlComponents uc;
  13614. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13615. }
  13616. {
  13617. detail::UrlComponents uc;
  13618. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13619. }
  13620. {
  13621. // Accepted by parse_url; callers restrict to http/https
  13622. detail::UrlComponents uc;
  13623. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13624. EXPECT_EQ("ftp", uc.scheme);
  13625. }
  13626. {
  13627. detail::UrlComponents uc;
  13628. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13629. }
  13630. {
  13631. detail::UrlComponents uc;
  13632. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13633. }
  13634. }
  13635. TEST(ParseUrlTest, FragmentHandling) {
  13636. {
  13637. detail::UrlComponents uc;
  13638. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13639. EXPECT_EQ("/path", uc.path);
  13640. EXPECT_TRUE(uc.query.empty());
  13641. }
  13642. {
  13643. detail::UrlComponents uc;
  13644. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13645. EXPECT_TRUE(uc.path.empty());
  13646. EXPECT_TRUE(uc.query.empty());
  13647. }
  13648. }
  13649. TEST(ParseUrlTest, UserinfoHandling) {
  13650. // Userinfo with @ but no colon — host includes @
  13651. detail::UrlComponents uc;
  13652. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13653. EXPECT_EQ("user@host.com", uc.host);
  13654. EXPECT_EQ("/path", uc.path);
  13655. }
  13656. TEST(ParseUrlTest, IPv6EdgeCases) {
  13657. {
  13658. detail::UrlComponents uc;
  13659. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13660. EXPECT_TRUE(uc.scheme.empty());
  13661. EXPECT_EQ("::1", uc.host);
  13662. EXPECT_EQ("8080", uc.port);
  13663. }
  13664. {
  13665. // Zone ID '%25' is not in [a-fA-F0-9:]
  13666. detail::UrlComponents uc;
  13667. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13668. }
  13669. }
  13670. TEST(ParseUrlTest, SchemeEdgeCases) {
  13671. {
  13672. detail::UrlComponents uc;
  13673. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13674. }
  13675. {
  13676. detail::UrlComponents uc;
  13677. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13678. }
  13679. {
  13680. detail::UrlComponents uc;
  13681. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13682. }
  13683. }
  13684. TEST(ParseUrlTest, PortEdgeCases) {
  13685. {
  13686. detail::UrlComponents uc;
  13687. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13688. EXPECT_TRUE(uc.port.empty());
  13689. EXPECT_EQ("/path", uc.path);
  13690. }
  13691. {
  13692. // parse_url accepts any port string; validation is done by parse_port
  13693. detail::UrlComponents uc;
  13694. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13695. EXPECT_EQ("abc", uc.port);
  13696. }
  13697. }
  13698. TEST(ParseUrlTest, WebSocketPatterns) {
  13699. {
  13700. detail::UrlComponents uc;
  13701. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13702. EXPECT_EQ("ws", uc.scheme);
  13703. EXPECT_EQ("echo.example.com", uc.host);
  13704. EXPECT_EQ("8080", uc.port);
  13705. EXPECT_EQ("/ws", uc.path);
  13706. }
  13707. {
  13708. detail::UrlComponents uc;
  13709. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13710. EXPECT_EQ("wss", uc.scheme);
  13711. EXPECT_EQ("echo.example.com", uc.host);
  13712. EXPECT_TRUE(uc.port.empty());
  13713. EXPECT_EQ("/ws", uc.path);
  13714. }
  13715. }
  13716. TEST(ParseUrlTest, QueryOnly) {
  13717. detail::UrlComponents uc;
  13718. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13719. EXPECT_TRUE(uc.host.empty());
  13720. EXPECT_TRUE(uc.path.empty());
  13721. EXPECT_EQ("?q=1&r=2", uc.query);
  13722. }
  13723. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13724. detail::UrlComponents uc;
  13725. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13726. EXPECT_TRUE(uc.scheme.empty());
  13727. EXPECT_EQ("example.com", uc.host);
  13728. EXPECT_EQ("443", uc.port);
  13729. EXPECT_EQ("/path", uc.path);
  13730. }
  13731. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13732. // If ipv6 regex working, regex match codepath is taken.
  13733. // else port will default to 80 in Client impl
  13734. int clientImplMagicPort = 80;
  13735. int port = 4321;
  13736. // above ports must be different to avoid false negative
  13737. EXPECT_NE(clientImplMagicPort, port);
  13738. std::string ipV6TestURL = "http://[ff06::c3]";
  13739. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13740. CLIENT_PRIVATE_KEY_FILE);
  13741. EXPECT_EQ(cli.port(), port);
  13742. }
  13743. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13744. auto file_path = "./www/dir/index.html";
  13745. auto dir_path = "./www/dir";
  13746. detail::FileStat stat_file(file_path);
  13747. EXPECT_TRUE(stat_file.is_file());
  13748. EXPECT_FALSE(stat_file.is_dir());
  13749. detail::FileStat stat_dir(dir_path);
  13750. EXPECT_FALSE(stat_dir.is_file());
  13751. EXPECT_TRUE(stat_dir.is_dir());
  13752. }
  13753. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13754. // IPv4 with default HTTP port (80)
  13755. EXPECT_EQ("example.com",
  13756. detail::make_host_and_port_string("example.com", 80, false));
  13757. // IPv4 with default HTTPS port (443)
  13758. EXPECT_EQ("example.com",
  13759. detail::make_host_and_port_string("example.com", 443, true));
  13760. // IPv4 with non-default HTTP port
  13761. EXPECT_EQ("example.com:8080",
  13762. detail::make_host_and_port_string("example.com", 8080, false));
  13763. // IPv4 with non-default HTTPS port
  13764. EXPECT_EQ("example.com:8443",
  13765. detail::make_host_and_port_string("example.com", 8443, true));
  13766. // IPv6 with default HTTP port (80)
  13767. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13768. // IPv6 with default HTTPS port (443)
  13769. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13770. // IPv6 with non-default HTTP port
  13771. EXPECT_EQ("[::1]:8080",
  13772. detail::make_host_and_port_string("::1", 8080, false));
  13773. // IPv6 with non-default HTTPS port
  13774. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13775. // IPv6 full address with default port
  13776. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13777. detail::make_host_and_port_string(
  13778. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13779. // IPv6 full address with non-default port
  13780. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13781. detail::make_host_and_port_string(
  13782. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13783. // IPv6 localhost with non-default port
  13784. EXPECT_EQ("[::1]:3000",
  13785. detail::make_host_and_port_string("::1", 3000, false));
  13786. // IPv6 with zone ID (link-local address) with default port
  13787. EXPECT_EQ("[fe80::1%eth0]",
  13788. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13789. // IPv6 with zone ID (link-local address) with non-default port
  13790. EXPECT_EQ("[fe80::1%eth0]:8080",
  13791. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13792. // Edge case: Port 443 with is_ssl=false (should add port)
  13793. EXPECT_EQ("example.com:443",
  13794. detail::make_host_and_port_string("example.com", 443, false));
  13795. // Edge case: Port 80 with is_ssl=true (should add port)
  13796. EXPECT_EQ("example.com:80",
  13797. detail::make_host_and_port_string("example.com", 80, true));
  13798. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13799. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13800. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13801. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13802. // Security fix: Already bracketed IPv6 should not get double brackets
  13803. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13804. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13805. EXPECT_EQ("[::1]:8080",
  13806. detail::make_host_and_port_string("[::1]", 8080, false));
  13807. EXPECT_EQ("[2001:db8::1]:8080",
  13808. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13809. EXPECT_EQ("[fe80::1%eth0]",
  13810. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13811. EXPECT_EQ("[fe80::1%eth0]:8080",
  13812. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13813. // Edge case: Empty host (should return as-is)
  13814. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13815. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13816. // This is a known limitation but shouldn't crash
  13817. EXPECT_EQ("[host:name]",
  13818. detail::make_host_and_port_string("host:name", 80, false));
  13819. // Port number edge cases (no validation, but should not crash)
  13820. EXPECT_EQ("example.com:0",
  13821. detail::make_host_and_port_string("example.com", 0, false));
  13822. EXPECT_EQ("example.com:-1",
  13823. detail::make_host_and_port_string("example.com", -1, false));
  13824. EXPECT_EQ("example.com:65535",
  13825. detail::make_host_and_port_string("example.com", 65535, false));
  13826. EXPECT_EQ("example.com:65536",
  13827. detail::make_host_and_port_string("example.com", 65536, false));
  13828. }
  13829. #ifdef CPPHTTPLIB_SSL_ENABLED
  13830. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13831. httplib::SSLClient cli("roblox.com", 443);
  13832. cli.set_follow_location(true);
  13833. auto res = cli.Get("/");
  13834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13835. EXPECT_EQ(StatusCode::OK_200, res->status);
  13836. }
  13837. #endif
  13838. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13839. Server svr;
  13840. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13841. EXPECT_EQ(res.status, 400);
  13842. });
  13843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13844. auto se = detail::scope_exit([&] {
  13845. svr.stop();
  13846. thread.join();
  13847. ASSERT_FALSE(svr.is_running());
  13848. });
  13849. svr.wait_until_ready();
  13850. Client cli(HOST, PORT);
  13851. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13852. }
  13853. TEST(InvalidHeaderCharsTest, is_field_name) {
  13854. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13855. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13856. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13857. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13858. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13859. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13860. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13861. EXPECT_FALSE(detail::fields::is_field_name(""));
  13862. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13863. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13864. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13865. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13866. }
  13867. TEST(InvalidHeaderCharsTest, is_field_value) {
  13868. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13869. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13870. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13871. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13872. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13873. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13874. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13875. EXPECT_TRUE(detail::fields::is_field_value(""));
  13876. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13877. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13878. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13879. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13880. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13881. }
  13882. TEST(InvalidHeaderCharsTest, OnServer) {
  13883. Server svr;
  13884. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13885. std::string header = "Not Set";
  13886. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13887. res.set_header(header, "value");
  13888. res.set_content("Page Content Page Content", "text/plain");
  13889. });
  13890. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13891. std::string header = "Not Set";
  13892. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13893. res.set_header("X-Test", header);
  13894. res.set_content("Page Content Page Content", "text/plain");
  13895. });
  13896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13897. auto se = detail::scope_exit([&] {
  13898. svr.stop();
  13899. thread.join();
  13900. ASSERT_FALSE(svr.is_running());
  13901. });
  13902. svr.wait_until_ready();
  13903. Client cli(HOST, PORT);
  13904. {
  13905. auto res = cli.Get(
  13906. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13908. EXPECT_EQ("Page Content Page Content", res->body);
  13909. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13910. }
  13911. {
  13912. auto res = cli.Get(
  13913. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13915. EXPECT_EQ("Page Content Page Content", res->body);
  13916. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13917. }
  13918. }
  13919. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13920. auto handled = false;
  13921. Server svr;
  13922. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13923. thread t = thread([&] { svr.listen(HOST, PORT); });
  13924. auto se = detail::scope_exit([&] {
  13925. svr.stop();
  13926. t.join();
  13927. ASSERT_FALSE(svr.is_running());
  13928. ASSERT_FALSE(handled);
  13929. });
  13930. svr.wait_until_ready();
  13931. auto req = "POST /test HTTP/1.1\r\n"
  13932. "Content-Length: x\r\n"
  13933. "\r\n";
  13934. std::string response;
  13935. ASSERT_TRUE(send_request(1, req, &response));
  13936. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13937. response.substr(0, response.find("\r\n")));
  13938. }
  13939. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13940. // case-insensitive, and a server that receives a 100-continue expectation in
  13941. // an HTTP/1.0 request MUST ignore it.
  13942. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13943. std::string response;
  13944. ASSERT_TRUE(send_request(1, req, &response, port));
  13945. *got_100 = response.find("100 Continue") != std::string::npos;
  13946. }
  13947. class ExpectTokenTest : public ::testing::Test {
  13948. protected:
  13949. void SetUp() override {
  13950. svr_.Post("/p", [](const Request &, Response &res) {
  13951. res.set_content("ok", "text/plain");
  13952. });
  13953. port_ = svr_.bind_to_any_port(HOST);
  13954. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13955. svr_.wait_until_ready();
  13956. }
  13957. void TearDown() override {
  13958. svr_.stop();
  13959. if (thread_.joinable()) { thread_.join(); }
  13960. }
  13961. std::string request(const char *version, const char *expect_value) const {
  13962. return std::string("POST /p ") + version +
  13963. "\r\n"
  13964. "Host: localhost\r\n"
  13965. "Content-Length: 2\r\n"
  13966. "Connection: close\r\n"
  13967. "Expect: " +
  13968. expect_value +
  13969. "\r\n"
  13970. "\r\n"
  13971. "hi";
  13972. }
  13973. Server svr_;
  13974. int port_ = 0;
  13975. thread thread_;
  13976. };
  13977. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13978. bool got_100 = false;
  13979. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13980. EXPECT_TRUE(got_100);
  13981. }
  13982. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13983. bool got_100 = true;
  13984. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13985. EXPECT_FALSE(got_100);
  13986. }
  13987. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13988. bool got_100 = false;
  13989. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13990. EXPECT_TRUE(got_100);
  13991. }
  13992. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13993. bool got_100 = false;
  13994. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13995. EXPECT_TRUE(got_100);
  13996. }
  13997. #ifndef _WIN32
  13998. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13999. static constexpr char reject[] = "Unauthorized";
  14000. static constexpr char accept[] = "Upload accepted";
  14001. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14002. Server svr;
  14003. svr.set_expect_100_continue_handler(
  14004. [](const Request & /*req*/, Response &res) {
  14005. res.status = StatusCode::Unauthorized_401;
  14006. res.set_content(reject, "text/plain");
  14007. return res.status;
  14008. });
  14009. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14010. res.set_content(accept, "text/plain");
  14011. });
  14012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14013. auto se = detail::scope_exit([&] {
  14014. svr.stop();
  14015. thread.join();
  14016. ASSERT_FALSE(svr.is_running());
  14017. });
  14018. svr.wait_until_ready();
  14019. {
  14020. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14021. curl_easy_init(), &curl_easy_cleanup};
  14022. ASSERT_NE(curl, nullptr);
  14023. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14024. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14025. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14026. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14027. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14028. &curl_slist_free_all};
  14029. ASSERT_NE(list, nullptr);
  14030. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14031. struct read_data {
  14032. size_t read_size;
  14033. size_t total_size;
  14034. } data = {0, total_size};
  14035. using read_callback_t =
  14036. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14037. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14038. void *userdata) -> size_t {
  14039. read_data *d = (read_data *)userdata;
  14040. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14041. std::fill_n(ptr, size * nmemb, 'A');
  14042. d->read_size += size * nmemb;
  14043. return size * nmemb;
  14044. };
  14045. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14046. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14047. std::vector<char> buffer;
  14048. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14049. using write_callback_t =
  14050. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14051. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14052. void *userdata) -> size_t {
  14053. std::vector<char> *buf = (std::vector<char> *)userdata;
  14054. buf->reserve(buf->size() + size * nmemb + 1);
  14055. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14056. return size * nmemb;
  14057. };
  14058. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14059. {
  14060. const auto res = curl_easy_perform(curl.get());
  14061. ASSERT_EQ(res, CURLE_OK);
  14062. }
  14063. {
  14064. auto response_code = long{};
  14065. const auto res =
  14066. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14067. ASSERT_EQ(res, CURLE_OK);
  14068. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14069. }
  14070. {
  14071. auto dl = curl_off_t{};
  14072. const auto res =
  14073. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14074. ASSERT_EQ(res, CURLE_OK);
  14075. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14076. }
  14077. {
  14078. buffer.push_back('\0');
  14079. ASSERT_STRCASEEQ(buffer.data(), reject);
  14080. }
  14081. }
  14082. }
  14083. #endif
  14084. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14085. // Regression test for #2458.
  14086. //
  14087. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14088. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14089. // ticket can make the client socket spuriously readable during the
  14090. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14091. // the client withholds the body and then blocks reading a response that never
  14092. // comes, failing with `Failed to read connection`.
  14093. //
  14094. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14095. // within the timeout. This raw OpenSSL server deliberately never sends
  14096. // `100 Continue`; the client must still deliver the body and receive 200.
  14097. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14098. signal(SIGPIPE, SIG_IGN);
  14099. const auto port = PORT + 4;
  14100. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14101. ASSERT_NE(srv, INVALID_SOCKET);
  14102. int opt = 1;
  14103. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14104. sockaddr_in addr{};
  14105. addr.sin_family = AF_INET;
  14106. addr.sin_port = htons(static_cast<uint16_t>(port));
  14107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14108. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14109. ASSERT_EQ(0, ::listen(srv, 1));
  14110. std::atomic<size_t> server_body_bytes{0};
  14111. auto server_thread = std::thread([&] {
  14112. sockaddr_in cli_addr{};
  14113. socklen_t cli_len = sizeof(cli_addr);
  14114. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14115. if (cli == INVALID_SOCKET) { return; }
  14116. // Bound the lifetime of the server side so a buggy client (which never
  14117. // sends the body) cannot make this thread block forever on join.
  14118. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14119. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14120. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14121. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14122. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14123. SSL *ssl = SSL_new(ctx);
  14124. SSL_set_fd(ssl, static_cast<int>(cli));
  14125. if (SSL_accept(ssl) > 0) {
  14126. // Read the request headers. Reading here also flushes the TLS 1.3
  14127. // session tickets to the client. Deliberately do NOT send
  14128. // `100 Continue`.
  14129. std::string buf;
  14130. char tmp[1024];
  14131. while (buf.find("\r\n\r\n") == std::string::npos) {
  14132. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14133. if (n <= 0) { break; }
  14134. buf.append(tmp, static_cast<size_t>(n));
  14135. }
  14136. // A correct client sends the body now; count what arrives.
  14137. auto pos = buf.find("\r\n\r\n");
  14138. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14139. while (body < 4096) {
  14140. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14141. if (n <= 0) { break; }
  14142. body += static_cast<size_t>(n);
  14143. }
  14144. server_body_bytes = body;
  14145. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14146. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14147. SSL_shutdown(ssl);
  14148. }
  14149. SSL_free(ssl);
  14150. detail::close_socket(cli);
  14151. SSL_CTX_free(ctx);
  14152. });
  14153. auto se = detail::scope_exit([&] {
  14154. server_thread.join();
  14155. detail::close_socket(srv);
  14156. });
  14157. SSLClient cli("127.0.0.1", port);
  14158. cli.enable_server_certificate_verification(false);
  14159. cli.set_connection_timeout(5, 0);
  14160. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14161. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14162. std::string body(4096, 'A');
  14163. auto res = cli.Put("/api/test", body, "application/json");
  14164. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14165. EXPECT_EQ(StatusCode::OK_200, res->status);
  14166. EXPECT_EQ(body.size(), server_body_bytes.load());
  14167. }
  14168. #endif
  14169. template <typename S, typename C>
  14170. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14171. svr.Get("/stream", [&](const Request &, Response &res) {
  14172. auto data = new std::string("01234567890123456789");
  14173. res.set_content_provider(
  14174. data->size(), "text/plain",
  14175. [&, data](size_t offset, size_t length, DataSink &sink) {
  14176. const size_t DATA_CHUNK_SIZE = 4;
  14177. const auto &d = *data;
  14178. std::this_thread::sleep_for(std::chrono::seconds(1));
  14179. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14180. return true;
  14181. },
  14182. [data](bool success) {
  14183. EXPECT_FALSE(success);
  14184. delete data;
  14185. });
  14186. });
  14187. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14188. auto i = new size_t(0);
  14189. res.set_content_provider(
  14190. "text/plain",
  14191. [i](size_t, DataSink &sink) {
  14192. if (*i < 5) {
  14193. std::this_thread::sleep_for(std::chrono::seconds(1));
  14194. sink.write("abcd", 4);
  14195. (*i)++;
  14196. } else {
  14197. sink.done();
  14198. }
  14199. return true;
  14200. },
  14201. [i](bool success) {
  14202. EXPECT_FALSE(success);
  14203. delete i;
  14204. });
  14205. });
  14206. svr.Get("/chunked", [&](const Request &, Response &res) {
  14207. auto i = new size_t(0);
  14208. res.set_chunked_content_provider(
  14209. "text/plain",
  14210. [i](size_t, DataSink &sink) {
  14211. if (*i < 5) {
  14212. std::this_thread::sleep_for(std::chrono::seconds(1));
  14213. sink.os << "abcd";
  14214. (*i)++;
  14215. } else {
  14216. sink.done();
  14217. }
  14218. return true;
  14219. },
  14220. [i](bool success) {
  14221. EXPECT_FALSE(success);
  14222. delete i;
  14223. });
  14224. });
  14225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14226. auto se = detail::scope_exit([&] {
  14227. svr.stop();
  14228. listen_thread.join();
  14229. ASSERT_FALSE(svr.is_running());
  14230. });
  14231. svr.wait_until_ready();
  14232. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14233. {
  14234. auto start = std::chrono::steady_clock::now();
  14235. auto res = cli.Get("/stream");
  14236. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14237. std::chrono::steady_clock::now() - start)
  14238. .count();
  14239. ASSERT_FALSE(res);
  14240. EXPECT_EQ(Error::Read, res.error());
  14241. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14242. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14243. }
  14244. {
  14245. auto start = std::chrono::steady_clock::now();
  14246. auto res = cli.Get("/stream_without_length");
  14247. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14248. std::chrono::steady_clock::now() - start)
  14249. .count();
  14250. ASSERT_FALSE(res);
  14251. EXPECT_EQ(Error::Read, res.error());
  14252. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14253. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14254. }
  14255. {
  14256. auto start = std::chrono::steady_clock::now();
  14257. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14258. EXPECT_EQ("abcd", string(data, data_length));
  14259. return true;
  14260. });
  14261. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14262. std::chrono::steady_clock::now() - start)
  14263. .count();
  14264. ASSERT_FALSE(res);
  14265. EXPECT_EQ(Error::Read, res.error());
  14266. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14267. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14268. }
  14269. }
  14270. TEST(MaxTimeoutTest, ContentStream) {
  14271. time_t timeout = 2000;
  14272. time_t threshold = 200;
  14273. Server svr;
  14274. Client cli("localhost", PORT);
  14275. max_timeout_test(svr, cli, timeout, threshold);
  14276. }
  14277. #ifdef CPPHTTPLIB_SSL_ENABLED
  14278. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14279. time_t timeout = 2000;
  14280. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14282. SSLClient cli("localhost", PORT);
  14283. cli.enable_server_certificate_verification(false);
  14284. max_timeout_test(svr, cli, timeout, threshold);
  14285. }
  14286. #endif
  14287. class EventDispatcher {
  14288. public:
  14289. EventDispatcher() {}
  14290. bool wait_event(DataSink *sink) {
  14291. unique_lock<mutex> lk(m_);
  14292. int id = id_;
  14293. // Wait with timeout to prevent hanging if client disconnects
  14294. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14295. [&] { return cid_ == id; })) {
  14296. return false; // Timeout occurred
  14297. }
  14298. sink->write(message_.data(), message_.size());
  14299. return true;
  14300. }
  14301. void send_event(const string &message) {
  14302. lock_guard<mutex> lk(m_);
  14303. cid_ = id_++;
  14304. message_ = message;
  14305. cv_.notify_all();
  14306. }
  14307. private:
  14308. mutex m_;
  14309. condition_variable cv_;
  14310. atomic_int id_{0};
  14311. atomic_int cid_{-1};
  14312. string message_;
  14313. };
  14314. TEST(ClientInThreadTest, Issue2068) {
  14315. EventDispatcher ed;
  14316. Server svr;
  14317. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14318. res.set_chunked_content_provider("text/event-stream",
  14319. [&](size_t /*offset*/, DataSink &sink) {
  14320. return ed.wait_event(&sink);
  14321. });
  14322. });
  14323. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14324. svr.wait_until_ready();
  14325. thread event_thread([&] {
  14326. int id = 0;
  14327. while (svr.is_running()) {
  14328. this_thread::sleep_for(chrono::milliseconds(500));
  14329. std::stringstream ss;
  14330. ss << "data: " << id << "\n\n";
  14331. ed.send_event(ss.str());
  14332. id++;
  14333. }
  14334. });
  14335. auto se = detail::scope_exit([&] {
  14336. svr.stop();
  14337. listen_thread.join();
  14338. event_thread.join();
  14339. ASSERT_FALSE(svr.is_running());
  14340. });
  14341. {
  14342. auto client = detail::make_unique<Client>(HOST, PORT);
  14343. client->set_read_timeout(std::chrono::minutes(10));
  14344. std::atomic<bool> stop{false};
  14345. std::thread t([&] {
  14346. client->Get("/event1",
  14347. [&](const char *, size_t) -> bool { return !stop; });
  14348. });
  14349. std::this_thread::sleep_for(std::chrono::seconds(2));
  14350. stop = true;
  14351. client->stop();
  14352. t.join();
  14353. // Reset client after thread has finished
  14354. client.reset();
  14355. }
  14356. }
  14357. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14358. auto handled = false;
  14359. Server svr;
  14360. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14362. auto se = detail::scope_exit([&] {
  14363. svr.stop();
  14364. t.join();
  14365. ASSERT_FALSE(svr.is_running());
  14366. ASSERT_FALSE(handled);
  14367. });
  14368. svr.wait_until_ready();
  14369. // Two Content-Length headers with different values — must be rejected
  14370. auto req = "POST /test HTTP/1.1\r\n"
  14371. "Content-Length: 5\r\n"
  14372. "Content-Length: 10\r\n"
  14373. "\r\n"
  14374. "hello";
  14375. std::string response;
  14376. ASSERT_TRUE(send_request(1, req, &response));
  14377. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14378. response.substr(0, response.find("\r\n")));
  14379. }
  14380. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14381. auto handled = false;
  14382. Server svr;
  14383. svr.Post("/test", [&](const Request &, Response &res) {
  14384. handled = true;
  14385. res.set_content("ok", "text/plain");
  14386. });
  14387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14388. auto se = detail::scope_exit([&] {
  14389. svr.stop();
  14390. t.join();
  14391. ASSERT_FALSE(svr.is_running());
  14392. ASSERT_TRUE(handled);
  14393. });
  14394. svr.wait_until_ready();
  14395. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14396. auto req = "POST /test HTTP/1.1\r\n"
  14397. "Content-Length: 5\r\n"
  14398. "Content-Length: 5\r\n"
  14399. "\r\n"
  14400. "hello";
  14401. std::string response;
  14402. ASSERT_TRUE(send_request(1, req, &response));
  14403. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14404. }
  14405. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14406. Server svr;
  14407. svr.Get("/", [](const Request &req, Response &res) {
  14408. EXPECT_EQ(2U, req.trailers.size());
  14409. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14410. // Denied
  14411. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14412. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14413. // Accepted
  14414. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14415. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14416. EXPECT_TRUE(req.has_trailer("X-World"));
  14417. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14418. res.set_content("ok", "text/plain");
  14419. });
  14420. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14421. auto se = detail::scope_exit([&] {
  14422. svr.stop();
  14423. t.join();
  14424. ASSERT_FALSE(svr.is_running());
  14425. });
  14426. svr.wait_until_ready();
  14427. const std::string req = "GET / HTTP/1.1\r\n"
  14428. "Transfer-Encoding: chunked\r\n"
  14429. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14430. "\r\n"
  14431. "0\r\n"
  14432. "Content-Length: 10\r\n"
  14433. "Host: internal.local\r\n"
  14434. "Content-Type: malicious/content\r\n"
  14435. "Cookie: any\r\n"
  14436. "Set-Cookie: any\r\n"
  14437. "X-Forwarded-For: attacker.com\r\n"
  14438. "X-Real-Ip: 1.1.1.1\r\n"
  14439. "X-Hello: hello\r\n"
  14440. "X-World: world\r\n"
  14441. "\r\n";
  14442. std::string res;
  14443. ASSERT_TRUE(send_request(1, req, &res));
  14444. }
  14445. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14446. // several field lines, and the combined value is what has to be parsed. A
  14447. // Trailer field split across lines therefore declares every name it lists;
  14448. // reading only the first line silently drops the trailers the later lines
  14449. // declare. The prohibited-trailer filter still applies to every line.
  14450. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14451. Server svr;
  14452. size_t observed_trailer_count = 0;
  14453. std::string observed_hello;
  14454. std::string observed_world;
  14455. bool observed_content_length = true;
  14456. svr.Get("/", [&](const Request &req, Response &res) {
  14457. observed_trailer_count = req.trailers.size();
  14458. observed_hello = req.get_trailer_value("X-Hello");
  14459. observed_world = req.get_trailer_value("X-World");
  14460. observed_content_length = req.has_trailer("Content-Length");
  14461. res.set_content("ok", "text/plain");
  14462. });
  14463. auto port = svr.bind_to_any_port(HOST);
  14464. thread t = thread([&]() { svr.listen_after_bind(); });
  14465. auto se = detail::scope_exit([&] {
  14466. svr.stop();
  14467. t.join();
  14468. ASSERT_FALSE(svr.is_running());
  14469. });
  14470. svr.wait_until_ready();
  14471. const std::string req = "GET / HTTP/1.1\r\n"
  14472. "Transfer-Encoding: chunked\r\n"
  14473. "Trailer: X-Hello\r\n"
  14474. "Trailer: X-World, Content-Length\r\n"
  14475. "\r\n"
  14476. "0\r\n"
  14477. "X-Hello: hello\r\n"
  14478. "X-World: world\r\n"
  14479. "Content-Length: 10\r\n"
  14480. "\r\n";
  14481. std::string res;
  14482. ASSERT_TRUE(send_request(1, req, &res, port));
  14483. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14484. // Accepted: both field lines contribute to the declared set
  14485. EXPECT_EQ(2U, observed_trailer_count);
  14486. EXPECT_EQ(observed_hello, "hello");
  14487. EXPECT_EQ(observed_world, "world");
  14488. // Denied: a prohibited name stays prohibited on a later field line
  14489. EXPECT_FALSE(observed_content_length);
  14490. }
  14491. // A direct client that is not listed in trusted_proxies must not be able to
  14492. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14493. // the peer address on the actual TCP connection determines whether the
  14494. // header is honored.
  14495. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14496. Server svr;
  14497. // Deliberately does NOT include the loopback address the test client
  14498. // actually connects from, so the direct connection is not a trusted proxy.
  14499. svr.set_trusted_proxies({"203.0.113.66"});
  14500. std::string observed_remote_addr;
  14501. svr.Get("/ip", [&](const Request &req, Response &res) {
  14502. observed_remote_addr = req.remote_addr;
  14503. res.set_content("ok", "text/plain");
  14504. });
  14505. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14506. auto se = detail::scope_exit([&] {
  14507. svr.stop();
  14508. t.join();
  14509. ASSERT_FALSE(svr.is_running());
  14510. });
  14511. svr.wait_until_ready();
  14512. Client cli(HOST, PORT);
  14513. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14515. EXPECT_EQ(StatusCode::OK_200, res->status);
  14516. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14517. // ignored entirely and the real connection-level address retained.
  14518. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14519. observed_remote_addr == "127.0.0.1");
  14520. }
  14521. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14522. Server svr;
  14523. std::string observed_remote_addr;
  14524. std::string observed_xff;
  14525. svr.Get("/ip", [&](const Request &req, Response &res) {
  14526. observed_remote_addr = req.remote_addr;
  14527. observed_xff = req.get_header_value("X-Forwarded-For");
  14528. res.set_content("ok", "text/plain");
  14529. });
  14530. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14531. auto se = detail::scope_exit([&] {
  14532. svr.stop();
  14533. t.join();
  14534. ASSERT_FALSE(svr.is_running());
  14535. });
  14536. svr.wait_until_ready();
  14537. Client cli(HOST, PORT);
  14538. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. EXPECT_EQ(StatusCode::OK_200, res->status);
  14541. EXPECT_EQ(observed_xff, "203.0.113.66");
  14542. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14543. observed_remote_addr == "127.0.0.1");
  14544. }
  14545. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14546. Server svr;
  14547. svr.set_trusted_proxies({"203.0.113.66"});
  14548. std::string observed_remote_addr;
  14549. std::string observed_xff;
  14550. svr.Get("/ip", [&](const Request &req, Response &res) {
  14551. observed_remote_addr = req.remote_addr;
  14552. observed_xff = req.get_header_value("X-Forwarded-For");
  14553. res.set_content("ok", "text/plain");
  14554. });
  14555. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14556. auto se = detail::scope_exit([&] {
  14557. svr.stop();
  14558. t.join();
  14559. ASSERT_FALSE(svr.is_running());
  14560. });
  14561. svr.wait_until_ready();
  14562. Client cli(HOST, PORT);
  14563. auto res = cli.Get("/ip");
  14564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14565. EXPECT_EQ(StatusCode::OK_200, res->status);
  14566. EXPECT_EQ(observed_xff, "");
  14567. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14568. observed_remote_addr == "127.0.0.1");
  14569. }
  14570. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14571. Server svr;
  14572. // Include the loopback address the test client actually connects from, so
  14573. // the direct connection itself is recognized as the trusted proxy hop.
  14574. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14575. std::string observed_remote_addr;
  14576. std::string observed_xff;
  14577. svr.Get("/ip", [&](const Request &req, Response &res) {
  14578. observed_remote_addr = req.remote_addr;
  14579. observed_xff = req.get_header_value("X-Forwarded-For");
  14580. res.set_content("ok", "text/plain");
  14581. });
  14582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14583. auto se = detail::scope_exit([&] {
  14584. svr.stop();
  14585. t.join();
  14586. ASSERT_FALSE(svr.is_running());
  14587. });
  14588. svr.wait_until_ready();
  14589. Client cli(HOST, PORT);
  14590. auto res = cli.Get(
  14591. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14593. EXPECT_EQ(StatusCode::OK_200, res->status);
  14594. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14595. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14596. }
  14597. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14598. Server svr;
  14599. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14600. std::string observed_remote_addr;
  14601. std::string observed_xff;
  14602. svr.Get("/ip", [&](const Request &req, Response &res) {
  14603. observed_remote_addr = req.remote_addr;
  14604. observed_xff = req.get_header_value("X-Forwarded-For");
  14605. res.set_content("ok", "text/plain");
  14606. });
  14607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14608. auto se = detail::scope_exit([&] {
  14609. svr.stop();
  14610. t.join();
  14611. ASSERT_FALSE(svr.is_running());
  14612. });
  14613. svr.wait_until_ready();
  14614. Client cli(HOST, PORT);
  14615. auto res = cli.Get(
  14616. "/ip",
  14617. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14619. EXPECT_EQ(StatusCode::OK_200, res->status);
  14620. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14621. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14622. }
  14623. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14624. Server svr;
  14625. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14626. std::string observed_remote_addr;
  14627. std::string observed_xff;
  14628. svr.Get("/ip", [&](const Request &req, Response &res) {
  14629. observed_remote_addr = req.remote_addr;
  14630. observed_xff = req.get_header_value("X-Forwarded-For");
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. ASSERT_FALSE(svr.is_running());
  14638. });
  14639. svr.wait_until_ready();
  14640. Client cli(HOST, PORT);
  14641. auto res = cli.Get(
  14642. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14644. EXPECT_EQ(StatusCode::OK_200, res->status);
  14645. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14646. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14647. // and must not be selected.
  14648. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14649. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14650. }
  14651. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14652. Server svr;
  14653. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14654. std::string observed_remote_addr;
  14655. svr.Get("/ip", [&](const Request &req, Response &res) {
  14656. observed_remote_addr = req.remote_addr;
  14657. res.set_content("ok", "text/plain");
  14658. });
  14659. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14660. auto se = detail::scope_exit([&] {
  14661. svr.stop();
  14662. t.join();
  14663. ASSERT_FALSE(svr.is_running());
  14664. });
  14665. svr.wait_until_ready();
  14666. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14667. // a forged address and the trusted proxy's own address; the forged value must
  14668. // not win over the address the trusted proxy actually recorded.
  14669. Client cli(HOST, PORT);
  14670. auto res = cli.Get(
  14671. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14673. EXPECT_EQ(StatusCode::OK_200, res->status);
  14674. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14675. }
  14676. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14677. Server svr;
  14678. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14679. std::string observed_remote_addr;
  14680. std::string observed_xff;
  14681. svr.Get("/ip", [&](const Request &req, Response &res) {
  14682. observed_remote_addr = req.remote_addr;
  14683. observed_xff = req.get_header_value("X-Forwarded-For");
  14684. res.set_content("ok", "text/plain");
  14685. });
  14686. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14687. auto se = detail::scope_exit([&] {
  14688. svr.stop();
  14689. t.join();
  14690. ASSERT_FALSE(svr.is_running());
  14691. });
  14692. svr.wait_until_ready();
  14693. Client cli(HOST, PORT);
  14694. auto res = cli.Get(
  14695. "/ip",
  14696. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14698. EXPECT_EQ(StatusCode::OK_200, res->status);
  14699. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14700. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14701. }
  14702. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14703. Server svr;
  14704. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14705. std::string observed_remote_addr;
  14706. std::string observed_xff;
  14707. svr.Get("/ip", [&](const Request &req, Response &res) {
  14708. observed_remote_addr = req.remote_addr;
  14709. observed_xff = req.get_header_value("X-Forwarded-For");
  14710. res.set_content("ok", "text/plain");
  14711. });
  14712. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14713. auto se = detail::scope_exit([&] {
  14714. svr.stop();
  14715. t.join();
  14716. ASSERT_FALSE(svr.is_running());
  14717. });
  14718. svr.wait_until_ready();
  14719. std::string raw_req =
  14720. "GET /ip HTTP/1.1\r\n"
  14721. "Host: localhost\r\n"
  14722. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14723. "Connection: close\r\n"
  14724. "\r\n";
  14725. std::string out;
  14726. ASSERT_TRUE(send_request(5, raw_req, &out));
  14727. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14728. // Header parser trims surrounding whitespace of the header value
  14729. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14730. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14731. }
  14732. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14733. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14734. // their own X-Forwarded-For as a separate field line rather than extending the
  14735. // one the client sent, so every occurrence has to be taken into account.
  14736. // Reading only the first one hands back the address the client chose.
  14737. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14738. Server svr;
  14739. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14740. std::string observed_remote_addr;
  14741. size_t observed_xff_count = 0;
  14742. svr.Get("/ip", [&](const Request &req, Response &res) {
  14743. observed_remote_addr = req.remote_addr;
  14744. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14745. res.set_content("ok", "text/plain");
  14746. });
  14747. auto port = svr.bind_to_any_port(HOST);
  14748. thread t = thread([&]() { svr.listen_after_bind(); });
  14749. auto se = detail::scope_exit([&] {
  14750. svr.stop();
  14751. t.join();
  14752. ASSERT_FALSE(svr.is_running());
  14753. });
  14754. svr.wait_until_ready();
  14755. // The client supplies the first field line; the trusted proxy appends the
  14756. // address it observed as a second one.
  14757. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14758. "Host: localhost\r\n"
  14759. "X-Forwarded-For: 1.2.3.4\r\n"
  14760. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14761. "Connection: close\r\n"
  14762. "\r\n";
  14763. std::string out;
  14764. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14765. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14766. EXPECT_EQ(observed_xff_count, 2U);
  14767. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14768. // The same chain spread over one field line per hop derives the same client
  14769. // address, i.e. the split and the comma-joined representations agree.
  14770. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14771. "Host: localhost\r\n"
  14772. "X-Forwarded-For: 1.2.3.4\r\n"
  14773. "X-Forwarded-For: 198.51.100.23\r\n"
  14774. "X-Forwarded-For: 192.0.2.45\r\n"
  14775. "Connection: close\r\n"
  14776. "\r\n";
  14777. out.clear();
  14778. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14779. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14780. EXPECT_EQ(observed_xff_count, 3U);
  14781. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14782. }
  14783. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14784. // crash the server (it used to call front() on an empty vector inside
  14785. // get_client_ip). The connection-level remote address must be retained instead.
  14786. static void run_malformed_xff_test(const std::string &xff_value) {
  14787. Server svr;
  14788. svr.set_trusted_proxies({"192.0.2.45"});
  14789. std::string observed_remote_addr;
  14790. svr.Get("/ip", [&](const Request &req, Response &res) {
  14791. observed_remote_addr = req.remote_addr;
  14792. res.set_content("ok", "text/plain");
  14793. });
  14794. int port = 0;
  14795. thread t = thread([&]() {
  14796. port = svr.bind_to_any_port(HOST);
  14797. svr.listen_after_bind();
  14798. });
  14799. auto se = detail::scope_exit([&] {
  14800. svr.stop();
  14801. t.join();
  14802. ASSERT_FALSE(svr.is_running());
  14803. });
  14804. svr.wait_until_ready();
  14805. Client cli(HOST, port);
  14806. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14808. EXPECT_EQ(StatusCode::OK_200, res->status);
  14809. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14810. observed_remote_addr == "127.0.0.1");
  14811. }
  14812. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14813. run_malformed_xff_test("");
  14814. }
  14815. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14816. run_malformed_xff_test(",");
  14817. }
  14818. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14819. run_malformed_xff_test(", , ,");
  14820. }
  14821. // The same rule applies to Accept: a request whose acceptable types are spread
  14822. // over several field lines must be negotiated against all of them.
  14823. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14824. // case-insensitive connection options. Comparing the whole field value against
  14825. // one option misses a client that sends several of them, and misses every
  14826. // casing but the one written in the comparison.
  14827. //
  14828. // Sends req, reads the response, then reuses the same socket for a second
  14829. // request to find out whether the server kept the connection.
  14830. static void probe_connection_reuse(int port, const std::string &req,
  14831. bool *announced_close, bool *reusable) {
  14832. auto error = Error::Success;
  14833. auto sock = detail::create_client_socket(
  14834. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14835. /*connection_timeout_sec=*/5, 0,
  14836. /*read_timeout_sec=*/1, 0,
  14837. /*write_timeout_sec=*/5, 0, std::string(), error);
  14838. ASSERT_NE(sock, INVALID_SOCKET);
  14839. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14840. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14841. "Host: localhost\r\n"
  14842. "Connection: close\r\n"
  14843. "\r\n";
  14844. std::string first_response;
  14845. std::string second_response;
  14846. detail::process_client_socket(
  14847. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14848. [&](Stream &strm) {
  14849. if (strm.write(req.data(), req.size()) !=
  14850. static_cast<ssize_t>(req.size())) {
  14851. return false;
  14852. }
  14853. char buf[512];
  14854. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14855. // Headers plus the two-byte body of the handler below
  14856. while (reader.getline()) {
  14857. first_response += reader.ptr();
  14858. if (first_response.find("ok") != std::string::npos) { break; }
  14859. }
  14860. if (strm.write(second.data(), second.size()) !=
  14861. static_cast<ssize_t>(second.size())) {
  14862. return true;
  14863. }
  14864. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14865. while (reader2.getline()) {
  14866. second_response += reader2.ptr();
  14867. if (second_response.find("ok") != std::string::npos) { break; }
  14868. }
  14869. return true;
  14870. });
  14871. *announced_close =
  14872. first_response.find("Connection: close") != std::string::npos;
  14873. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14874. }
  14875. class ConnectionTokenTest : public ::testing::Test {
  14876. protected:
  14877. void SetUp() override {
  14878. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14879. res.set_content("ok", "text/plain");
  14880. });
  14881. port_ = svr_.bind_to_any_port(HOST);
  14882. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14883. svr_.wait_until_ready();
  14884. }
  14885. void TearDown() override {
  14886. svr_.stop();
  14887. if (thread_.joinable()) { thread_.join(); }
  14888. }
  14889. Server svr_;
  14890. int port_ = 0;
  14891. thread thread_;
  14892. };
  14893. // "close" alongside another option still closes the connection, and the
  14894. // response says so rather than leaving the peer to discover it.
  14895. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14896. bool announced_close = false;
  14897. bool reusable = true;
  14898. probe_connection_reuse(port_,
  14899. "GET /keepalive HTTP/1.1\r\n"
  14900. "Host: localhost\r\n"
  14901. "Connection: keep-alive, close\r\n"
  14902. "\r\n",
  14903. &announced_close, &reusable);
  14904. EXPECT_TRUE(announced_close);
  14905. EXPECT_FALSE(reusable);
  14906. }
  14907. // "close" split over two field lines is the same list, so it is honored too.
  14908. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14909. bool announced_close = false;
  14910. bool reusable = true;
  14911. probe_connection_reuse(port_,
  14912. "GET /keepalive HTTP/1.1\r\n"
  14913. "Host: localhost\r\n"
  14914. "Connection: keep-alive\r\n"
  14915. "Connection: close\r\n"
  14916. "\r\n",
  14917. &announced_close, &reusable);
  14918. EXPECT_TRUE(announced_close);
  14919. EXPECT_FALSE(reusable);
  14920. }
  14921. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14922. // keep-alive in the spelling everyone actually sends keeps its connection.
  14923. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14924. bool announced_close = false;
  14925. bool reusable = false;
  14926. probe_connection_reuse(port_,
  14927. "GET /keepalive HTTP/1.0\r\n"
  14928. "Host: localhost\r\n"
  14929. "Connection: keep-alive\r\n"
  14930. "\r\n",
  14931. &announced_close, &reusable);
  14932. EXPECT_FALSE(announced_close);
  14933. EXPECT_TRUE(reusable);
  14934. }
  14935. // A token the value merely contains is not the token itself.
  14936. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14937. bool announced_close = false;
  14938. bool reusable = false;
  14939. probe_connection_reuse(port_,
  14940. "GET /keepalive HTTP/1.1\r\n"
  14941. "Host: localhost\r\n"
  14942. "Connection: notclose\r\n"
  14943. "\r\n",
  14944. &announced_close, &reusable);
  14945. EXPECT_FALSE(announced_close);
  14946. EXPECT_TRUE(reusable);
  14947. }
  14948. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14949. Server svr;
  14950. std::vector<std::string> observed_types;
  14951. svr.Get("/", [&](const Request &req, Response &res) {
  14952. observed_types = req.accept_content_types;
  14953. res.set_content("ok", "text/plain");
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. thread t = thread([&]() { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. ASSERT_FALSE(svr.is_running());
  14961. });
  14962. svr.wait_until_ready();
  14963. Client cli(HOST, port);
  14964. Headers headers;
  14965. headers.emplace("Accept", "text/plain;q=0.5");
  14966. headers.emplace("Accept", "application/json");
  14967. auto res = cli.Get("/", headers);
  14968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14969. EXPECT_EQ(StatusCode::OK_200, res->status);
  14970. // Sorted by q-value, so the second field line's type comes first
  14971. ASSERT_EQ(2U, observed_types.size());
  14972. EXPECT_EQ("application/json", observed_types[0]);
  14973. EXPECT_EQ("text/plain", observed_types[1]);
  14974. }
  14975. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14976. // empty field line must not contribute a bare comma to the combined value.
  14977. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14978. // turn a legal request into 400 Bad Request.
  14979. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14980. Server svr;
  14981. std::vector<std::string> observed_types;
  14982. svr.Get("/", [&](const Request &req, Response &res) {
  14983. observed_types = req.accept_content_types;
  14984. res.set_content("ok", "text/plain");
  14985. });
  14986. auto port = svr.bind_to_any_port(HOST);
  14987. thread t = thread([&]() { svr.listen_after_bind(); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. ASSERT_FALSE(svr.is_running());
  14992. });
  14993. svr.wait_until_ready();
  14994. // Empty first field line, then a real one
  14995. std::string raw_req = "GET / HTTP/1.1\r\n"
  14996. "Host: localhost\r\n"
  14997. "Accept:\r\n"
  14998. "Accept: application/json\r\n"
  14999. "Connection: close\r\n"
  15000. "\r\n";
  15001. std::string out;
  15002. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15003. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15004. ASSERT_EQ(1U, observed_types.size());
  15005. EXPECT_EQ("application/json", observed_types[0]);
  15006. }
  15007. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15008. // An encoding offered on a later Accept-Encoding field line is still offered.
  15009. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15010. Server svr;
  15011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15012. res.set_content(std::string(1024, 'x'), "text/plain");
  15013. });
  15014. auto port = svr.bind_to_any_port(HOST);
  15015. thread t = thread([&]() { svr.listen_after_bind(); });
  15016. auto se = detail::scope_exit([&] {
  15017. svr.stop();
  15018. t.join();
  15019. ASSERT_FALSE(svr.is_running());
  15020. });
  15021. svr.wait_until_ready();
  15022. Client cli(HOST, port);
  15023. cli.set_decompress(false);
  15024. Headers headers;
  15025. headers.emplace("Accept-Encoding", "identity");
  15026. headers.emplace("Accept-Encoding", "gzip");
  15027. auto res = cli.Get("/", headers);
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::OK_200, res->status);
  15030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15031. }
  15032. #endif
  15033. #ifndef _WIN32
  15034. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15035. Server svr;
  15036. svr.Post("/post", [&](const Request &req, Response &res) {
  15037. res.set_content(req.body, "text/plain");
  15038. });
  15039. svr.Put("/put", [&](const Request &req, Response &res) {
  15040. res.set_content(req.body, "text/plain");
  15041. });
  15042. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15043. res.set_content(req.body, "text/plain");
  15044. });
  15045. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15046. res.set_content(req.body, "text/plain");
  15047. });
  15048. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15049. auto se = detail::scope_exit([&] {
  15050. svr.stop();
  15051. t.join();
  15052. ASSERT_FALSE(svr.is_running());
  15053. });
  15054. svr.wait_until_ready();
  15055. std::string resp;
  15056. // POST without Content-Length
  15057. ASSERT_TRUE(send_request(5,
  15058. "POST /post HTTP/1.1\r\n"
  15059. "Host: localhost\r\n"
  15060. "Connection: close\r\n"
  15061. "\r\n",
  15062. &resp));
  15063. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15064. // PUT without Content-Length
  15065. resp.clear();
  15066. ASSERT_TRUE(send_request(5,
  15067. "PUT /put HTTP/1.1\r\n"
  15068. "Host: localhost\r\n"
  15069. "Connection: close\r\n"
  15070. "\r\n",
  15071. &resp));
  15072. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15073. // PATCH without Content-Length
  15074. resp.clear();
  15075. ASSERT_TRUE(send_request(5,
  15076. "PATCH /patch HTTP/1.1\r\n"
  15077. "Host: localhost\r\n"
  15078. "Connection: close\r\n"
  15079. "\r\n",
  15080. &resp));
  15081. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15082. // DELETE without Content-Length
  15083. resp.clear();
  15084. ASSERT_TRUE(send_request(5,
  15085. "DELETE /delete HTTP/1.1\r\n"
  15086. "Host: localhost\r\n"
  15087. "Connection: close\r\n"
  15088. "\r\n",
  15089. &resp));
  15090. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15091. }
  15092. #endif
  15093. //==============================================================================
  15094. // open_stream() Tests
  15095. //==============================================================================
  15096. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15097. std::string result;
  15098. char buf[8192];
  15099. ssize_t n;
  15100. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15101. result.append(buf, static_cast<size_t>(n));
  15102. }
  15103. return result;
  15104. }
  15105. // Mock stream for unit tests
  15106. class MockStream : public Stream {
  15107. public:
  15108. std::string data;
  15109. size_t pos = 0;
  15110. ssize_t error_after = -1; // -1 = no error
  15111. explicit MockStream(const std::string &d, ssize_t err = -1)
  15112. : data(d), error_after(err) {}
  15113. bool is_readable() const override { return true; }
  15114. bool wait_readable() const override { return true; }
  15115. bool wait_writable() const override { return true; }
  15116. ssize_t read(char *ptr, size_t size) override {
  15117. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15118. if (pos >= data.size()) return 0;
  15119. size_t limit =
  15120. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15121. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15122. std::memcpy(ptr, data.data() + pos, to_read);
  15123. pos += to_read;
  15124. return static_cast<ssize_t>(to_read);
  15125. }
  15126. ssize_t write(const char *, size_t) override { return -1; }
  15127. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15128. ip = "127.0.0.1";
  15129. port = 0;
  15130. }
  15131. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15132. ip = "127.0.0.1";
  15133. port = 0;
  15134. }
  15135. socket_t socket() const override { return INVALID_SOCKET; }
  15136. time_t duration() const override { return 0; }
  15137. };
  15138. TEST(StreamHandleTest, Basic) {
  15139. ClientImpl::StreamHandle handle;
  15140. EXPECT_FALSE(handle.is_valid());
  15141. handle.response = detail::make_unique<Response>();
  15142. handle.error = Error::Connection;
  15143. EXPECT_FALSE(handle.is_valid());
  15144. handle.error = Error::Success;
  15145. EXPECT_TRUE(handle.is_valid());
  15146. }
  15147. TEST(BodyReaderTest, Basic) {
  15148. MockStream stream("Hello, World!");
  15149. detail::BodyReader reader;
  15150. reader.stream = &stream;
  15151. reader.content_length = 13;
  15152. char buf[32];
  15153. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15154. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15155. EXPECT_TRUE(reader.eof);
  15156. }
  15157. TEST(BodyReaderTest, NoStream) {
  15158. detail::BodyReader reader;
  15159. char buf[32];
  15160. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15161. EXPECT_EQ(Error::Connection, reader.last_error);
  15162. }
  15163. TEST(BodyReaderTest, Error) {
  15164. MockStream stream("Hello, World!", 5);
  15165. detail::BodyReader reader;
  15166. reader.stream = &stream;
  15167. reader.content_length = 13;
  15168. char buf[32];
  15169. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15170. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15171. EXPECT_EQ(Error::Read, reader.last_error);
  15172. }
  15173. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15174. // Mock-based StreamHandle tests relying on private internals are removed.
  15175. class OpenStreamTest : public ::testing::Test {
  15176. protected:
  15177. void SetUp() override {
  15178. svr_.Get("/hello", [](const Request &, Response &res) {
  15179. res.set_content("Hello World!", "text/plain");
  15180. });
  15181. svr_.Get("/large", [](const Request &, Response &res) {
  15182. res.set_content(std::string(10000, 'X'), "text/plain");
  15183. });
  15184. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15185. res.set_content("Hello World!", "image/jpeg");
  15186. res.set_header("Content-Encoding", "UTF-8");
  15187. });
  15188. svr_.Get("/chunked", [](const Request &, Response &res) {
  15189. res.set_chunked_content_provider("text/plain",
  15190. [](size_t offset, DataSink &sink) {
  15191. if (offset < 15) {
  15192. sink.write("chunk", 5);
  15193. return true;
  15194. }
  15195. sink.done();
  15196. return true;
  15197. });
  15198. });
  15199. svr_.Get("/compressible", [](const Request &, Response &res) {
  15200. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15201. DataSink &sink) {
  15202. if (offset < 100 * 1024) {
  15203. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15204. sink.write(chunk.data(), chunk.size());
  15205. return true;
  15206. }
  15207. sink.done();
  15208. return true;
  15209. });
  15210. });
  15211. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15212. [](const Request & /*req*/, Response &res) {
  15213. auto i = new int(0);
  15214. res.set_header("Trailer", "Content-Length, X-Allowed");
  15215. res.set_chunked_content_provider(
  15216. "text/plain",
  15217. [i](size_t /*offset*/, DataSink &sink) {
  15218. switch (*i) {
  15219. case 0: sink.os << "123"; break;
  15220. case 1: sink.os << "456"; break;
  15221. case 2: sink.os << "789"; break;
  15222. case 3: {
  15223. sink.done_with_trailer(
  15224. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15225. } break;
  15226. }
  15227. (*i)++;
  15228. return true;
  15229. },
  15230. [i](bool success) {
  15231. EXPECT_TRUE(success);
  15232. delete i;
  15233. });
  15234. });
  15235. // Echo headers endpoint for header-related tests
  15236. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15237. std::string body;
  15238. for (const auto &h : req.headers) {
  15239. body.append(h.first);
  15240. body.push_back(':');
  15241. body.append(h.second);
  15242. body.push_back('\n');
  15243. }
  15244. res.set_content(body, "text/plain");
  15245. });
  15246. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15247. std::string body;
  15248. for (const auto &h : req.headers) {
  15249. body.append(h.first);
  15250. body.push_back(':');
  15251. body.append(h.second);
  15252. body.push_back('\n');
  15253. }
  15254. res.set_content(body, "text/plain");
  15255. });
  15256. port_ = svr_.bind_to_any_port("127.0.0.1");
  15257. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15258. svr_.wait_until_ready();
  15259. }
  15260. void TearDown() override {
  15261. svr_.stop();
  15262. if (thread_.joinable()) thread_.join();
  15263. }
  15264. Server svr_;
  15265. std::thread thread_;
  15266. int port_ = 0;
  15267. };
  15268. TEST_F(OpenStreamTest, Basic) {
  15269. Client cli("127.0.0.1", port_);
  15270. auto handle = cli.open_stream("GET", "/hello");
  15271. EXPECT_TRUE(handle.is_valid());
  15272. EXPECT_EQ("Hello World!", read_all(handle));
  15273. }
  15274. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15275. Client cli("127.0.0.1", port_);
  15276. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15277. ASSERT_TRUE(handle.is_valid());
  15278. EXPECT_EQ("Hello World!", read_all(handle));
  15279. }
  15280. TEST_F(OpenStreamTest, SmallBuffer) {
  15281. Client cli("127.0.0.1", port_);
  15282. auto handle = cli.open_stream("GET", "/hello");
  15283. std::string result;
  15284. char buf[4];
  15285. ssize_t n;
  15286. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15287. result.append(buf, static_cast<size_t>(n));
  15288. EXPECT_EQ("Hello World!", result);
  15289. }
  15290. TEST_F(OpenStreamTest, DefaultHeaders) {
  15291. Client cli("127.0.0.1", port_);
  15292. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15293. {
  15294. auto handle = cli.open_stream("GET", "/echo-headers");
  15295. ASSERT_TRUE(handle.is_valid());
  15296. auto body = read_all(handle);
  15297. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15298. std::string::npos);
  15299. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15300. std::string::npos);
  15301. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15302. }
  15303. // open_stream POST with body and no explicit content_type should NOT add
  15304. // text/plain Content-Type (behavior differs from non-streaming path), but
  15305. // should include Content-Length
  15306. {
  15307. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15308. ASSERT_TRUE(handle.is_valid());
  15309. auto body = read_all(handle);
  15310. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15311. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15312. }
  15313. // open_stream POST with explicit Content-Type should preserve it
  15314. {
  15315. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15316. {{"Content-Type", "application/custom"}},
  15317. "{}", "application/custom");
  15318. ASSERT_TRUE(handle.is_valid());
  15319. auto body = read_all(handle);
  15320. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15321. }
  15322. // User-specified User-Agent must not be overwritten for stream API
  15323. {
  15324. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15325. {{"User-Agent", "MyAgent/1.2"}});
  15326. ASSERT_TRUE(handle.is_valid());
  15327. auto body = read_all(handle);
  15328. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15329. }
  15330. }
  15331. TEST_F(OpenStreamTest, Large) {
  15332. Client cli("127.0.0.1", port_);
  15333. auto handle = cli.open_stream("GET", "/large");
  15334. EXPECT_EQ(10000u, read_all(handle).size());
  15335. }
  15336. TEST_F(OpenStreamTest, ConnectionError) {
  15337. Client cli("127.0.0.1", 9999);
  15338. auto handle = cli.open_stream("GET", "/hello");
  15339. EXPECT_FALSE(handle.is_valid());
  15340. }
  15341. TEST_F(OpenStreamTest, Chunked) {
  15342. Client cli("127.0.0.1", port_);
  15343. auto handle = cli.open_stream("GET", "/chunked");
  15344. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15345. "Transfer-Encoding") == "chunked");
  15346. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15347. }
  15348. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15349. Client cli("127.0.0.1", port_);
  15350. auto handle =
  15351. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15352. ASSERT_TRUE(handle.is_valid());
  15353. // Consume body to allow trailers to be received/parsed
  15354. auto body = read_all(handle);
  15355. // Explicitly parse trailers (ensure trailers are available for assertion)
  15356. handle.parse_trailers_if_needed();
  15357. EXPECT_EQ(std::string("123456789"), body);
  15358. // The response should include a Trailer header declaring both names
  15359. ASSERT_TRUE(handle.response);
  15360. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15361. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15362. handle.response->get_header_value("Trailer"));
  15363. // Prohibited trailer must not be present
  15364. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15365. // Allowed trailer should be present
  15366. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15367. EXPECT_EQ(std::string("yes"),
  15368. handle.response->get_trailer_value("X-Allowed"));
  15369. // Verify trailers are NOT present as regular headers
  15370. EXPECT_EQ(std::string(""),
  15371. handle.response->get_header_value("Content-Length"));
  15372. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15373. }
  15374. static std::thread serve_single_response(std::promise<int> &port_promise,
  15375. const std::string &response) {
  15376. return std::thread([&port_promise, response] {
  15377. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15378. default_socket_options(srv);
  15379. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15380. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15381. sockaddr_in addr{};
  15382. addr.sin_family = AF_INET;
  15383. addr.sin_port = htons(0); // Let OS assign a free port
  15384. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15385. int opt = 1;
  15386. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15387. #ifdef _WIN32
  15388. reinterpret_cast<const char *>(&opt),
  15389. #else
  15390. &opt,
  15391. #endif
  15392. sizeof(opt));
  15393. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15394. ::listen(srv, 1) != 0) {
  15395. port_promise.set_value(-1);
  15396. detail::close_socket(srv);
  15397. return;
  15398. }
  15399. socklen_t addr_len = sizeof(addr);
  15400. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15401. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15402. sockaddr_in cli_addr{};
  15403. socklen_t cli_len = sizeof(cli_addr);
  15404. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15405. if (cli != INVALID_SOCKET) {
  15406. // Read the complete HTTP request (until the blank line that terminates
  15407. // headers) before sending the response. If the server closes the socket
  15408. // while the client's request data is still unread in the kernel receive
  15409. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15410. // connection on both sides: it discards the client's receive buffer
  15411. // (which already holds our response) and causes any in-progress write on
  15412. // the client to fail with ECONNRESET. Reading all request data first
  15413. // ensures close() emits a graceful FIN.
  15414. {
  15415. char rbuf[256];
  15416. std::string req;
  15417. while (req.find("\r\n\r\n") == std::string::npos) {
  15418. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15419. if (n <= 0) { break; }
  15420. req.append(rbuf, static_cast<size_t>(n));
  15421. }
  15422. }
  15423. ::send(cli,
  15424. #ifdef _WIN32
  15425. static_cast<const char *>(response.c_str()),
  15426. static_cast<int>(response.size()),
  15427. #else
  15428. response.c_str(), response.size(),
  15429. #endif
  15430. 0);
  15431. detail::close_socket(cli);
  15432. }
  15433. detail::close_socket(srv);
  15434. });
  15435. }
  15436. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15437. #ifndef _WIN32
  15438. signal(SIGPIPE, SIG_IGN);
  15439. #endif
  15440. std::promise<int> port_promise;
  15441. auto port_future = port_promise.get_future();
  15442. auto server_thread =
  15443. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15444. "Content-Type: text/plain\r\n"
  15445. "Content-Length: not-a-number\r\n"
  15446. "Connection: close\r\n"
  15447. "\r\n"
  15448. "hello");
  15449. auto port = port_future.get();
  15450. ASSERT_GT(port, 0);
  15451. Client cli("127.0.0.1", port);
  15452. auto handle = cli.open_stream("GET", "/");
  15453. EXPECT_FALSE(handle.is_valid());
  15454. server_thread.join();
  15455. }
  15456. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15457. #ifndef _WIN32
  15458. signal(SIGPIPE, SIG_IGN);
  15459. #endif
  15460. std::promise<int> port_promise;
  15461. auto port_future = port_promise.get_future();
  15462. auto server_thread = serve_single_response(
  15463. port_promise, "HTTP/1.1 200 OK\r\n"
  15464. "Content-Type: text/plain\r\n"
  15465. "Content-Length: 99999999999999999999999999\r\n"
  15466. "Connection: close\r\n"
  15467. "\r\n"
  15468. "hello");
  15469. auto port = port_future.get();
  15470. ASSERT_GT(port, 0);
  15471. // Historically std::stoull would throw std::out_of_range here and crash
  15472. // the process, then parsing silently clamped to a bogus framing length and
  15473. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15474. // so the stream fails to open, matching the not-a-number case above. The
  15475. // process still must NOT terminate.
  15476. Client cli("127.0.0.1", port);
  15477. auto handle = cli.open_stream("GET", "/");
  15478. EXPECT_FALSE(handle.is_valid());
  15479. server_thread.join();
  15480. }
  15481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15482. TEST_F(OpenStreamTest, Gzip) {
  15483. Client cli("127.0.0.1", port_);
  15484. auto handle = cli.open_stream("GET", "/compressible", {},
  15485. {{"Accept-Encoding", "gzip"}});
  15486. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15487. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15488. }
  15489. #endif
  15490. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15491. TEST_F(OpenStreamTest, Brotli) {
  15492. Client cli("127.0.0.1", port_);
  15493. auto handle =
  15494. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15495. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15496. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15497. }
  15498. #endif
  15499. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15500. TEST_F(OpenStreamTest, Zstd) {
  15501. Client cli("127.0.0.1", port_);
  15502. auto handle = cli.open_stream("GET", "/compressible", {},
  15503. {{"Accept-Encoding", "zstd"}});
  15504. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15505. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15506. }
  15507. #endif
  15508. #ifdef CPPHTTPLIB_SSL_ENABLED
  15509. class SSLOpenStreamTest : public ::testing::Test {
  15510. protected:
  15511. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15512. void SetUp() override {
  15513. svr_.Get("/hello", [](const Request &, Response &res) {
  15514. res.set_content("Hello SSL World!", "text/plain");
  15515. });
  15516. svr_.Get("/chunked", [](const Request &, Response &res) {
  15517. res.set_chunked_content_provider("text/plain",
  15518. [](size_t offset, DataSink &sink) {
  15519. if (offset < 15) {
  15520. sink.write("chunk", 5);
  15521. return true;
  15522. }
  15523. sink.done();
  15524. return true;
  15525. });
  15526. });
  15527. svr_.Post("/echo", [](const Request &req, Response &res) {
  15528. res.set_content(req.body, req.get_header_value("Content-Type"));
  15529. });
  15530. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15531. std::string body = req.body;
  15532. res.set_chunked_content_provider(
  15533. "text/plain", [body](size_t offset, DataSink &sink) {
  15534. if (offset < body.size()) {
  15535. sink.write(body.data() + offset, body.size() - offset);
  15536. }
  15537. sink.done();
  15538. return true;
  15539. });
  15540. });
  15541. port_ = svr_.bind_to_any_port("127.0.0.1");
  15542. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15543. svr_.wait_until_ready();
  15544. }
  15545. void TearDown() override {
  15546. svr_.stop();
  15547. if (thread_.joinable()) thread_.join();
  15548. }
  15549. SSLServer svr_;
  15550. std::thread thread_;
  15551. int port_ = 0;
  15552. };
  15553. TEST_F(SSLOpenStreamTest, Basic) {
  15554. SSLClient cli("127.0.0.1", port_);
  15555. cli.enable_server_certificate_verification(false);
  15556. auto handle = cli.open_stream("GET", "/hello");
  15557. ASSERT_TRUE(handle.is_valid());
  15558. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15559. }
  15560. TEST_F(SSLOpenStreamTest, Chunked) {
  15561. SSLClient cli("127.0.0.1", port_);
  15562. cli.enable_server_certificate_verification(false);
  15563. auto handle = cli.open_stream("GET", "/chunked");
  15564. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15565. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15566. "Transfer-Encoding") == "chunked");
  15567. auto body = read_all(handle);
  15568. EXPECT_EQ("chunkchunkchunk", body);
  15569. }
  15570. TEST_F(SSLOpenStreamTest, Post) {
  15571. SSLClient cli("127.0.0.1", port_);
  15572. cli.enable_server_certificate_verification(false);
  15573. auto handle =
  15574. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15575. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15576. EXPECT_EQ(200, handle.response->status);
  15577. auto body = read_all(handle);
  15578. EXPECT_EQ("Hello SSL POST", body);
  15579. }
  15580. TEST_F(SSLOpenStreamTest, PostChunked) {
  15581. SSLClient cli("127.0.0.1", port_);
  15582. cli.enable_server_certificate_verification(false);
  15583. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15584. "Chunked SSL Data", "text/plain");
  15585. ASSERT_TRUE(handle.is_valid());
  15586. EXPECT_EQ(200, handle.response->status);
  15587. auto body = read_all(handle);
  15588. EXPECT_EQ("Chunked SSL Data", body);
  15589. }
  15590. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15591. // Content-Length is terminated by the server closing the connection. When the
  15592. // SSL peer sends a close_notify after the body, the client must treat it as a
  15593. // clean EOF and return a successful response rather than an error.
  15594. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15596. ASSERT_TRUE(svr.is_valid());
  15597. svr.set_keep_alive_max_count(1);
  15598. const std::string expected_body = "Hello from connection-close response!";
  15599. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15600. res.set_content_provider("text/plain",
  15601. [&](size_t offset, DataSink &sink) -> bool {
  15602. if (offset < expected_body.size()) {
  15603. sink.write(expected_body.data() + offset,
  15604. expected_body.size() - offset);
  15605. }
  15606. sink.done();
  15607. return true;
  15608. });
  15609. });
  15610. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15611. auto se = detail::scope_exit([&] {
  15612. svr.stop();
  15613. listen_thread.join();
  15614. ASSERT_FALSE(svr.is_running());
  15615. });
  15616. svr.wait_until_ready();
  15617. SSLClient cli(HOST, PORT);
  15618. cli.enable_server_certificate_verification(false);
  15619. auto res = cli.Get("/no-content-length");
  15620. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15621. EXPECT_EQ(StatusCode::OK_200, res->status);
  15622. EXPECT_EQ(expected_body, res->body);
  15623. }
  15624. #endif // CPPHTTPLIB_SSL_ENABLED
  15625. //==============================================================================
  15626. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15627. // results for various scenarios.
  15628. //==============================================================================
  15629. TEST(ParityTest, GetVsOpenStream) {
  15630. Server svr;
  15631. const std::string path = "/parity";
  15632. const std::string content = "Parity test content: hello world";
  15633. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15634. res.set_content(content, "text/plain");
  15635. });
  15636. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15637. auto se = detail::scope_exit([&] {
  15638. svr.stop();
  15639. t.join();
  15640. ASSERT_FALSE(svr.is_running());
  15641. });
  15642. svr.wait_until_ready();
  15643. Client cli(HOST, PORT);
  15644. // Non-stream path
  15645. auto r1 = cli.Get(path);
  15646. ASSERT_TRUE(r1);
  15647. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15648. // Stream path
  15649. auto h = cli.open_stream("GET", path);
  15650. ASSERT_TRUE(h.is_valid());
  15651. EXPECT_EQ(r1->body, read_all(h));
  15652. }
  15653. // Helper to compress data with provided compressor type T
  15654. template <typename Compressor>
  15655. static std::string compress_payload_for_parity(const std::string &in) {
  15656. std::string out;
  15657. Compressor compressor;
  15658. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15659. [&](const char *data, size_t n) {
  15660. out.append(data, n);
  15661. return true;
  15662. });
  15663. EXPECT_TRUE(ok);
  15664. return out;
  15665. }
  15666. // Helper function for compression parity tests
  15667. template <typename Compressor>
  15668. static void test_compression_parity(const std::string &original,
  15669. const std::string &path,
  15670. const std::string &encoding) {
  15671. const std::string compressed =
  15672. compress_payload_for_parity<Compressor>(original);
  15673. Server svr;
  15674. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15675. res.set_content(compressed, "application/octet-stream");
  15676. res.set_header("Content-Encoding", encoding);
  15677. });
  15678. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15679. auto se = detail::scope_exit([&] {
  15680. svr.stop();
  15681. t.join();
  15682. ASSERT_FALSE(svr.is_running());
  15683. });
  15684. svr.wait_until_ready();
  15685. Client cli(HOST, PORT);
  15686. // Non-streaming
  15687. {
  15688. auto res = cli.Get(path);
  15689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15690. EXPECT_EQ(StatusCode::OK_200, res->status);
  15691. EXPECT_EQ(original, res->body);
  15692. }
  15693. // Streaming
  15694. {
  15695. auto h = cli.open_stream("GET", path);
  15696. ASSERT_TRUE(h.is_valid());
  15697. EXPECT_EQ(original, read_all(h));
  15698. }
  15699. }
  15700. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15701. TEST(ParityTest, Gzip) {
  15702. test_compression_parity<detail::gzip_compressor>(
  15703. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15704. }
  15705. #endif
  15706. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15707. TEST(ParityTest, Brotli) {
  15708. test_compression_parity<detail::brotli_compressor>(
  15709. "Hello, brotli parity test payload", "/parity-br", "br");
  15710. }
  15711. #endif
  15712. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15713. TEST(ParityTest, Zstd) {
  15714. test_compression_parity<detail::zstd_compressor>(
  15715. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15716. }
  15717. #endif
  15718. //==============================================================================
  15719. // New Stream API Tests
  15720. //==============================================================================
  15721. inline std::string read_body(httplib::stream::Result &result) {
  15722. std::string body;
  15723. while (result.next()) {
  15724. body.append(result.data(), result.size());
  15725. }
  15726. return body;
  15727. }
  15728. TEST(ClientConnectionTest, Basic) {
  15729. httplib::ClientConnection conn;
  15730. EXPECT_FALSE(conn.is_open());
  15731. conn.sock = 1;
  15732. EXPECT_TRUE(conn.is_open());
  15733. httplib::ClientConnection conn2(std::move(conn));
  15734. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15735. conn2.sock = INVALID_SOCKET;
  15736. }
  15737. // Unified test server for all stream::* tests
  15738. class StreamApiTest : public ::testing::Test {
  15739. protected:
  15740. void SetUp() override {
  15741. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15742. res.set_content("Hello World!", "text/plain");
  15743. });
  15744. svr_.Get("/echo-params",
  15745. [](const httplib::Request &req, httplib::Response &res) {
  15746. std::string r;
  15747. for (const auto &p : req.params) {
  15748. if (!r.empty()) r += "&";
  15749. r += p.first + "=" + p.second;
  15750. }
  15751. res.set_content(r, "text/plain");
  15752. });
  15753. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15754. res.set_content(req.body, req.get_header_value("Content-Type"));
  15755. });
  15756. svr_.Post("/echo-headers",
  15757. [](const httplib::Request &req, httplib::Response &res) {
  15758. std::string r;
  15759. for (const auto &h : req.headers)
  15760. r += h.first + ": " + h.second + "\n";
  15761. res.set_content(r, "text/plain");
  15762. });
  15763. svr_.Post("/echo-params",
  15764. [](const httplib::Request &req, httplib::Response &res) {
  15765. std::string r = "params:";
  15766. for (const auto &p : req.params)
  15767. r += p.first + "=" + p.second + ";";
  15768. res.set_content(r + " body:" + req.body, "text/plain");
  15769. });
  15770. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15771. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15772. });
  15773. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15774. res.set_content("PUT:" + req.body, "text/plain");
  15775. });
  15776. svr_.Patch("/echo",
  15777. [](const httplib::Request &req, httplib::Response &res) {
  15778. res.set_content("PATCH:" + req.body, "text/plain");
  15779. });
  15780. svr_.Delete(
  15781. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15782. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15783. "text/plain");
  15784. });
  15785. svr_.Get("/head-test",
  15786. [](const httplib::Request &, httplib::Response &res) {
  15787. res.set_content("body for HEAD", "text/plain");
  15788. });
  15789. svr_.Options("/options",
  15790. [](const httplib::Request &, httplib::Response &res) {
  15791. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15792. });
  15793. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15794. svr_.wait_until_ready();
  15795. }
  15796. void TearDown() override {
  15797. svr_.stop();
  15798. if (thread_.joinable()) thread_.join();
  15799. }
  15800. httplib::Server svr_;
  15801. std::thread thread_;
  15802. };
  15803. // stream::Get tests
  15804. TEST_F(StreamApiTest, GetBasic) {
  15805. httplib::Client cli(HOST, PORT);
  15806. auto result = httplib::stream::Get(cli, "/hello");
  15807. ASSERT_TRUE(result.is_valid());
  15808. EXPECT_EQ(200, result.status());
  15809. EXPECT_EQ("Hello World!", read_body(result));
  15810. }
  15811. TEST_F(StreamApiTest, GetWithParams) {
  15812. httplib::Client cli(HOST, PORT);
  15813. httplib::Params params{{"foo", "bar"}};
  15814. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15815. ASSERT_TRUE(result.is_valid());
  15816. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15817. }
  15818. TEST_F(StreamApiTest, GetConnectionError) {
  15819. httplib::Client cli(HOST, 9999);
  15820. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15821. }
  15822. TEST_F(StreamApiTest, Get404) {
  15823. httplib::Client cli(HOST, PORT);
  15824. auto result = httplib::stream::Get(cli, "/nonexistent");
  15825. EXPECT_TRUE(result.is_valid());
  15826. EXPECT_EQ(404, result.status());
  15827. }
  15828. // stream::Post tests
  15829. TEST_F(StreamApiTest, PostBasic) {
  15830. httplib::Client cli(HOST, PORT);
  15831. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15832. "application/json");
  15833. ASSERT_TRUE(result.is_valid());
  15834. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15835. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15836. }
  15837. TEST_F(StreamApiTest, PostWithHeaders) {
  15838. httplib::Client cli(HOST, PORT);
  15839. httplib::Headers headers{{"X-Custom", "value"}};
  15840. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15841. "text/plain");
  15842. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15843. }
  15844. TEST_F(StreamApiTest, PostWithParams) {
  15845. httplib::Client cli(HOST, PORT);
  15846. httplib::Params params{{"k", "v"}};
  15847. auto result =
  15848. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15849. auto body = read_body(result);
  15850. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15851. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15852. }
  15853. TEST_F(StreamApiTest, PostLarge) {
  15854. httplib::Client cli(HOST, PORT);
  15855. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15856. size_t total = 0;
  15857. while (result.next()) {
  15858. total += result.size();
  15859. }
  15860. EXPECT_EQ(100u * 1024u, total);
  15861. }
  15862. // stream::Put/Patch tests
  15863. TEST_F(StreamApiTest, PutAndPatch) {
  15864. httplib::Client cli(HOST, PORT);
  15865. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15866. EXPECT_EQ("PUT:test", read_body(put));
  15867. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15868. EXPECT_EQ("PATCH:test", read_body(patch));
  15869. }
  15870. // stream::Delete tests
  15871. TEST_F(StreamApiTest, Delete) {
  15872. httplib::Client cli(HOST, PORT);
  15873. auto del1 = httplib::stream::Delete(cli, "/resource");
  15874. EXPECT_EQ("Deleted", read_body(del1));
  15875. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15876. EXPECT_EQ("Deleted:data", read_body(del2));
  15877. }
  15878. // stream::Head/Options tests
  15879. TEST_F(StreamApiTest, HeadAndOptions) {
  15880. httplib::Client cli(HOST, PORT);
  15881. auto head = httplib::stream::Head(cli, "/head-test");
  15882. EXPECT_TRUE(head.is_valid());
  15883. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15884. auto opts = httplib::stream::Options(cli, "/options");
  15885. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15886. }
  15887. // SSL stream::* tests
  15888. #ifdef CPPHTTPLIB_SSL_ENABLED
  15889. class SSLStreamApiTest : public ::testing::Test {
  15890. protected:
  15891. void SetUp() override {
  15892. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15893. res.set_content("Hello SSL!", "text/plain");
  15894. });
  15895. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15896. res.set_content(req.body, "text/plain");
  15897. });
  15898. port_ = svr_.bind_to_any_port("127.0.0.1");
  15899. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15900. svr_.wait_until_ready();
  15901. }
  15902. void TearDown() override {
  15903. svr_.stop();
  15904. if (thread_.joinable()) thread_.join();
  15905. }
  15906. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15907. std::thread thread_;
  15908. int port_ = 0;
  15909. };
  15910. TEST_F(SSLStreamApiTest, GetAndPost) {
  15911. httplib::SSLClient cli("127.0.0.1", port_);
  15912. cli.enable_server_certificate_verification(false);
  15913. auto get = httplib::stream::Get(cli, "/hello");
  15914. EXPECT_EQ("Hello SSL!", read_body(get));
  15915. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15916. EXPECT_EQ("test", read_body(post));
  15917. }
  15918. #endif
  15919. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15920. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15921. // BodyReader
  15922. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15923. // Test that read timeout during streaming is detected
  15924. // Use a large content-length response where server delays mid-stream
  15925. Server svr;
  15926. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15927. // Send a large response with delay in the middle
  15928. res.set_content_provider(
  15929. 1000, // content_length
  15930. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15931. if (offset < 100) {
  15932. // Send first 100 bytes immediately
  15933. std::string data(100, 'A');
  15934. sink.write(data.c_str(), data.size());
  15935. return true;
  15936. }
  15937. // Then delay longer than client timeout
  15938. std::this_thread::sleep_for(std::chrono::seconds(3));
  15939. std::string data(900, 'B');
  15940. sink.write(data.c_str(), data.size());
  15941. return true;
  15942. });
  15943. });
  15944. auto port = 8091;
  15945. std::thread t([&]() { svr.listen("localhost", port); });
  15946. svr.wait_until_ready();
  15947. Client cli("localhost", port);
  15948. cli.set_read_timeout(1, 0); // 1 second timeout
  15949. auto handle = cli.open_stream("GET", "/slow-stream");
  15950. ASSERT_TRUE(handle.is_valid());
  15951. char buf[256];
  15952. ssize_t total = 0;
  15953. ssize_t n;
  15954. bool got_error = false;
  15955. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15956. total += n;
  15957. }
  15958. if (n < 0) {
  15959. got_error = true;
  15960. // Should be timeout or read error
  15961. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15962. handle.get_read_error() == Error::Read)
  15963. << "Actual error: " << to_string(handle.get_read_error());
  15964. }
  15965. // Either we got an error, or we got less data than expected
  15966. EXPECT_TRUE(got_error || total < 1000)
  15967. << "Expected timeout but got all " << total << " bytes";
  15968. svr.stop();
  15969. t.join();
  15970. }
  15971. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15972. // Test connection closed detection via BodyReader
  15973. Server svr;
  15974. std::atomic<bool> close_now{false};
  15975. svr.Get("/will-close", [&](const Request &, Response &res) {
  15976. res.set_content_provider(
  15977. 10000, // Large content_length that we won't fully send
  15978. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15979. if (offset < 100) {
  15980. std::string data(100, 'X');
  15981. sink.write(data.c_str(), data.size());
  15982. return true;
  15983. }
  15984. // Wait for signal then abort
  15985. while (!close_now) {
  15986. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15987. }
  15988. return false; // Abort - server will close connection
  15989. });
  15990. });
  15991. auto port = 8092;
  15992. std::thread t([&]() { svr.listen("localhost", port); });
  15993. svr.wait_until_ready();
  15994. Client cli("localhost", port);
  15995. auto handle = cli.open_stream("GET", "/will-close");
  15996. ASSERT_TRUE(handle.is_valid());
  15997. char buf[256];
  15998. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15999. EXPECT_GT(n, 0) << "First read should succeed";
  16000. // Signal server to close
  16001. close_now = true;
  16002. // Keep reading until error or EOF
  16003. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16004. // Keep reading
  16005. }
  16006. // Should get an error since content_length wasn't satisfied
  16007. if (n < 0) {
  16008. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16009. handle.get_read_error() == Error::Read)
  16010. << "Actual error: " << to_string(handle.get_read_error());
  16011. }
  16012. svr.stop();
  16013. t.join();
  16014. }
  16015. #ifdef CPPHTTPLIB_SSL_ENABLED
  16016. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16017. // Test that read timeout during SSL streaming is detected
  16018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16019. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16020. res.set_content_provider(
  16021. 1000, "text/plain",
  16022. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16023. if (offset < 100) {
  16024. std::string data(100, 'A');
  16025. sink.write(data.c_str(), data.size());
  16026. return true;
  16027. }
  16028. std::this_thread::sleep_for(std::chrono::seconds(3));
  16029. std::string data(900, 'B');
  16030. sink.write(data.c_str(), data.size());
  16031. return true;
  16032. });
  16033. });
  16034. auto port = 8093;
  16035. std::thread t([&]() { svr.listen("localhost", port); });
  16036. svr.wait_until_ready();
  16037. SSLClient cli("localhost", port);
  16038. cli.enable_server_certificate_verification(false);
  16039. cli.set_read_timeout(1, 0); // 1 second timeout
  16040. auto handle = cli.open_stream("GET", "/slow-stream");
  16041. ASSERT_TRUE(handle.is_valid());
  16042. char buf[256];
  16043. ssize_t total = 0;
  16044. ssize_t n;
  16045. bool got_error = false;
  16046. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16047. total += n;
  16048. }
  16049. if (n < 0) {
  16050. got_error = true;
  16051. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16052. handle.get_read_error() == Error::Read)
  16053. << "Actual error: " << to_string(handle.get_read_error());
  16054. }
  16055. EXPECT_TRUE(got_error || total < 1000)
  16056. << "Expected timeout but got all " << total << " bytes";
  16057. svr.stop();
  16058. t.join();
  16059. }
  16060. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16061. // Test SSL connection closed detection
  16062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16063. std::atomic<bool> close_now{false};
  16064. svr.Get("/will-close", [&](const Request &, Response &res) {
  16065. res.set_content_provider(
  16066. 10000, "text/plain",
  16067. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16068. if (offset < 100) {
  16069. std::string data(100, 'X');
  16070. sink.write(data.c_str(), data.size());
  16071. return true;
  16072. }
  16073. while (!close_now) {
  16074. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16075. }
  16076. return false;
  16077. });
  16078. });
  16079. auto port = 8094;
  16080. std::thread t([&]() { svr.listen("localhost", port); });
  16081. svr.wait_until_ready();
  16082. SSLClient cli("localhost", port);
  16083. cli.enable_server_certificate_verification(false);
  16084. auto handle = cli.open_stream("GET", "/will-close");
  16085. ASSERT_TRUE(handle.is_valid());
  16086. char buf[256];
  16087. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16088. EXPECT_GT(n, 0);
  16089. // Signal server to close
  16090. close_now = true;
  16091. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16092. // Keep reading
  16093. }
  16094. if (n < 0) {
  16095. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16096. handle.get_read_error() == Error::Read)
  16097. << "Actual error: " << to_string(handle.get_read_error());
  16098. }
  16099. svr.stop();
  16100. t.join();
  16101. }
  16102. #endif
  16103. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16104. using namespace httplib;
  16105. // Create a test file
  16106. const char *fname = "etag_testfile.txt";
  16107. const char *content = "etag-content";
  16108. {
  16109. std::ofstream ofs(fname);
  16110. ofs << content;
  16111. ASSERT_TRUE(ofs.good());
  16112. }
  16113. Server svr;
  16114. svr.set_mount_point("/static", ".");
  16115. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16116. svr.wait_until_ready();
  16117. Client cli(HOST, PORT);
  16118. // First request: should get 200 with ETag header
  16119. auto res1 = cli.Get("/static/etag_testfile.txt");
  16120. ASSERT_TRUE(res1);
  16121. ASSERT_EQ(200, res1->status);
  16122. ASSERT_TRUE(res1->has_header("ETag"));
  16123. std::string etag = res1->get_header_value("ETag");
  16124. EXPECT_FALSE(etag.empty());
  16125. // Verify ETag format: W/"hex-hex"
  16126. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16127. EXPECT_EQ('W', etag[0]);
  16128. EXPECT_EQ('/', etag[1]);
  16129. EXPECT_EQ('"', etag[2]);
  16130. EXPECT_EQ('"', etag.back());
  16131. // Exact match: expect 304 Not Modified
  16132. Headers h2 = {{"If-None-Match", etag}};
  16133. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16134. ASSERT_TRUE(res2);
  16135. EXPECT_EQ(304, res2->status);
  16136. // Wildcard match: expect 304 Not Modified
  16137. Headers h3 = {{"If-None-Match", "*"}};
  16138. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16139. ASSERT_TRUE(res3);
  16140. EXPECT_EQ(304, res3->status);
  16141. // Non-matching ETag: expect 200
  16142. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16143. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16144. ASSERT_TRUE(res4);
  16145. EXPECT_EQ(200, res4->status);
  16146. // Multiple ETags with one matching: expect 304
  16147. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16148. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16149. ASSERT_TRUE(res5);
  16150. EXPECT_EQ(304, res5->status);
  16151. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16152. // that equivalent to the single comma-separated list above, so the match on
  16153. // the second line must still be found.
  16154. Headers h6;
  16155. h6.emplace("If-None-Match", "W/\"other\"");
  16156. h6.emplace("If-None-Match", etag);
  16157. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16158. ASSERT_TRUE(res6);
  16159. EXPECT_EQ(304, res6->status);
  16160. svr.stop();
  16161. t.join();
  16162. std::remove(fname);
  16163. }
  16164. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16165. using namespace httplib;
  16166. Server svr;
  16167. svr.set_mount_point("/static", ".");
  16168. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16169. svr.wait_until_ready();
  16170. Client cli(HOST, PORT);
  16171. // Send If-None-Match: * to a non-existent file
  16172. Headers h = {{"If-None-Match", "*"}};
  16173. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16175. EXPECT_EQ(404, res->status);
  16176. svr.stop();
  16177. t.join();
  16178. }
  16179. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16180. using namespace httplib;
  16181. // Create a test file
  16182. const char *fname = "etag_boundary_testfile.txt";
  16183. const char *content = "boundary-test";
  16184. {
  16185. std::ofstream ofs(fname);
  16186. ofs << content;
  16187. ASSERT_TRUE(ofs.good());
  16188. }
  16189. Server svr;
  16190. svr.set_mount_point("/static", ".");
  16191. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16192. svr.wait_until_ready();
  16193. Client cli(HOST, PORT);
  16194. // Get the actual ETag
  16195. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16196. ASSERT_TRUE(res1);
  16197. ASSERT_EQ(200, res1->status);
  16198. ASSERT_TRUE(res1->has_header("ETag"));
  16199. std::string etag = res1->get_header_value("ETag");
  16200. // Test 1: Very long ETag value (longer than actual ETag)
  16201. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16202. Headers h1 = {{"If-None-Match", "W/"
  16203. "\"very-long-etag-value-that-is-much-longer-"
  16204. "than-the-actual-etag-value\""}};
  16205. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16206. ASSERT_TRUE(res2);
  16207. EXPECT_EQ(200, res2->status); // Should not match
  16208. // Test 2: Long string followed by wildcard
  16209. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16210. // string)
  16211. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16212. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16213. ASSERT_TRUE(res3);
  16214. EXPECT_EQ(304, res3->status); // Should match on "*"
  16215. // Test 3: Wildcard followed by long string
  16216. // Should match on "*" immediately and return 304
  16217. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16218. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16219. ASSERT_TRUE(res4);
  16220. EXPECT_EQ(304, res4->status); // Should match on "*"
  16221. // Test 4: Multiple long non-matching values
  16222. // Should NOT match and return 200 (test that all comparisons are safe)
  16223. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16224. "W/\"second-long-non-matching-value\", "
  16225. "W/\"third-long-non-matching-value\""}};
  16226. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16227. ASSERT_TRUE(res5);
  16228. EXPECT_EQ(200, res5->status); // Should not match
  16229. // Test 5: Single character that is not "*" (edge case)
  16230. Headers h5 = {{"If-None-Match", "X"}};
  16231. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16232. ASSERT_TRUE(res6);
  16233. EXPECT_EQ(200, res6->status); // Should not match
  16234. svr.stop();
  16235. t.join();
  16236. std::remove(fname);
  16237. }
  16238. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16239. using namespace httplib;
  16240. // Create a test file
  16241. const char *fname = "ims_testfile.txt";
  16242. const char *content = "if-modified-since-test";
  16243. {
  16244. std::ofstream ofs(fname);
  16245. ofs << content;
  16246. ASSERT_TRUE(ofs.good());
  16247. }
  16248. Server svr;
  16249. svr.set_mount_point("/static", ".");
  16250. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16251. svr.wait_until_ready();
  16252. Client cli(HOST, PORT);
  16253. // First request: should get 200 with Last-Modified header
  16254. auto res1 = cli.Get("/static/ims_testfile.txt");
  16255. ASSERT_TRUE(res1);
  16256. ASSERT_EQ(200, res1->status);
  16257. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16258. std::string last_modified = res1->get_header_value("Last-Modified");
  16259. EXPECT_FALSE(last_modified.empty());
  16260. // If-Modified-Since with same time: expect 304
  16261. Headers h2 = {{"If-Modified-Since", last_modified}};
  16262. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16263. ASSERT_TRUE(res2);
  16264. EXPECT_EQ(304, res2->status);
  16265. // If-Modified-Since with future time: expect 304
  16266. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16267. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16268. ASSERT_TRUE(res3);
  16269. EXPECT_EQ(304, res3->status);
  16270. // If-Modified-Since with past time: expect 200
  16271. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16272. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16273. ASSERT_TRUE(res4);
  16274. EXPECT_EQ(200, res4->status);
  16275. // If-None-Match takes precedence over If-Modified-Since
  16276. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16277. ASSERT_TRUE(res1->has_header("ETag"));
  16278. std::string etag = res1->get_header_value("ETag");
  16279. Headers h5 = {{"If-None-Match", etag},
  16280. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16281. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16282. ASSERT_TRUE(res5);
  16283. EXPECT_EQ(304, res5->status);
  16284. svr.stop();
  16285. t.join();
  16286. std::remove(fname);
  16287. }
  16288. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16289. using namespace httplib;
  16290. Server svr;
  16291. // Endpoint that returns compressible content
  16292. svr.Get("/compressible", [](const Request &, Response &res) {
  16293. // Return a large enough body to trigger compression
  16294. std::string body(1000, 'a');
  16295. res.set_content(body, "text/plain");
  16296. });
  16297. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16298. svr.wait_until_ready();
  16299. Client cli(HOST, PORT);
  16300. // Request with gzip support: should get Vary header when compressed
  16301. cli.set_compress(true);
  16302. auto res1 = cli.Get("/compressible");
  16303. ASSERT_TRUE(res1);
  16304. EXPECT_EQ(200, res1->status);
  16305. // If Content-Encoding is set, Vary should also be set
  16306. if (res1->has_header("Content-Encoding")) {
  16307. EXPECT_TRUE(res1->has_header("Vary"));
  16308. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16309. }
  16310. // Request without Accept-Encoding header: should not have compression
  16311. Headers h_no_compress;
  16312. auto res2 = cli.Get("/compressible", h_no_compress);
  16313. ASSERT_TRUE(res2);
  16314. EXPECT_EQ(200, res2->status);
  16315. // Verify Vary header is present when compression is applied
  16316. // (the exact behavior depends on server configuration)
  16317. svr.stop();
  16318. t.join();
  16319. }
  16320. TEST(ETagTest, IfRangeWithETag) {
  16321. using namespace httplib;
  16322. // Create a test file with known content
  16323. const char *fname = "if_range_testfile.txt";
  16324. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16325. {
  16326. std::ofstream ofs(fname);
  16327. ofs << content;
  16328. ASSERT_TRUE(ofs.good());
  16329. }
  16330. Server svr;
  16331. svr.set_mount_point("/static", ".");
  16332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16333. svr.wait_until_ready();
  16334. Client cli(HOST, PORT);
  16335. // First request: get ETag
  16336. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16337. ASSERT_TRUE(res1);
  16338. ASSERT_EQ(200, res1->status);
  16339. ASSERT_TRUE(res1->has_header("ETag"));
  16340. std::string etag = res1->get_header_value("ETag");
  16341. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16342. // Since our server generates weak ETags (W/"..."), If-Range with our
  16343. // ETag should NOT result in partial content - it should return full content.
  16344. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16345. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16346. ASSERT_TRUE(res2);
  16347. // Weak ETag in If-Range -> full content (200), not partial (206)
  16348. EXPECT_EQ(200, res2->status);
  16349. EXPECT_EQ(content, res2->body);
  16350. EXPECT_FALSE(res2->has_header("Content-Range"));
  16351. // Range request with non-matching If-Range (ETag): should get 200 (full
  16352. // content)
  16353. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16354. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16355. ASSERT_TRUE(res3);
  16356. EXPECT_EQ(200, res3->status);
  16357. EXPECT_EQ(content, res3->body);
  16358. EXPECT_FALSE(res3->has_header("Content-Range"));
  16359. // Range request with strong ETag (hypothetical - our server doesn't generate
  16360. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16361. // should return full content)
  16362. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16363. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16364. ASSERT_TRUE(res4);
  16365. EXPECT_EQ(200, res4->status);
  16366. EXPECT_EQ(content, res4->body);
  16367. EXPECT_FALSE(res4->has_header("Content-Range"));
  16368. svr.stop();
  16369. t.join();
  16370. std::remove(fname);
  16371. }
  16372. TEST(ETagTest, IfRangeWithDate) {
  16373. using namespace httplib;
  16374. // Create a test file
  16375. const char *fname = "if_range_date_testfile.txt";
  16376. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16377. {
  16378. std::ofstream ofs(fname);
  16379. ofs << content;
  16380. ASSERT_TRUE(ofs.good());
  16381. }
  16382. Server svr;
  16383. svr.set_mount_point("/static", ".");
  16384. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16385. svr.wait_until_ready();
  16386. Client cli(HOST, PORT);
  16387. // First request: get Last-Modified
  16388. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16389. ASSERT_TRUE(res1);
  16390. ASSERT_EQ(200, res1->status);
  16391. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16392. std::string last_modified = res1->get_header_value("Last-Modified");
  16393. // Range request with matching If-Range (date): should get 206
  16394. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16395. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16396. ASSERT_TRUE(res2);
  16397. EXPECT_EQ(206, res2->status);
  16398. EXPECT_EQ("FGHIJ", res2->body);
  16399. // Range request with old If-Range date: should get 200 (full content)
  16400. Headers h3 = {{"Range", "bytes=5-9"},
  16401. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16402. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16403. ASSERT_TRUE(res3);
  16404. EXPECT_EQ(200, res3->status);
  16405. EXPECT_EQ(content, res3->body);
  16406. // Range request with future If-Range date: should get 206
  16407. Headers h4 = {{"Range", "bytes=0-4"},
  16408. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16409. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16410. ASSERT_TRUE(res4);
  16411. EXPECT_EQ(206, res4->status);
  16412. EXPECT_EQ("ABCDE", res4->body);
  16413. svr.stop();
  16414. t.join();
  16415. std::remove(fname);
  16416. }
  16417. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16418. using namespace httplib;
  16419. const char *fname = "etag_malformed.txt";
  16420. const char *content = "malformed-etag";
  16421. {
  16422. std::ofstream ofs(fname);
  16423. ofs << content;
  16424. ASSERT_TRUE(ofs.good());
  16425. }
  16426. Server svr;
  16427. svr.set_mount_point("/static", ".");
  16428. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16429. svr.wait_until_ready();
  16430. Client cli(HOST, PORT);
  16431. // baseline: should get 200 and an ETag
  16432. auto res1 = cli.Get("/static/etag_malformed.txt");
  16433. ASSERT_TRUE(res1);
  16434. ASSERT_EQ(200, res1->status);
  16435. ASSERT_TRUE(res1->has_header("ETag"));
  16436. // Malformed ETag value (missing quotes) should be treated as non-matching
  16437. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16438. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16439. ASSERT_TRUE(res_bad);
  16440. EXPECT_EQ(200, res_bad->status);
  16441. // Whitespace-only header value should be considered invalid / non-matching
  16442. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16443. "Host: localhost\r\n"
  16444. "If-None-Match: \r\n"
  16445. "Connection: close\r\n"
  16446. "\r\n";
  16447. std::string out;
  16448. ASSERT_TRUE(send_request(5, raw_req, &out));
  16449. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16450. svr.stop();
  16451. t.join();
  16452. std::remove(fname);
  16453. }
  16454. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16455. using namespace httplib;
  16456. const char *fname = "ims_invalid_format.txt";
  16457. const char *content = "ims-bad-format";
  16458. {
  16459. std::ofstream ofs(fname);
  16460. ofs << content;
  16461. ASSERT_TRUE(ofs.good());
  16462. }
  16463. Server svr;
  16464. svr.set_mount_point("/static", ".");
  16465. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16466. svr.wait_until_ready();
  16467. Client cli(HOST, PORT);
  16468. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16469. ASSERT_TRUE(res1);
  16470. ASSERT_EQ(200, res1->status);
  16471. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16472. // If-Modified-Since with invalid format should not result in 304
  16473. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16474. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16475. ASSERT_TRUE(res_bad);
  16476. EXPECT_EQ(200, res_bad->status);
  16477. // If-Range with invalid date format should be treated as mismatch -> full
  16478. // content (200)
  16479. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16480. {"If-Range", "invalid-date"}};
  16481. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16482. ASSERT_TRUE(res_ifrange);
  16483. EXPECT_EQ(200, res_ifrange->status);
  16484. svr.stop();
  16485. t.join();
  16486. std::remove(fname);
  16487. }
  16488. TEST(ETagTest, IfRangeWithMalformedETag) {
  16489. using namespace httplib;
  16490. const char *fname = "ifrange_malformed.txt";
  16491. const std::string content = "0123456789";
  16492. {
  16493. std::ofstream ofs(fname);
  16494. ofs << content;
  16495. ASSERT_TRUE(ofs.good());
  16496. }
  16497. Server svr;
  16498. svr.set_mount_point("/static", ".");
  16499. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16500. svr.wait_until_ready();
  16501. Client cli(HOST, PORT);
  16502. // First request: get ETag
  16503. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16504. ASSERT_TRUE(res1);
  16505. ASSERT_EQ(200, res1->status);
  16506. ASSERT_TRUE(res1->has_header("ETag"));
  16507. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16508. // full content (200)
  16509. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16510. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16511. ASSERT_TRUE(res2);
  16512. EXPECT_EQ(200, res2->status);
  16513. EXPECT_EQ(content, res2->body);
  16514. svr.stop();
  16515. t.join();
  16516. std::remove(fname);
  16517. }
  16518. TEST(ETagTest, ExtremeLargeDateValues) {
  16519. using namespace httplib;
  16520. const char *fname = "ims_extreme_date.txt";
  16521. const char *content = "ims-extreme-date";
  16522. {
  16523. std::ofstream ofs(fname);
  16524. ofs << content;
  16525. ASSERT_TRUE(ofs.good());
  16526. }
  16527. Server svr;
  16528. svr.set_mount_point("/static", ".");
  16529. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16530. svr.wait_until_ready();
  16531. Client cli(HOST, PORT);
  16532. auto res1 = cli.Get(std::string("/static/") + fname);
  16533. ASSERT_TRUE(res1);
  16534. ASSERT_EQ(200, res1->status);
  16535. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16536. // Extremely large year that may overflow date parsing routines.
  16537. Headers h_large_date = {
  16538. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16539. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16540. ASSERT_TRUE(res_bad);
  16541. // Expect server to treat this as invalid/mismatch and return full content
  16542. EXPECT_EQ(200, res_bad->status);
  16543. // If-Range with extremely large date should be treated as mismatch -> full
  16544. // content (200)
  16545. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16546. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16547. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16548. ASSERT_TRUE(res_ifrange);
  16549. EXPECT_EQ(200, res_ifrange->status);
  16550. svr.stop();
  16551. t.join();
  16552. std::remove(fname);
  16553. }
  16554. TEST(ETagTest, NegativeFileModificationTime) {
  16555. using namespace httplib;
  16556. const char *fname = "ims_negative_mtime.txt";
  16557. const std::string content = "negative-mtime";
  16558. {
  16559. std::ofstream ofs(fname);
  16560. ofs << content;
  16561. ASSERT_TRUE(ofs.good());
  16562. }
  16563. // Try to set file mtime to a negative value. This may fail on some
  16564. // platforms/filesystems; if it fails, the test will still verify server
  16565. // behaves safely by performing a regular conditional request.
  16566. #if defined(__APPLE__) || defined(__linux__)
  16567. bool set_negative = false;
  16568. do {
  16569. struct timeval times[2];
  16570. // access time: now
  16571. times[0].tv_sec = time(nullptr);
  16572. times[0].tv_usec = 0;
  16573. // modification time: negative (e.g., -1)
  16574. times[1].tv_sec = -1;
  16575. times[1].tv_usec = 0;
  16576. if (utimes(fname, times) == 0) { set_negative = true; }
  16577. } while (0);
  16578. #else
  16579. bool set_negative = false;
  16580. #endif
  16581. Server svr;
  16582. svr.set_mount_point("/static", ".");
  16583. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16584. svr.wait_until_ready();
  16585. Client cli(HOST, PORT);
  16586. auto res1 = cli.Get(std::string("/static/") + fname);
  16587. ASSERT_TRUE(res1);
  16588. ASSERT_EQ(200, res1->status);
  16589. bool has_last_modified = res1->has_header("Last-Modified");
  16590. std::string last_modified;
  16591. if (has_last_modified) {
  16592. last_modified = res1->get_header_value("Last-Modified");
  16593. }
  16594. if (set_negative) {
  16595. // If we successfully set a negative mtime, ensure server returns a
  16596. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16597. // with an old date and ensure server handles it without crash.
  16598. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16599. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16600. ASSERT_TRUE(res2);
  16601. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16602. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16603. } else {
  16604. // Could not set negative mtime on this platform; fall back to verifying
  16605. // that normal invalid/malformed dates are treated safely (non-304).
  16606. Headers h_bad_date = {
  16607. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16608. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16609. ASSERT_TRUE(res_bad);
  16610. EXPECT_EQ(200, res_bad->status);
  16611. }
  16612. svr.stop();
  16613. t.join();
  16614. std::remove(fname);
  16615. }
  16616. //==============================================================================
  16617. // SSE Parsing Tests
  16618. //==============================================================================
  16619. class SSEParsingTest : public ::testing::Test {
  16620. protected:
  16621. // Test helper that mimics SSE parsing behavior
  16622. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16623. int &retry_ms) {
  16624. // Blank line signals end of event
  16625. if (line.empty() || line == "\r") { return true; }
  16626. // Lines starting with ':' are comments (ignored)
  16627. if (!line.empty() && line[0] == ':') { return false; }
  16628. // Find the colon separator
  16629. auto colon_pos = line.find(':');
  16630. if (colon_pos == std::string::npos) {
  16631. // Line with no colon is treated as field name with empty value
  16632. return false;
  16633. }
  16634. std::string field = line.substr(0, colon_pos);
  16635. std::string value;
  16636. // Value starts after colon, skip optional single space
  16637. if (colon_pos + 1 < line.size()) {
  16638. size_t value_start = colon_pos + 1;
  16639. if (line[value_start] == ' ') { value_start++; }
  16640. value = line.substr(value_start);
  16641. // Remove trailing \r if present
  16642. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16643. }
  16644. // Handle known fields
  16645. if (field == "event") {
  16646. msg.event = value;
  16647. } else if (field == "data") {
  16648. // Multiple data lines are concatenated with newlines
  16649. if (!msg.data.empty()) { msg.data += "\n"; }
  16650. msg.data += value;
  16651. } else if (field == "id") {
  16652. // Empty id is valid (clears the last event ID)
  16653. msg.id = value;
  16654. } else if (field == "retry") {
  16655. // Parse retry interval in milliseconds
  16656. {
  16657. int v = 0;
  16658. auto res =
  16659. detail::from_chars(value.data(), value.data() + value.size(), v);
  16660. if (res.ec == std::errc{}) { retry_ms = v; }
  16661. }
  16662. }
  16663. // Unknown fields are ignored per SSE spec
  16664. return false;
  16665. }
  16666. };
  16667. // Test: Single-line data
  16668. TEST_F(SSEParsingTest, SingleLineData) {
  16669. sse::SSEMessage msg;
  16670. int retry_ms = 3000;
  16671. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16672. EXPECT_EQ(msg.data, "hello");
  16673. EXPECT_EQ(msg.event, "message");
  16674. // Blank line ends event
  16675. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16676. }
  16677. // Test: Multi-line data
  16678. TEST_F(SSEParsingTest, MultiLineData) {
  16679. sse::SSEMessage msg;
  16680. int retry_ms = 3000;
  16681. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16682. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16683. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16684. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16685. }
  16686. // Test: Custom event types
  16687. TEST_F(SSEParsingTest, CustomEventType) {
  16688. sse::SSEMessage msg;
  16689. int retry_ms = 3000;
  16690. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16691. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16692. EXPECT_EQ(msg.event, "update");
  16693. EXPECT_EQ(msg.data, "payload");
  16694. }
  16695. // Test: Event ID handling
  16696. TEST_F(SSEParsingTest, EventIdHandling) {
  16697. sse::SSEMessage msg;
  16698. int retry_ms = 3000;
  16699. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16700. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16701. EXPECT_EQ(msg.id, "12345");
  16702. }
  16703. // Test: Empty event ID (clears last event ID)
  16704. TEST_F(SSEParsingTest, EmptyEventId) {
  16705. sse::SSEMessage msg;
  16706. msg.id = "previous";
  16707. int retry_ms = 3000;
  16708. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16709. EXPECT_EQ(msg.id, "");
  16710. }
  16711. // Test: Retry field parsing
  16712. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16713. sse::SSEMessage msg;
  16714. int retry_ms = 3000;
  16715. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16716. EXPECT_EQ(retry_ms, 5000);
  16717. }
  16718. // Test: Invalid retry value
  16719. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16720. sse::SSEMessage msg;
  16721. int retry_ms = 3000;
  16722. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16723. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16724. }
  16725. // Test: Comments (lines starting with :)
  16726. TEST_F(SSEParsingTest, CommentsIgnored) {
  16727. sse::SSEMessage msg;
  16728. int retry_ms = 3000;
  16729. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16730. EXPECT_EQ(msg.data, "");
  16731. EXPECT_EQ(msg.event, "message");
  16732. }
  16733. // Test: Colon in value
  16734. TEST_F(SSEParsingTest, ColonInValue) {
  16735. sse::SSEMessage msg;
  16736. int retry_ms = 3000;
  16737. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16738. EXPECT_EQ(msg.data, "hello:world:test");
  16739. }
  16740. // Test: Line with no colon (field name only)
  16741. TEST_F(SSEParsingTest, FieldNameOnly) {
  16742. sse::SSEMessage msg;
  16743. int retry_ms = 3000;
  16744. // According to SSE spec, this is treated as field name with empty value
  16745. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16746. // Since we don't recognize "data" without colon, data should be empty
  16747. EXPECT_EQ(msg.data, "");
  16748. }
  16749. // Test: Trailing \r handling
  16750. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16751. sse::SSEMessage msg;
  16752. int retry_ms = 3000;
  16753. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16754. EXPECT_EQ(msg.data, "hello");
  16755. }
  16756. // Test: Unknown fields ignored
  16757. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16758. sse::SSEMessage msg;
  16759. int retry_ms = 3000;
  16760. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16761. EXPECT_EQ(msg.data, "");
  16762. EXPECT_EQ(msg.event, "message");
  16763. }
  16764. // Test: Space after colon is optional
  16765. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16766. sse::SSEMessage msg1, msg2;
  16767. int retry_ms = 3000;
  16768. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16769. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16770. EXPECT_EQ(msg1.data, "hello");
  16771. EXPECT_EQ(msg2.data, "hello");
  16772. }
  16773. // Test: SSEMessage clear
  16774. TEST_F(SSEParsingTest, MessageClear) {
  16775. sse::SSEMessage msg;
  16776. msg.event = "custom";
  16777. msg.data = "some data";
  16778. msg.id = "123";
  16779. msg.clear();
  16780. EXPECT_EQ(msg.event, "message");
  16781. EXPECT_EQ(msg.data, "");
  16782. EXPECT_EQ(msg.id, "");
  16783. }
  16784. // Test: Complete event parsing
  16785. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16786. sse::SSEMessage msg;
  16787. int retry_ms = 3000;
  16788. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16789. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16790. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16791. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16792. // Blank line ends event
  16793. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16794. EXPECT_EQ(msg.event, "notification");
  16795. EXPECT_EQ(msg.id, "evt-42");
  16796. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16797. EXPECT_EQ(retry_ms, 1000);
  16798. }
  16799. //==============================================================================
  16800. // Integration Tests with Server
  16801. //==============================================================================
  16802. class SSEIntegrationTest : public ::testing::Test {
  16803. protected:
  16804. void SetUp() override {
  16805. stop_server_.store(false);
  16806. events_.clear();
  16807. server_ = httplib::detail::make_unique<Server>();
  16808. setup_server();
  16809. start_server();
  16810. }
  16811. void TearDown() override {
  16812. stop_server_.store(true);
  16813. event_cv_.notify_all();
  16814. server_->stop();
  16815. if (server_thread_.joinable()) { server_thread_.join(); }
  16816. }
  16817. void setup_server() {
  16818. // Simple SSE endpoint
  16819. server_->Get("/events", [this](const Request &req, Response &res) {
  16820. auto last_id = req.get_header_value("Last-Event-ID");
  16821. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16822. res.set_chunked_content_provider(
  16823. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16824. std::unique_lock<std::mutex> lock(event_mutex_);
  16825. if (event_cv_.wait_for(
  16826. lock, std::chrono::milliseconds(200), [this] {
  16827. return !events_.empty() || stop_server_.load();
  16828. })) {
  16829. if (stop_server_.load()) { return false; }
  16830. if (!events_.empty()) {
  16831. std::string event = events_.front();
  16832. events_.erase(events_.begin());
  16833. sink.write(event.data(), event.size());
  16834. return true;
  16835. }
  16836. }
  16837. return !stop_server_.load();
  16838. });
  16839. });
  16840. // Endpoint that returns error
  16841. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16842. res.status = 500;
  16843. res.set_content("Internal Server Error", "text/plain");
  16844. });
  16845. // Endpoint for custom event types
  16846. server_->Get("/custom-events", [](const Request &, Response &res) {
  16847. res.set_chunked_content_provider(
  16848. "text/event-stream", [](size_t offset, DataSink &sink) {
  16849. if (offset == 0) {
  16850. std::string event = "event: update\ndata: updated\n\n"
  16851. "event: delete\ndata: deleted\n\n";
  16852. sink.write(event.data(), event.size());
  16853. }
  16854. return false; // End stream after sending
  16855. });
  16856. });
  16857. }
  16858. void start_server() {
  16859. port_ = server_->bind_to_any_port(HOST);
  16860. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16861. // Wait for server to start
  16862. while (!server_->is_running()) {
  16863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16864. }
  16865. }
  16866. int get_port() const { return port_; }
  16867. void send_event(const std::string &event) {
  16868. std::lock_guard<std::mutex> lock(event_mutex_);
  16869. events_.push_back(event);
  16870. event_cv_.notify_all();
  16871. }
  16872. std::unique_ptr<Server> server_;
  16873. std::thread server_thread_;
  16874. std::mutex event_mutex_;
  16875. std::condition_variable event_cv_;
  16876. std::vector<std::string> events_;
  16877. std::atomic<bool> stop_server_{false};
  16878. std::string last_received_event_id_;
  16879. int port_ = 0;
  16880. };
  16881. // Test: Successful connection and on_open callback
  16882. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16883. // Add a simple endpoint that sends one event and closes
  16884. server_->Get("/simple-event", [](const Request &, Response &res) {
  16885. res.set_chunked_content_provider(
  16886. "text/event-stream", [](size_t offset, DataSink &sink) {
  16887. if (offset == 0) {
  16888. std::string event = "data: hello\n\n";
  16889. sink.write(event.data(), event.size());
  16890. }
  16891. return false; // Close stream after sending
  16892. });
  16893. });
  16894. Client client("localhost", get_port());
  16895. sse::SSEClient sse(client, "/simple-event");
  16896. std::atomic<bool> open_called{false};
  16897. std::atomic<bool> message_received{false};
  16898. sse.on_open([&open_called]() { open_called.store(true); });
  16899. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16900. if (msg.data == "hello") { message_received.store(true); }
  16901. });
  16902. sse.set_reconnect_interval(100);
  16903. sse.set_max_reconnect_attempts(1);
  16904. // Start async
  16905. sse.start_async();
  16906. // Wait for message to be processed
  16907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16908. sse.stop();
  16909. EXPECT_TRUE(open_called.load());
  16910. EXPECT_TRUE(message_received.load());
  16911. }
  16912. // Test: on_message callback
  16913. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16914. // Endpoint that sends multiple events then closes
  16915. server_->Get("/multi-event", [](const Request &, Response &res) {
  16916. res.set_chunked_content_provider(
  16917. "text/event-stream", [](size_t offset, DataSink &sink) {
  16918. if (offset == 0) {
  16919. std::string events = "data: message1\n\ndata: message2\n\n";
  16920. sink.write(events.data(), events.size());
  16921. }
  16922. return false;
  16923. });
  16924. });
  16925. Client client("localhost", get_port());
  16926. sse::SSEClient sse(client, "/multi-event");
  16927. std::vector<std::string> received_messages;
  16928. std::mutex messages_mutex;
  16929. sse.on_message([&](const sse::SSEMessage &msg) {
  16930. std::lock_guard<std::mutex> lock(messages_mutex);
  16931. received_messages.push_back(msg.data);
  16932. });
  16933. sse.set_reconnect_interval(100);
  16934. sse.set_max_reconnect_attempts(1);
  16935. sse.start_async();
  16936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16937. sse.stop();
  16938. std::lock_guard<std::mutex> lock(messages_mutex);
  16939. EXPECT_GE(received_messages.size(), 2u);
  16940. if (received_messages.size() >= 2) {
  16941. EXPECT_EQ(received_messages[0], "message1");
  16942. EXPECT_EQ(received_messages[1], "message2");
  16943. }
  16944. }
  16945. // Test: on_event for specific types
  16946. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16947. Client client("localhost", get_port());
  16948. sse::SSEClient sse(client, "/custom-events");
  16949. std::atomic<bool> update_received{false};
  16950. std::atomic<bool> delete_received{false};
  16951. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16952. if (msg.data == "updated") { update_received.store(true); }
  16953. });
  16954. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16955. if (msg.data == "deleted") { delete_received.store(true); }
  16956. });
  16957. sse.set_max_reconnect_attempts(1);
  16958. sse.start_async();
  16959. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16960. sse.stop();
  16961. EXPECT_TRUE(update_received.load());
  16962. EXPECT_TRUE(delete_received.load());
  16963. }
  16964. // Test: on_error callback on connection failure
  16965. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16966. // Connect to a non-existent port
  16967. Client client("localhost", 59999);
  16968. sse::SSEClient sse(client, "/events");
  16969. std::atomic<bool> error_called{false};
  16970. Error received_error = Error::Success;
  16971. sse.on_error([&](Error err) {
  16972. error_called.store(true);
  16973. received_error = err;
  16974. });
  16975. sse.set_reconnect_interval(50);
  16976. sse.set_max_reconnect_attempts(1);
  16977. sse.start_async();
  16978. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16979. sse.stop();
  16980. EXPECT_TRUE(error_called.load());
  16981. EXPECT_NE(received_error, Error::Success);
  16982. }
  16983. // Test: Last-Event-ID header sent on reconnect
  16984. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16985. // Endpoint that sends event with ID
  16986. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16987. res.set_chunked_content_provider(
  16988. "text/event-stream", [](size_t offset, DataSink &sink) {
  16989. if (offset == 0) {
  16990. std::string event = "id: evt-123\ndata: test\n\n";
  16991. sink.write(event.data(), event.size());
  16992. }
  16993. return false;
  16994. });
  16995. });
  16996. Client client("localhost", get_port());
  16997. sse::SSEClient sse(client, "/event-with-id");
  16998. std::atomic<bool> id_received{false};
  16999. sse.on_message([&](const sse::SSEMessage &msg) {
  17000. if (!msg.id.empty()) { id_received.store(true); }
  17001. });
  17002. sse.set_reconnect_interval(100);
  17003. sse.set_max_reconnect_attempts(1);
  17004. sse.start_async();
  17005. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17006. sse.stop();
  17007. EXPECT_TRUE(id_received.load());
  17008. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17009. }
  17010. // Test: Manual stop
  17011. TEST_F(SSEIntegrationTest, ManualStop) {
  17012. // Endpoint that sends one event and stays open briefly
  17013. std::atomic<bool> handler_running{true};
  17014. server_->Get("/stay-open", [&handler_running](const Request &,
  17015. Response &res) {
  17016. res.set_chunked_content_provider(
  17017. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17018. if (offset == 0) {
  17019. std::string event = "data: connected\n\n";
  17020. sink.write(event.data(), event.size());
  17021. }
  17022. // Keep connection open while handler_running is true
  17023. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17024. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17025. }
  17026. return false;
  17027. });
  17028. });
  17029. Client client("localhost", get_port());
  17030. sse::SSEClient sse(client, "/stay-open");
  17031. std::atomic<bool> connected{false};
  17032. sse.on_open([&connected]() { connected.store(true); });
  17033. sse.set_reconnect_interval(100);
  17034. sse.set_max_reconnect_attempts(1);
  17035. sse.start_async();
  17036. // Wait for connection to establish
  17037. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17038. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17039. }
  17040. EXPECT_TRUE(connected.load());
  17041. EXPECT_TRUE(sse.is_connected());
  17042. // Signal handler to stop
  17043. handler_running.store(false);
  17044. // Stop SSE client
  17045. sse.stop();
  17046. EXPECT_FALSE(sse.is_connected());
  17047. }
  17048. // Test: SSEClient with custom headers
  17049. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17050. // Setup a server endpoint that checks for custom header
  17051. std::atomic<bool> header_received{false};
  17052. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17053. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17054. header_received.store(true);
  17055. }
  17056. res.set_chunked_content_provider("text/event-stream",
  17057. [](size_t, DataSink &) { return false; });
  17058. });
  17059. Client client("localhost", get_port());
  17060. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17061. sse::SSEClient sse(client, "/header-check", headers);
  17062. sse.set_max_reconnect_attempts(1);
  17063. sse.start_async();
  17064. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17065. sse.stop();
  17066. EXPECT_TRUE(header_received.load());
  17067. }
  17068. // Test: Reconnect interval configuration
  17069. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17070. Client client("localhost", get_port());
  17071. sse::SSEClient sse(client, "/events");
  17072. auto &result = sse.set_reconnect_interval(500);
  17073. // Builder pattern should return reference to self
  17074. EXPECT_EQ(&result, &sse);
  17075. }
  17076. // Test: Max reconnect attempts
  17077. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17078. // Connect to non-existent port to force reconnects
  17079. Client client("localhost", 59998);
  17080. sse::SSEClient sse(client, "/events");
  17081. std::atomic<int> error_count{0};
  17082. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17083. sse.set_reconnect_interval(50);
  17084. sse.set_max_reconnect_attempts(2);
  17085. auto start = std::chrono::steady_clock::now();
  17086. sse.start(); // Blocking call
  17087. auto end = std::chrono::steady_clock::now();
  17088. // Should have stopped after 2 failed attempts
  17089. EXPECT_GE(error_count.load(), 2);
  17090. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17091. auto duration =
  17092. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17093. #ifdef _WIN32
  17094. // Windows is much slower for socket connection failures
  17095. EXPECT_LT(duration.count(), 7000);
  17096. #else
  17097. EXPECT_LT(duration.count(), 1000);
  17098. #endif
  17099. }
  17100. // Test: Multi-line data in integration
  17101. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17102. // Endpoint with multi-line data
  17103. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17104. res.set_chunked_content_provider(
  17105. "text/event-stream", [](size_t offset, DataSink &sink) {
  17106. if (offset == 0) {
  17107. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17108. sink.write(event.data(), event.size());
  17109. }
  17110. return false;
  17111. });
  17112. });
  17113. Client client("localhost", get_port());
  17114. sse::SSEClient sse(client, "/multiline-data");
  17115. std::string received_data;
  17116. std::mutex data_mutex;
  17117. sse.on_message([&](const sse::SSEMessage &msg) {
  17118. std::lock_guard<std::mutex> lock(data_mutex);
  17119. received_data = msg.data;
  17120. });
  17121. sse.set_reconnect_interval(100);
  17122. sse.set_max_reconnect_attempts(1);
  17123. sse.start_async();
  17124. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17125. sse.stop();
  17126. std::lock_guard<std::mutex> lock(data_mutex);
  17127. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17128. }
  17129. // Test: Auto-reconnect after server disconnection
  17130. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17131. std::atomic<int> connection_count{0};
  17132. std::atomic<int> message_count{0};
  17133. // Endpoint that sends one event and closes, forcing reconnect
  17134. server_->Get("/reconnect-test",
  17135. [&connection_count](const Request &, Response &res) {
  17136. connection_count.fetch_add(1);
  17137. res.set_chunked_content_provider(
  17138. "text/event-stream", [](size_t offset, DataSink &sink) {
  17139. if (offset == 0) {
  17140. std::string event = "data: hello\n\n";
  17141. sink.write(event.data(), event.size());
  17142. }
  17143. return false; // Close connection after sending
  17144. });
  17145. });
  17146. Client client("localhost", get_port());
  17147. sse::SSEClient sse(client, "/reconnect-test");
  17148. sse.on_message([&message_count](const sse::SSEMessage &) {
  17149. message_count.fetch_add(1);
  17150. });
  17151. sse.set_reconnect_interval(100);
  17152. sse.set_max_reconnect_attempts(3);
  17153. sse.start_async();
  17154. // Wait long enough for multiple reconnects
  17155. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17156. sse.stop();
  17157. // Should have connected multiple times (initial + reconnects)
  17158. EXPECT_GE(connection_count.load(), 2);
  17159. // Should have received messages from multiple connections
  17160. EXPECT_GE(message_count.load(), 2);
  17161. }
  17162. // Test: Last-Event-ID sent on reconnect
  17163. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17164. std::atomic<int> connection_count{0};
  17165. std::vector<std::string> received_last_event_ids;
  17166. std::mutex id_mutex;
  17167. // Endpoint that checks Last-Event-ID header and sends event with ID
  17168. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17169. int conn = connection_count.fetch_add(1);
  17170. // Capture the Last-Event-ID header from each connection
  17171. {
  17172. std::lock_guard<std::mutex> lock(id_mutex);
  17173. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17174. }
  17175. res.set_chunked_content_provider(
  17176. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17177. if (offset == 0) {
  17178. std::string event =
  17179. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17180. sink.write(event.data(), event.size());
  17181. }
  17182. return false;
  17183. });
  17184. });
  17185. Client client("localhost", get_port());
  17186. sse::SSEClient sse(client, "/reconnect-with-id");
  17187. sse.set_reconnect_interval(100);
  17188. sse.set_max_reconnect_attempts(3);
  17189. sse.start_async();
  17190. // Wait for at least 2 connections
  17191. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17192. sse.stop();
  17193. // Verify behavior
  17194. std::lock_guard<std::mutex> lock(id_mutex);
  17195. EXPECT_GE(received_last_event_ids.size(), 2u);
  17196. // First connection should have no Last-Event-ID
  17197. if (!received_last_event_ids.empty()) {
  17198. EXPECT_EQ(received_last_event_ids[0], "");
  17199. }
  17200. // Second connection should have Last-Event-ID from first connection
  17201. if (received_last_event_ids.size() >= 2) {
  17202. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17203. }
  17204. }
  17205. // Test: set_headers updates headers used on reconnect
  17206. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17207. std::vector<std::string> received_tokens;
  17208. std::mutex token_mutex;
  17209. // Endpoint that captures Authorization header
  17210. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17211. {
  17212. std::lock_guard<std::mutex> lock(token_mutex);
  17213. received_tokens.push_back(req.get_header_value("Authorization"));
  17214. }
  17215. res.set_chunked_content_provider(
  17216. "text/event-stream", [](size_t offset, DataSink &sink) {
  17217. if (offset == 0) {
  17218. std::string event = "data: hello\n\n";
  17219. sink.write(event.data(), event.size());
  17220. }
  17221. return false; // Close connection to trigger reconnect
  17222. });
  17223. });
  17224. Client client("localhost", get_port());
  17225. Headers headers = {{"Authorization", "Bearer old-token"}};
  17226. sse::SSEClient sse(client, "/auth-check", headers);
  17227. // Update headers on each successful connection
  17228. sse.on_open(
  17229. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17230. sse.set_reconnect_interval(100);
  17231. sse.set_max_reconnect_attempts(3);
  17232. sse.start_async();
  17233. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17234. sse.stop();
  17235. std::lock_guard<std::mutex> lock(token_mutex);
  17236. ASSERT_GE(received_tokens.size(), 2u);
  17237. // First connection uses original header
  17238. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17239. // Second connection uses updated header from set_headers
  17240. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17241. }
  17242. // Test: 401 allows reconnection (so on_error can refresh headers)
  17243. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17244. std::atomic<int> connection_count{0};
  17245. // Endpoint: returns 401 on first attempt, 200 on second
  17246. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17247. int conn = connection_count.fetch_add(1);
  17248. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17249. res.status = StatusCode::Unauthorized_401;
  17250. res.set_content("Unauthorized", "text/plain");
  17251. return;
  17252. }
  17253. res.set_chunked_content_provider(
  17254. "text/event-stream", [](size_t offset, DataSink &sink) {
  17255. if (offset == 0) {
  17256. std::string event = "data: authenticated\n\n";
  17257. sink.write(event.data(), event.size());
  17258. }
  17259. return false;
  17260. });
  17261. });
  17262. Client client("localhost", get_port());
  17263. Headers headers = {{"Authorization", "Bearer expired"}};
  17264. sse::SSEClient sse(client, "/auth-retry", headers);
  17265. std::atomic<bool> message_received{false};
  17266. // Refresh token on error
  17267. sse.on_error(
  17268. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17269. sse.on_message([&](const sse::SSEMessage &msg) {
  17270. if (msg.data == "authenticated") { message_received.store(true); }
  17271. });
  17272. sse.set_reconnect_interval(100);
  17273. sse.set_max_reconnect_attempts(3);
  17274. sse.start_async();
  17275. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17276. sse.stop();
  17277. // Should have reconnected after 401 and succeeded with new token
  17278. EXPECT_GE(connection_count.load(), 2);
  17279. EXPECT_TRUE(message_received.load());
  17280. }
  17281. TEST(Issue2318Test, EmptyHostString) {
  17282. {
  17283. httplib::Client cli_empty("", PORT);
  17284. auto res = cli_empty.Get("/");
  17285. ASSERT_FALSE(res);
  17286. EXPECT_EQ(httplib::Error::Connection, res.error());
  17287. }
  17288. {
  17289. httplib::Client cli(" ", PORT);
  17290. auto res = cli.Get("/");
  17291. ASSERT_FALSE(res);
  17292. EXPECT_EQ(httplib::Error::Connection, res.error());
  17293. }
  17294. }
  17295. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17296. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17297. Server svr;
  17298. // Set a small payload limit (1KB)
  17299. svr.set_payload_max_length(1024);
  17300. svr.Post("/test", [&](const Request &req, Response &res) {
  17301. res.set_content("Body size: " + std::to_string(req.body.size()),
  17302. "text/plain");
  17303. });
  17304. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17305. auto se = detail::scope_exit([&] {
  17306. svr.stop();
  17307. listen_thread.join();
  17308. });
  17309. svr.wait_until_ready();
  17310. // Create data that compresses well but exceeds limit when decompressed
  17311. // 8KB of repeated null bytes compresses to a very small size
  17312. std::string original_data(8 * 1024, '\0');
  17313. // Compress the data using gzip
  17314. std::string compressed_data;
  17315. detail::gzip_compressor compressor;
  17316. compressor.compress(original_data.data(), original_data.size(), true,
  17317. [&](const char *data, size_t size) {
  17318. compressed_data.append(data, size);
  17319. return true;
  17320. });
  17321. // Verify compression worked (compressed should be much smaller)
  17322. ASSERT_LT(compressed_data.size(), original_data.size());
  17323. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17324. // Send compressed data with Content-Encoding: gzip
  17325. Client cli(HOST, PORT);
  17326. Headers headers = {{"Content-Encoding", "gzip"}};
  17327. auto res =
  17328. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17329. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17331. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17332. }
  17333. #endif
  17334. // ============================================================================
  17335. // OpenSSL-Specific Tests
  17336. // ============================================================================
  17337. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17338. X509 *readCertificate(const std::string &strFileName) {
  17339. std::ifstream inStream(strFileName);
  17340. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17341. std::istreambuf_iterator<char>());
  17342. if (strCertPEM.empty()) return (nullptr);
  17343. BIO *pbCert = BIO_new(BIO_s_mem());
  17344. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17345. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17346. BIO_free(pbCert);
  17347. return (pCert);
  17348. }
  17349. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17350. std::ifstream inStream(strFileName);
  17351. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17352. std::istreambuf_iterator<char>());
  17353. if (strPrivateKeyPEM.empty()) return (nullptr);
  17354. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17355. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17356. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17357. BIO_free(pbPrivKey);
  17358. return (pPrivateKey);
  17359. }
  17360. TEST(BindServerTest, UpdateCerts) {
  17361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17362. int port = svr.bind_to_any_port("0.0.0.0");
  17363. ASSERT_TRUE(svr.is_valid());
  17364. ASSERT_TRUE(port > 0);
  17365. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17366. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17367. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17368. ASSERT_TRUE(cert != nullptr);
  17369. ASSERT_TRUE(ca_cert != nullptr);
  17370. ASSERT_TRUE(key != nullptr);
  17371. X509_STORE *cert_store = X509_STORE_new();
  17372. X509_STORE_add_cert(cert_store, ca_cert);
  17373. // svr.update_certs(cert, key, cert_store); // deprecated
  17374. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17375. CLIENT_CA_CERT_FILE);
  17376. ASSERT_TRUE(svr.is_valid());
  17377. svr.stop();
  17378. X509_STORE_free(cert_store);
  17379. X509_free(cert);
  17380. X509_free(ca_cert);
  17381. EVP_PKEY_free(key);
  17382. }
  17383. // Test that update_certs() updates client CA list correctly
  17384. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17385. // Start with file-based constructor
  17386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17387. ASSERT_TRUE(svr.is_valid());
  17388. // Initially no client CA list should be set
  17389. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17390. ASSERT_TRUE(ssl_ctx != nullptr);
  17391. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17392. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17393. EXPECT_EQ(0, count_before);
  17394. // Now update with client CA (PEM string)
  17395. std::string cert_pem, key_pem, ca_pem;
  17396. read_file(SERVER_CERT_FILE, cert_pem);
  17397. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17398. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17399. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17400. ASSERT_TRUE(svr.is_valid());
  17401. // Now client CA list should be set
  17402. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17403. ASSERT_TRUE(ca_list_after != nullptr);
  17404. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17405. }
  17406. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17407. // Test that the file-path SSLServer constructor properly sets the client CA
  17408. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17410. ASSERT_TRUE(svr.is_valid());
  17411. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17412. ASSERT_TRUE(ssl_ctx != nullptr);
  17413. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17414. ASSERT_TRUE(ca_list != nullptr);
  17415. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17416. }
  17417. #endif
  17418. // ============================================================================
  17419. // MbedTLS-Specific Tests
  17420. // ============================================================================
  17421. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17422. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17423. using namespace httplib::tls;
  17424. // Track if callback was invoked
  17425. bool callback_invoked = false;
  17426. // The callback receives void* ctx which is actually MbedTlsContext*
  17427. // We can access the mbedtls_ssl_config via the context
  17428. auto setup_callback = [&callback_invoked](void *ctx) {
  17429. callback_invoked = true;
  17430. // Cast to MbedTlsContext* to access the ssl config
  17431. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17432. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17433. // Use static variables to hold certificate data (simplified for test)
  17434. static mbedtls_x509_crt own_cert;
  17435. static mbedtls_pk_context own_key;
  17436. static mbedtls_x509_crt ca_chain;
  17437. static bool initialized = false;
  17438. if (!initialized) {
  17439. mbedtls_x509_crt_init(&own_cert);
  17440. mbedtls_pk_init(&own_key);
  17441. mbedtls_x509_crt_init(&ca_chain);
  17442. // Load server certificate
  17443. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17444. return false;
  17445. }
  17446. // Load server private key.
  17447. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17448. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17449. #if MBEDTLS_VERSION_MAJOR == 3
  17450. ,
  17451. mbedtls_ctr_drbg_random, nullptr
  17452. #endif
  17453. ) != 0) {
  17454. return false;
  17455. }
  17456. // Load CA chain for client verification
  17457. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17458. return false;
  17459. }
  17460. initialized = true;
  17461. }
  17462. // Configure the SSL config
  17463. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17464. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17465. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17466. // Set minimum TLS version using mbedTLS native API
  17467. #if MBEDTLS_VERSION_MAJOR >= 3
  17468. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17469. #else
  17470. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17471. MBEDTLS_SSL_MINOR_VERSION_3);
  17472. #endif
  17473. return true;
  17474. };
  17475. SSLServer svr(setup_callback);
  17476. ASSERT_TRUE(svr.is_valid());
  17477. ASSERT_TRUE(callback_invoked);
  17478. svr.Get("/test", [&](const Request &req, Response &res) {
  17479. res.set_content("test", "text/plain");
  17480. auto cert = req.peer_cert();
  17481. ASSERT_TRUE(static_cast<bool>(cert));
  17482. auto common_name = cert.subject_cn();
  17483. EXPECT_EQ("Common Name", common_name);
  17484. });
  17485. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17486. auto se = detail::scope_exit([&] {
  17487. svr.stop();
  17488. t.join();
  17489. ASSERT_FALSE(svr.is_running());
  17490. });
  17491. svr.wait_until_ready();
  17492. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17493. cli.enable_server_certificate_verification(false);
  17494. cli.set_connection_timeout(30);
  17495. auto res = cli.Get("/test");
  17496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17497. ASSERT_EQ(StatusCode::OK_200, res->status);
  17498. }
  17499. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17500. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17501. // keep-alive SSL session, which reads through that config in
  17502. // mbedtls_ssl_close_notify.
  17503. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17505. ASSERT_TRUE(svr.is_valid());
  17506. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17507. res.set_content("test", "text/plain");
  17508. });
  17509. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17510. auto se = detail::scope_exit([&] {
  17511. svr.stop();
  17512. t.join();
  17513. ASSERT_FALSE(svr.is_running());
  17514. });
  17515. svr.wait_until_ready();
  17516. {
  17517. SSLClient cli(HOST, PORT);
  17518. cli.enable_server_certificate_verification(false);
  17519. cli.set_keep_alive(true);
  17520. auto res = cli.Get("/test");
  17521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17522. ASSERT_EQ(StatusCode::OK_200, res->status);
  17523. // cli is destructed here with the keep-alive SSL session still open.
  17524. }
  17525. }
  17526. #endif
  17527. // WebSocket Tests
  17528. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17529. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17530. // defining the meaning of these bits has been negotiated.
  17531. auto make_frame = [](uint8_t first_byte) {
  17532. std::string frame;
  17533. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17534. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17535. frame += "Hello";
  17536. return frame;
  17537. };
  17538. // RSV1 set (0x40)
  17539. {
  17540. detail::BufferStream strm;
  17541. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17542. ws::Opcode opcode;
  17543. std::string payload;
  17544. bool fin;
  17545. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17546. false, 1024));
  17547. }
  17548. // RSV2 set (0x20)
  17549. {
  17550. detail::BufferStream strm;
  17551. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17552. ws::Opcode opcode;
  17553. std::string payload;
  17554. bool fin;
  17555. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17556. false, 1024));
  17557. }
  17558. // RSV3 set (0x10)
  17559. {
  17560. detail::BufferStream strm;
  17561. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17562. ws::Opcode opcode;
  17563. std::string payload;
  17564. bool fin;
  17565. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17566. false, 1024));
  17567. }
  17568. // No RSV bits set - should succeed
  17569. {
  17570. detail::BufferStream strm;
  17571. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17572. ws::Opcode opcode;
  17573. std::string payload;
  17574. bool fin;
  17575. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17576. false, 1024));
  17577. EXPECT_EQ(ws::Opcode::Text, opcode);
  17578. EXPECT_EQ("Hello", payload);
  17579. EXPECT_TRUE(fin);
  17580. }
  17581. }
  17582. TEST(WebSocketTest, ControlFrameValidation) {
  17583. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17584. // payload length <= 125.
  17585. // Ping with FIN=0 - must be rejected
  17586. {
  17587. detail::BufferStream strm;
  17588. std::string frame;
  17589. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17590. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17591. strm.write(frame.data(), frame.size());
  17592. ws::Opcode opcode;
  17593. std::string payload;
  17594. bool fin;
  17595. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17596. false, 1024));
  17597. }
  17598. // Close with FIN=0 - must be rejected
  17599. {
  17600. detail::BufferStream strm;
  17601. std::string frame;
  17602. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17603. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17604. strm.write(frame.data(), frame.size());
  17605. ws::Opcode opcode;
  17606. std::string payload;
  17607. bool fin;
  17608. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17609. false, 1024));
  17610. }
  17611. // Ping with payload_len=126 (extended length) - must be rejected
  17612. {
  17613. detail::BufferStream strm;
  17614. std::string frame;
  17615. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17616. frame += static_cast<char>(126); // payload_len=126 (>125)
  17617. frame += static_cast<char>(0x00); // extended length high byte
  17618. frame += static_cast<char>(126); // extended length low byte
  17619. frame += std::string(126, 'x');
  17620. strm.write(frame.data(), frame.size());
  17621. ws::Opcode opcode;
  17622. std::string payload;
  17623. bool fin;
  17624. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17625. false, 1024));
  17626. }
  17627. // Ping with FIN=1 and payload_len=125 - should succeed
  17628. {
  17629. detail::BufferStream strm;
  17630. std::string frame;
  17631. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17632. frame += static_cast<char>(125); // payload_len=125
  17633. frame += std::string(125, 'x');
  17634. strm.write(frame.data(), frame.size());
  17635. ws::Opcode opcode;
  17636. std::string payload;
  17637. bool fin;
  17638. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17639. false, 1024));
  17640. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17641. EXPECT_EQ(125u, payload.size());
  17642. EXPECT_TRUE(fin);
  17643. }
  17644. }
  17645. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17646. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17647. // length MUST be 0.
  17648. // MSB set - must be rejected
  17649. {
  17650. detail::BufferStream strm;
  17651. std::string frame;
  17652. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17653. frame += static_cast<char>(127); // 64-bit extended length
  17654. frame += static_cast<char>(0x80); // MSB set (invalid)
  17655. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17656. strm.write(frame.data(), frame.size());
  17657. ws::Opcode opcode;
  17658. std::string payload;
  17659. bool fin;
  17660. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17661. false, 1024));
  17662. }
  17663. // MSB clear - should pass length parsing (will be rejected by max_len,
  17664. // but that's a different check; use a small length to verify)
  17665. {
  17666. detail::BufferStream strm;
  17667. std::string frame;
  17668. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17669. frame += static_cast<char>(127); // 64-bit extended length
  17670. frame += std::string(7, '\0'); // high bytes = 0
  17671. frame += static_cast<char>(0x03); // length = 3
  17672. frame += "abc";
  17673. strm.write(frame.data(), frame.size());
  17674. ws::Opcode opcode;
  17675. std::string payload;
  17676. bool fin;
  17677. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17678. false, 1024));
  17679. EXPECT_EQ(ws::Opcode::Text, opcode);
  17680. EXPECT_EQ("abc", payload);
  17681. }
  17682. }
  17683. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17684. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17685. // Valid UTF-8
  17686. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17687. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17688. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17689. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17690. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17691. // Invalid UTF-8
  17692. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17693. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17694. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17695. EXPECT_FALSE(
  17696. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17697. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17698. }
  17699. TEST(WebSocketTest, ConnectAndDisconnect) {
  17700. Server svr;
  17701. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17702. std::string msg;
  17703. while (ws.read(msg)) {}
  17704. });
  17705. auto port = svr.bind_to_any_port(HOST);
  17706. std::thread t([&]() { svr.listen_after_bind(); });
  17707. svr.wait_until_ready();
  17708. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17709. auto res = client.connect();
  17710. ASSERT_TRUE(res);
  17711. EXPECT_EQ(Error::Success, res.error());
  17712. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17713. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17714. EXPECT_TRUE(client.is_open());
  17715. client.close();
  17716. EXPECT_FALSE(client.is_open());
  17717. svr.stop();
  17718. t.join();
  17719. }
  17720. TEST(WebSocketTest, ValidURL) {
  17721. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17722. EXPECT_TRUE(ws1.is_valid());
  17723. ws::WebSocketClient ws2("ws://example.com/path");
  17724. EXPECT_TRUE(ws2.is_valid());
  17725. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17726. EXPECT_TRUE(ws3.is_valid());
  17727. #ifdef CPPHTTPLIB_SSL_ENABLED
  17728. ws::WebSocketClient wss1("wss://example.com/path");
  17729. EXPECT_TRUE(wss1.is_valid());
  17730. ws::WebSocketClient wss2("wss://example.com:443/path");
  17731. EXPECT_TRUE(wss2.is_valid());
  17732. #endif
  17733. }
  17734. TEST(WebSocketTest, InvalidURL) {
  17735. // No scheme
  17736. ws::WebSocketClient ws1("localhost:8080/path");
  17737. EXPECT_FALSE(ws1.is_valid());
  17738. // No path
  17739. ws::WebSocketClient ws2("ws://localhost:8080");
  17740. EXPECT_FALSE(ws2.is_valid());
  17741. // Empty string
  17742. ws::WebSocketClient ws3("");
  17743. EXPECT_FALSE(ws3.is_valid());
  17744. // Missing host
  17745. ws::WebSocketClient ws4("ws://:8080/path");
  17746. EXPECT_FALSE(ws4.is_valid());
  17747. // Port number overflow — should not crash
  17748. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17749. EXPECT_FALSE(ws5.is_valid());
  17750. // Port out of range
  17751. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17752. EXPECT_FALSE(ws6.is_valid());
  17753. }
  17754. TEST(WebSocketTest, UnsupportedScheme) {
  17755. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17756. ws::WebSocketClient ws1("http://localhost:8080/path");
  17757. EXPECT_FALSE(ws1.is_valid());
  17758. ws::WebSocketClient ws2("https://localhost:8080/path");
  17759. EXPECT_FALSE(ws2.is_valid());
  17760. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17761. EXPECT_FALSE(ws3.is_valid());
  17762. #else
  17763. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17764. std::invalid_argument);
  17765. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17766. std::invalid_argument);
  17767. #endif
  17768. }
  17769. TEST(WebSocketTest, ConnectWhenInvalid) {
  17770. ws::WebSocketClient ws("not a valid url");
  17771. EXPECT_FALSE(ws.is_valid());
  17772. auto res = ws.connect();
  17773. EXPECT_FALSE(res);
  17774. EXPECT_EQ(Error::Connection, res.error());
  17775. EXPECT_EQ(-1, res.status());
  17776. }
  17777. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17778. // Grab a port that is free, then close it again so nothing listens there
  17779. Server svr;
  17780. auto port = svr.bind_to_any_port(HOST);
  17781. svr.stop();
  17782. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17783. auto res = client.connect();
  17784. ASSERT_FALSE(res);
  17785. EXPECT_EQ(Error::Connection, res.error());
  17786. EXPECT_EQ(-1, res.status());
  17787. }
  17788. TEST(WebSocketTest, DefaultPort) {
  17789. ws::WebSocketClient ws1("ws://example.com/path");
  17790. EXPECT_TRUE(ws1.is_valid());
  17791. // ws:// defaults to port 80 (verified by successful parse)
  17792. #ifdef CPPHTTPLIB_SSL_ENABLED
  17793. ws::WebSocketClient ws2("wss://example.com/path");
  17794. EXPECT_TRUE(ws2.is_valid());
  17795. // wss:// defaults to port 443 (verified by successful parse)
  17796. #endif
  17797. }
  17798. TEST(WebSocketTest, IPv6LiteralAddress) {
  17799. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17800. EXPECT_TRUE(ws1.is_valid());
  17801. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17802. EXPECT_TRUE(ws2.is_valid());
  17803. }
  17804. TEST(WebSocketTest, ComplexPath) {
  17805. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17806. EXPECT_TRUE(ws1.is_valid());
  17807. ws::WebSocketClient ws2("ws://localhost:8080/");
  17808. EXPECT_TRUE(ws2.is_valid());
  17809. }
  17810. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17811. Server svr;
  17812. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17813. std::string msg;
  17814. while (ws.read(msg)) {}
  17815. });
  17816. auto port = svr.bind_to_any_port(HOST);
  17817. std::thread t([&]() { svr.listen_after_bind(); });
  17818. svr.wait_until_ready();
  17819. auto another_host = "example.com";
  17820. auto wrong_ip = "192.0.2.1";
  17821. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17822. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17823. ASSERT_TRUE(client.connect());
  17824. EXPECT_TRUE(client.is_open());
  17825. client.close();
  17826. svr.stop();
  17827. t.join();
  17828. }
  17829. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17830. Server svr;
  17831. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17832. std::string msg;
  17833. while (ws.read(msg)) {}
  17834. });
  17835. auto port = svr.bind_to_any_port(HOST);
  17836. std::thread t([&]() { svr.listen_after_bind(); });
  17837. svr.wait_until_ready();
  17838. auto wrong_ip = "192.0.2.1";
  17839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17840. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17841. client.set_connection_timeout(1);
  17842. client.set_read_timeout(1);
  17843. client.set_write_timeout(1);
  17844. EXPECT_FALSE(client.connect());
  17845. EXPECT_FALSE(client.is_open());
  17846. svr.stop();
  17847. t.join();
  17848. }
  17849. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17850. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17851. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17852. // (RFC 6761) is only a map key and the Host header value.
  17853. auto host = "target.invalid";
  17854. Server svr;
  17855. std::string received_host;
  17856. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17857. received_host = req.get_header_value("Host");
  17858. std::string msg;
  17859. while (ws.read(msg)) {}
  17860. });
  17861. auto port = svr.bind_to_any_port(HOST);
  17862. std::thread t([&]() { svr.listen_after_bind(); });
  17863. // ASSERT_* below returns from the test body, which would leave t joinable
  17864. // and make ~thread call std::terminate.
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. if (t.joinable()) { t.join(); }
  17868. });
  17869. svr.wait_until_ready();
  17870. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17871. std::to_string(port) + "/ws");
  17872. client.set_hostname_addr_map({{host, HOST}});
  17873. ASSERT_TRUE(client.connect());
  17874. EXPECT_TRUE(client.is_open());
  17875. client.close();
  17876. svr.stop();
  17877. t.join();
  17878. // The mapping only redirects the connection; the identity stays host_.
  17879. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17880. }
  17881. class WebSocketIntegrationTest : public ::testing::Test {
  17882. protected:
  17883. void SetUp() override {
  17884. server_ = httplib::detail::make_unique<Server>();
  17885. setup_server();
  17886. start_server();
  17887. }
  17888. void TearDown() override {
  17889. server_->stop();
  17890. if (server_thread_.joinable()) { server_thread_.join(); }
  17891. }
  17892. void setup_server() {
  17893. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17894. std::string msg;
  17895. ws::ReadResult ret;
  17896. while ((ret = ws.read(msg))) {
  17897. if (ret == ws::Binary) {
  17898. ws.send(msg.data(), msg.size());
  17899. } else {
  17900. ws.send(msg);
  17901. }
  17902. }
  17903. });
  17904. server_->WebSocket("/ws-echo-string",
  17905. [](const Request &, ws::WebSocket &ws) {
  17906. std::string msg;
  17907. while (ws.read(msg)) {
  17908. ws.send("echo: " + msg);
  17909. }
  17910. });
  17911. server_->WebSocket(
  17912. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17913. // Echo back request metadata
  17914. ws.send("path:" + req.path);
  17915. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17916. std::string msg;
  17917. while (ws.read(msg)) {}
  17918. });
  17919. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17920. std::string msg;
  17921. ws.read(msg); // wait for a message
  17922. ws.close();
  17923. });
  17924. server_->WebSocket("/ws-close-status",
  17925. [](const Request &, ws::WebSocket &ws) {
  17926. std::string msg;
  17927. ws.read(msg); // wait for a message
  17928. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17929. });
  17930. server_->WebSocket(
  17931. "/ws-subprotocol",
  17932. [](const Request &, ws::WebSocket &ws) {
  17933. std::string msg;
  17934. while (ws.read(msg)) {
  17935. ws.send(msg);
  17936. }
  17937. },
  17938. [](const std::vector<std::string> &protocols) -> std::string {
  17939. for (const auto &p : protocols) {
  17940. if (p == "graphql-ws") { return p; }
  17941. }
  17942. return "";
  17943. });
  17944. }
  17945. void start_server() {
  17946. port_ = server_->bind_to_any_port(HOST);
  17947. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17948. server_->wait_until_ready();
  17949. }
  17950. std::unique_ptr<Server> server_;
  17951. std::thread server_thread_;
  17952. int port_ = 0;
  17953. };
  17954. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17956. "/ws-echo");
  17957. ASSERT_TRUE(client.connect());
  17958. ASSERT_TRUE(client.is_open());
  17959. ASSERT_TRUE(client.send("Hello WebSocket"));
  17960. std::string msg;
  17961. EXPECT_EQ(ws::Text, client.read(msg));
  17962. EXPECT_EQ("Hello WebSocket", msg);
  17963. client.close();
  17964. }
  17965. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17966. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17967. "/ws-echo");
  17968. ASSERT_TRUE(client.connect());
  17969. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17970. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17971. std::string msg;
  17972. EXPECT_EQ(ws::Binary, client.read(msg));
  17973. EXPECT_EQ(binary_data, msg);
  17974. client.close();
  17975. }
  17976. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17978. "/ws-echo");
  17979. ASSERT_TRUE(client.connect());
  17980. for (int i = 0; i < 10; i++) {
  17981. auto text = "message " + std::to_string(i);
  17982. ASSERT_TRUE(client.send(text));
  17983. std::string msg;
  17984. ASSERT_TRUE(client.read(msg));
  17985. EXPECT_EQ(text, msg);
  17986. }
  17987. client.close();
  17988. }
  17989. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17991. "/ws-close");
  17992. ASSERT_TRUE(client.connect());
  17993. // Send a message to trigger the server to close
  17994. ASSERT_TRUE(client.send("trigger close"));
  17995. // The server will close, so read should return false
  17996. std::string msg;
  17997. EXPECT_FALSE(client.read(msg));
  17998. EXPECT_FALSE(client.is_open());
  17999. }
  18000. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18002. "/ws-echo");
  18003. ASSERT_TRUE(client.connect());
  18004. // 128KB message
  18005. std::string large_data(128 * 1024, 'X');
  18006. ASSERT_TRUE(client.send(large_data));
  18007. std::string msg;
  18008. ASSERT_TRUE(client.read(msg));
  18009. EXPECT_EQ(large_data, msg);
  18010. client.close();
  18011. }
  18012. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18014. "/ws-echo");
  18015. ASSERT_TRUE(client.connect());
  18016. const int num_threads = 4;
  18017. std::vector<std::thread> threads;
  18018. std::atomic<int> send_count{0};
  18019. for (int t = 0; t < num_threads; t++) {
  18020. threads.emplace_back([&client, &send_count, t]() {
  18021. for (int i = 0; i < 5; i++) {
  18022. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18023. if (client.send(text)) { send_count++; }
  18024. }
  18025. });
  18026. }
  18027. for (auto &th : threads) {
  18028. th.join();
  18029. }
  18030. int received = 0;
  18031. std::string msg;
  18032. while (received < send_count.load()) {
  18033. if (!client.read(msg)) { break; }
  18034. received++;
  18035. }
  18036. EXPECT_EQ(send_count.load(), received);
  18037. client.close();
  18038. }
  18039. TEST_F(WebSocketIntegrationTest, ReadString) {
  18040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18041. "/ws-echo-string");
  18042. ASSERT_TRUE(client.connect());
  18043. ASSERT_TRUE(client.send("hello"));
  18044. std::string msg;
  18045. ASSERT_TRUE(client.read(msg));
  18046. EXPECT_EQ("echo: hello", msg);
  18047. ASSERT_TRUE(client.send("world"));
  18048. ASSERT_TRUE(client.read(msg));
  18049. EXPECT_EQ("echo: world", msg);
  18050. client.close();
  18051. }
  18052. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18053. Headers headers = {{"X-Test-Header", "test-value"}};
  18054. ws::WebSocketClient client(
  18055. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18056. ASSERT_TRUE(client.connect());
  18057. std::string msg;
  18058. ASSERT_TRUE(client.read(msg));
  18059. EXPECT_EQ("path:/ws-request-info", msg);
  18060. ASSERT_TRUE(client.read(msg));
  18061. EXPECT_EQ("header:test-value", msg);
  18062. client.close();
  18063. }
  18064. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18065. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18066. "/ws-echo");
  18067. client.set_read_timeout(1, 0); // 1 second
  18068. ASSERT_TRUE(client.connect());
  18069. // Don't send anything — server echo handler waits for a message,
  18070. // so read() should time out and return false.
  18071. std::string msg;
  18072. EXPECT_FALSE(client.read(msg));
  18073. }
  18074. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18076. "/ws-echo");
  18077. client.set_read_timeout(5, 0);
  18078. ASSERT_TRUE(client.connect());
  18079. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18080. // The server should reject it and close the connection.
  18081. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18082. client.send(oversized);
  18083. // The server's read() should have failed due to payload limit,
  18084. // so our read() should return false (connection closed).
  18085. std::string msg;
  18086. EXPECT_FALSE(client.read(msg));
  18087. }
  18088. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18089. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18090. "/ws-echo");
  18091. client.set_read_timeout(10, 0);
  18092. ASSERT_TRUE(client.connect());
  18093. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18094. // This should succeed.
  18095. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18096. ASSERT_TRUE(client.send(at_limit));
  18097. std::string msg;
  18098. ASSERT_TRUE(client.read(msg));
  18099. EXPECT_EQ(at_limit.size(), msg.size());
  18100. client.close();
  18101. }
  18102. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18104. "/nonexistent");
  18105. auto res = client.connect();
  18106. EXPECT_FALSE(res);
  18107. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18108. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18109. EXPECT_FALSE(client.is_open());
  18110. }
  18111. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18112. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18113. "/ws-echo");
  18114. ASSERT_TRUE(client.connect());
  18115. ASSERT_TRUE(client.send(""));
  18116. std::string msg;
  18117. EXPECT_EQ(ws::Text, client.read(msg));
  18118. EXPECT_EQ("", msg);
  18119. client.close();
  18120. }
  18121. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18123. "/ws-echo");
  18124. // First connection
  18125. ASSERT_TRUE(client.connect());
  18126. ASSERT_TRUE(client.send("first"));
  18127. std::string msg;
  18128. ASSERT_TRUE(client.read(msg));
  18129. EXPECT_EQ("first", msg);
  18130. client.close();
  18131. EXPECT_FALSE(client.is_open());
  18132. // Reconnect using the same client object
  18133. ASSERT_TRUE(client.connect());
  18134. ASSERT_TRUE(client.is_open());
  18135. ASSERT_TRUE(client.send("second"));
  18136. ASSERT_TRUE(client.read(msg));
  18137. EXPECT_EQ("second", msg);
  18138. client.close();
  18139. }
  18140. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18141. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18142. "/ws-close-status");
  18143. ASSERT_TRUE(client.connect());
  18144. // Trigger the server to close with GoingAway status
  18145. ASSERT_TRUE(client.send("trigger"));
  18146. // read() should return false after receiving the close frame
  18147. std::string msg;
  18148. EXPECT_FALSE(client.read(msg));
  18149. EXPECT_FALSE(client.is_open());
  18150. }
  18151. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18152. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18153. "/ws-echo");
  18154. ASSERT_TRUE(client.connect());
  18155. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18156. EXPECT_FALSE(client.is_open());
  18157. }
  18158. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18159. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18160. ws::WebSocketClient client(
  18161. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18162. ASSERT_TRUE(client.connect());
  18163. // Server should have selected graphql-ws
  18164. EXPECT_EQ("graphql-ws", client.subprotocol());
  18165. client.close();
  18166. }
  18167. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18168. Headers headers;
  18169. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18170. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18171. ws::WebSocketClient client(
  18172. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18173. ASSERT_TRUE(client.connect());
  18174. // The offer on the second field line counts too, so graphql-ws is selected
  18175. EXPECT_EQ("graphql-ws", client.subprotocol());
  18176. client.close();
  18177. }
  18178. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18179. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18180. ws::WebSocketClient client(
  18181. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18182. ASSERT_TRUE(client.connect());
  18183. // Server should not have selected any subprotocol
  18184. EXPECT_TRUE(client.subprotocol().empty());
  18185. client.close();
  18186. }
  18187. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18188. // Connect without requesting any subprotocol
  18189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18190. "/ws-subprotocol");
  18191. ASSERT_TRUE(client.connect());
  18192. EXPECT_TRUE(client.subprotocol().empty());
  18193. client.close();
  18194. }
  18195. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18197. "/ws-echo");
  18198. client.set_tcp_nodelay(true);
  18199. client.set_connection_timeout(3, 0);
  18200. bool socket_options_called = false;
  18201. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18202. ASSERT_TRUE(client.connect());
  18203. ASSERT_TRUE(client.is_open());
  18204. EXPECT_TRUE(socket_options_called);
  18205. ASSERT_TRUE(client.send("hello"));
  18206. std::string msg;
  18207. auto result = client.read(msg);
  18208. EXPECT_EQ(result, ws::ReadResult::Text);
  18209. EXPECT_EQ(msg, "hello");
  18210. client.close();
  18211. }
  18212. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18213. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18214. "/ws-echo");
  18215. client.set_connection_timeout(std::chrono::seconds(3));
  18216. client.set_write_timeout(std::chrono::seconds(3));
  18217. // A sub-second remainder exercises the seconds/microseconds split.
  18218. client.set_read_timeout(std::chrono::milliseconds(1500));
  18219. ASSERT_TRUE(client.connect());
  18220. auto start = std::chrono::steady_clock::now();
  18221. std::string msg;
  18222. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18223. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18224. std::chrono::steady_clock::now() - start)
  18225. .count();
  18226. // Above 1s so that dropping the microseconds half of the split fails here,
  18227. // and well under the 300s default so that ignoring the setter fails too.
  18228. EXPECT_GE(elapsed, 1400);
  18229. EXPECT_LT(elapsed, 30000);
  18230. }
  18231. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18232. Server svr;
  18233. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18234. if (!req.has_header("Authorization")) {
  18235. res.status = StatusCode::Unauthorized_401;
  18236. res.set_content("Unauthorized", "text/plain");
  18237. return Server::HandlerResponse::Handled;
  18238. }
  18239. return Server::HandlerResponse::Unhandled;
  18240. });
  18241. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18242. std::string msg;
  18243. while (ws.read(msg)) {
  18244. ws.send(msg);
  18245. }
  18246. });
  18247. auto port = svr.bind_to_any_port("localhost");
  18248. std::thread t([&]() { svr.listen_after_bind(); });
  18249. svr.wait_until_ready();
  18250. // Without Authorization header - should be rejected before upgrade
  18251. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18252. EXPECT_FALSE(client1.connect());
  18253. // With Authorization header - should succeed
  18254. Headers headers = {{"Authorization", "Bearer token123"}};
  18255. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18256. headers);
  18257. ASSERT_TRUE(client2.connect());
  18258. ASSERT_TRUE(client2.send("hello"));
  18259. std::string msg;
  18260. ASSERT_TRUE(client2.read(msg));
  18261. EXPECT_EQ("hello", msg);
  18262. client2.close();
  18263. svr.stop();
  18264. t.join();
  18265. }
  18266. TEST(WebSocketTest, QueryStringInHandshake) {
  18267. Server svr;
  18268. std::mutex mtx;
  18269. std::string received_target;
  18270. std::string received_token;
  18271. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18272. {
  18273. std::lock_guard<std::mutex> lock(mtx);
  18274. received_target = req.target;
  18275. if (req.has_param("token")) {
  18276. received_token = req.get_param_value("token");
  18277. }
  18278. }
  18279. std::string msg;
  18280. while (ws.read(msg)) {
  18281. ws.send(msg);
  18282. }
  18283. });
  18284. auto port = svr.bind_to_any_port("localhost");
  18285. std::thread t([&]() { svr.listen_after_bind(); });
  18286. svr.wait_until_ready();
  18287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18288. "/ws?token=ABC&session=123");
  18289. ASSERT_TRUE(client.connect());
  18290. // Round-trip ensures the handler has run and captured the request.
  18291. ASSERT_TRUE(client.send("hello"));
  18292. std::string msg;
  18293. ASSERT_TRUE(client.read(msg));
  18294. EXPECT_EQ("hello", msg);
  18295. client.close();
  18296. {
  18297. std::lock_guard<std::mutex> lock(mtx);
  18298. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18299. EXPECT_EQ("ABC", received_token);
  18300. }
  18301. svr.stop();
  18302. t.join();
  18303. }
  18304. // Run a handshake against a throwaway server and hand the request the server
  18305. // received back to the caller, so tests can assert on the headers the client
  18306. // actually put on the wire.
  18307. static void capture_websocket_handshake_request(
  18308. const Headers &client_headers,
  18309. std::function<void(const Request &, int port)> verify) {
  18310. Server svr;
  18311. std::mutex mtx;
  18312. Request received;
  18313. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18314. {
  18315. std::lock_guard<std::mutex> lock(mtx);
  18316. received = req;
  18317. }
  18318. std::string msg;
  18319. while (ws.read(msg)) {
  18320. ws.send(msg);
  18321. }
  18322. });
  18323. auto port = svr.bind_to_any_port("localhost");
  18324. std::thread t([&]() { svr.listen_after_bind(); });
  18325. auto se = detail::scope_exit([&] {
  18326. svr.stop();
  18327. t.join();
  18328. });
  18329. svr.wait_until_ready();
  18330. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18331. client_headers);
  18332. ASSERT_TRUE(client.connect());
  18333. ASSERT_TRUE(client.send("hello"));
  18334. std::string msg;
  18335. ASSERT_TRUE(client.read(msg));
  18336. client.close();
  18337. {
  18338. std::lock_guard<std::mutex> lock(mtx);
  18339. verify(received, port);
  18340. }
  18341. }
  18342. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18343. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18344. // Non-default port must be present in the Host header. Default ports
  18345. // (80/443) are omitted; that logic is covered by
  18346. // MakeHostAndPortStringTest.
  18347. EXPECT_EQ("localhost:" + std::to_string(port),
  18348. req.get_header_value("Host"));
  18349. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18350. req.get_header_value("User-Agent"));
  18351. EXPECT_FALSE(req.has_header("Accept"));
  18352. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18353. EXPECT_FALSE(req.has_header("Content-Length"));
  18354. });
  18355. }
  18356. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18357. capture_websocket_handshake_request(
  18358. {{"Host", "example.com"},
  18359. {"User-Agent", "custom-agent"},
  18360. {"X-Custom", "value"}},
  18361. [](const Request &req, int) {
  18362. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18363. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18364. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18365. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18366. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18367. });
  18368. }
  18369. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18370. capture_websocket_handshake_request(
  18371. {{"Upgrade", "bogus"},
  18372. {"Connection", "close"},
  18373. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18374. {"Sec-WebSocket-Version", "8"}},
  18375. [](const Request &req, int) {
  18376. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18377. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18378. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18379. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18380. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18381. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18382. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18383. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18384. req.get_header_value("Sec-WebSocket-Key"));
  18385. });
  18386. }
  18387. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18388. // A header the client refuses to send must abort the handshake before any
  18389. // part of it reaches the wire; a lone request line would otherwise sit in
  18390. // the peer's buffer as a truncated request.
  18391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18392. ASSERT_NE(INVALID_SOCKET, srv);
  18393. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18394. sockaddr_in addr{};
  18395. addr.sin_family = AF_INET;
  18396. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18398. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18399. ASSERT_EQ(0, ::listen(srv, 1));
  18400. sockaddr_in bound{};
  18401. socklen_t bound_len = sizeof(bound);
  18402. ASSERT_EQ(
  18403. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18404. auto port = ntohs(bound.sin_port);
  18405. ssize_t received = -1;
  18406. std::thread t([&] {
  18407. // Bound every blocking call so a regression fails the test with a bad
  18408. // value instead of hanging the suite.
  18409. fd_set rfds;
  18410. FD_ZERO(&rfds);
  18411. FD_SET(srv, &rfds);
  18412. timeval tv{5, 0};
  18413. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18414. 0) {
  18415. return;
  18416. }
  18417. sockaddr_in cli_addr{};
  18418. socklen_t cli_len = sizeof(cli_addr);
  18419. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18420. if (cli == INVALID_SOCKET) { return; }
  18421. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18422. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18423. char buf[4096];
  18424. received = ::recv(cli, buf, sizeof(buf), 0);
  18425. });
  18426. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18427. // connect() has already shut the socket down by the time it returns false,
  18428. // so the peer sees EOF without waiting for the client to be destroyed.
  18429. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18430. {{"X-Bad", "a\r\nInjected: 1"}});
  18431. EXPECT_FALSE(client.connect());
  18432. t.join();
  18433. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18434. EXPECT_EQ(0, received);
  18435. }
  18436. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18437. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18438. // contains "upgrade" as a substring is a different token and must not
  18439. // start a WebSocket handshake.
  18440. auto make_request = [](const std::vector<std::string> &connection_values) {
  18441. Request req;
  18442. req.method = "GET";
  18443. req.headers.emplace("Upgrade", "websocket");
  18444. for (const auto &value : connection_values) {
  18445. req.headers.emplace("Connection", value);
  18446. }
  18447. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18448. req.headers.emplace("Sec-WebSocket-Version", "13");
  18449. return req;
  18450. };
  18451. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18452. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18453. EXPECT_TRUE(
  18454. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18455. EXPECT_TRUE(
  18456. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18457. EXPECT_TRUE(
  18458. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18459. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18460. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18461. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18462. EXPECT_FALSE(
  18463. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18464. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18465. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18466. }
  18467. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18468. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18469. // asks recipients to match each protocol-name case-insensitively, and RFC
  18470. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18471. // client naming websocket alongside another protocol, or on a second field
  18472. // line, is offering websocket; a value that merely contains "websocket" as a
  18473. // substring is a different protocol name and is not.
  18474. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18475. Request req;
  18476. req.method = "GET";
  18477. for (const auto &value : upgrade_values) {
  18478. req.headers.emplace("Upgrade", value);
  18479. }
  18480. req.headers.emplace("Connection", "Upgrade");
  18481. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18482. req.headers.emplace("Sec-WebSocket-Version", "13");
  18483. return req;
  18484. };
  18485. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18486. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18487. EXPECT_TRUE(
  18488. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18489. EXPECT_TRUE(
  18490. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18491. EXPECT_TRUE(
  18492. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18493. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18494. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18495. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18496. EXPECT_FALSE(
  18497. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18498. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18499. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18500. }
  18501. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18502. Server svr;
  18503. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18504. auto port = svr.bind_to_any_port("localhost");
  18505. std::thread t([&]() { svr.listen_after_bind(); });
  18506. auto se = detail::scope_exit([&] {
  18507. svr.stop();
  18508. t.join();
  18509. });
  18510. svr.wait_until_ready();
  18511. Headers headers = {{"Upgrade", "websocket"},
  18512. {"Connection", "notupgrade"},
  18513. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18514. {"Sec-WebSocket-Version", "13"}};
  18515. Client cli("localhost", port);
  18516. auto res = cli.Get("/ws", headers);
  18517. // The route exists only as a WebSocket route, so a request that fails the
  18518. // handshake check falls through to ordinary routing.
  18519. ASSERT_TRUE(res);
  18520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18521. }
  18522. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18523. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18524. // Connection value is the only thing left for the client to reject.
  18525. Server svr;
  18526. svr.Get("/ws", [](const Request &req, Response &res) {
  18527. res.status = StatusCode::SwitchingProtocol_101;
  18528. res.set_header("Upgrade", "websocket");
  18529. res.set_header("Connection", "notupgrade");
  18530. res.set_header("Sec-WebSocket-Accept",
  18531. detail::websocket_accept_key(
  18532. req.get_header_value("Sec-WebSocket-Key")));
  18533. });
  18534. auto port = svr.bind_to_any_port("localhost");
  18535. std::thread t([&]() { svr.listen_after_bind(); });
  18536. auto se = detail::scope_exit([&] {
  18537. svr.stop();
  18538. t.join();
  18539. });
  18540. svr.wait_until_ready();
  18541. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18542. auto res = client.connect();
  18543. EXPECT_FALSE(res);
  18544. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18545. EXPECT_FALSE(client.is_open());
  18546. }
  18547. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18548. // The socket path doubles as the URL host, so it must not contain '/'.
  18549. const char *shard = getenv("GTEST_SHARD_INDEX");
  18550. const std::string sock_path =
  18551. shard ? std::string("httplib-ws-") + shard + ".sock"
  18552. : std::string("httplib-ws.sock");
  18553. std::remove(sock_path.c_str());
  18554. Server svr;
  18555. std::mutex mtx;
  18556. std::string received_host;
  18557. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18558. {
  18559. std::lock_guard<std::mutex> lock(mtx);
  18560. received_host = req.get_header_value("Host");
  18561. }
  18562. std::string msg;
  18563. while (ws.read(msg)) {
  18564. ws.send(msg);
  18565. }
  18566. });
  18567. svr.set_address_family(AF_UNIX);
  18568. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18569. auto se = detail::scope_exit([&] {
  18570. svr.stop();
  18571. t.join();
  18572. std::remove(sock_path.c_str());
  18573. });
  18574. svr.wait_until_ready();
  18575. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18576. client.set_address_family(AF_UNIX);
  18577. ASSERT_TRUE(client.connect());
  18578. ASSERT_TRUE(client.send("hello"));
  18579. std::string msg;
  18580. ASSERT_TRUE(client.read(msg));
  18581. client.close();
  18582. {
  18583. std::lock_guard<std::mutex> lock(mtx);
  18584. // There is no host:port for a Unix socket, so the same "localhost"
  18585. // placeholder the HTTP client uses is expected.
  18586. EXPECT_EQ("localhost", received_host);
  18587. }
  18588. }
  18589. // Two threads must never parse WebSocket frames from the same stream.
  18590. // close() used to read the peer's Close reply with its own frame read, so it
  18591. // raced a reader thread that was in the middle of a payload: the payload loop
  18592. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18593. // so bytes taken by close() were replaced with bytes from further along the
  18594. // stream. The message kept its length and silently changed content.
  18595. //
  18596. // The raw peer below sends a frame header plus part of the payload, waits for
  18597. // the handler to call close(), and only then sends the rest. Whichever thread
  18598. // would win the race for those bytes, the message must arrive intact, because
  18599. // close() must not touch the stream while read() owns it.
  18600. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18601. #ifndef _WIN32
  18602. signal(SIGPIPE, SIG_IGN);
  18603. #endif
  18604. const size_t payload_len = 120; // fits the 7-bit length field
  18605. const size_t prefix_len = 8;
  18606. const int attempts = 8;
  18607. std::string expected(payload_len, '\0');
  18608. for (size_t i = 0; i < payload_len; i++) {
  18609. expected[i] = static_cast<char>('a' + i % 26);
  18610. }
  18611. std::atomic<bool> peer_stalled{false};
  18612. std::atomic<bool> handler_done{false};
  18613. std::mutex received_mutex;
  18614. std::vector<std::string> received;
  18615. // Bound every wait, so a regression fails the test instead of hanging the
  18616. // suite.
  18617. auto wait_for = [](const std::atomic<bool> &flag) {
  18618. for (int i = 0; i < 500 && !flag; i++) {
  18619. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18620. }
  18621. };
  18622. Server svr;
  18623. svr.set_websocket_ping_interval(0);
  18624. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18625. std::thread reader([&]() {
  18626. std::string msg;
  18627. while (ws.read(msg)) {
  18628. std::lock_guard<std::mutex> guard(received_mutex);
  18629. received.push_back(msg);
  18630. }
  18631. });
  18632. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18633. // inside read_websocket_frame() when close() runs.
  18634. wait_for(peer_stalled);
  18635. ws.close();
  18636. reader.join();
  18637. handler_done = true;
  18638. });
  18639. auto port = svr.bind_to_any_port("127.0.0.1");
  18640. std::thread t([&]() { svr.listen_after_bind(); });
  18641. auto se = detail::scope_exit([&] {
  18642. svr.stop();
  18643. t.join();
  18644. });
  18645. svr.wait_until_ready();
  18646. auto send_bytes = [](socket_t s, const std::string &data) {
  18647. #ifdef _WIN32
  18648. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18649. #else
  18650. auto n = ::send(s, data.data(), data.size(), 0);
  18651. #endif
  18652. return n == static_cast<decltype(n)>(data.size());
  18653. };
  18654. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18655. // Every length used here fits the 7-bit length field.
  18656. auto masked_header = [](uint8_t first_byte, size_t len) {
  18657. std::string h;
  18658. h += static_cast<char>(first_byte);
  18659. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18660. h.append(4, '\0'); // mask key
  18661. return h;
  18662. };
  18663. for (int attempt = 0; attempt < attempts; attempt++) {
  18664. peer_stalled = false;
  18665. handler_done = false;
  18666. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18667. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18668. auto se_sock = detail::scope_exit([&] {
  18669. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18670. });
  18671. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18672. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18673. sockaddr_in addr{};
  18674. addr.sin_family = AF_INET;
  18675. addr.sin_port = htons(static_cast<uint16_t>(port));
  18676. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18677. ASSERT_EQ(
  18678. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18679. << "attempt " << attempt;
  18680. ASSERT_TRUE(send_bytes(sock,
  18681. "GET /ws HTTP/1.1\r\n"
  18682. "Host: 127.0.0.1\r\n"
  18683. "Upgrade: websocket\r\n"
  18684. "Connection: Upgrade\r\n"
  18685. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18686. "Sec-WebSocket-Version: 13\r\n"
  18687. "\r\n"))
  18688. << "attempt " << attempt;
  18689. std::string response;
  18690. while (response.find("\r\n\r\n") == std::string::npos) {
  18691. char buf[512];
  18692. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18693. if (n <= 0) { break; }
  18694. response.append(buf, static_cast<size_t>(n));
  18695. }
  18696. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18697. << "attempt " << attempt;
  18698. // Send the header of a Binary message but only the first prefix_len bytes
  18699. // of its payload, leaving the reader thread stalled inside the payload.
  18700. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18701. expected.substr(0, prefix_len)))
  18702. << "attempt " << attempt;
  18703. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18704. peer_stalled = true;
  18705. // Let close() send its Close frame and park in its own read before the
  18706. // rest of the payload arrives, so both threads are waiting for it.
  18707. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18708. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18709. close_frame += static_cast<char>(0x03); // status 1000
  18710. close_frame += static_cast<char>(0xE8);
  18711. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18712. << "attempt " << attempt;
  18713. // Closing the peer releases the reader thread even on the buggy path,
  18714. // where it waits for bytes another thread already consumed.
  18715. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18716. detail::close_socket(sock);
  18717. sock = INVALID_SOCKET;
  18718. wait_for(handler_done);
  18719. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18720. }
  18721. std::lock_guard<std::mutex> guard(received_mutex);
  18722. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18723. << "a message in flight when close() ran was dropped";
  18724. for (size_t i = 0; i < received.size(); i++) {
  18725. EXPECT_EQ(expected, received[i]) << "message " << i;
  18726. }
  18727. }
  18728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18729. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18730. protected:
  18731. void SetUp() override {
  18732. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18733. SERVER_PRIVATE_KEY_FILE);
  18734. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18735. std::string msg;
  18736. ws::ReadResult ret;
  18737. while ((ret = ws.read(msg))) {
  18738. if (ret == ws::Binary) {
  18739. ws.send(msg.data(), msg.size());
  18740. } else {
  18741. ws.send(msg);
  18742. }
  18743. }
  18744. });
  18745. port_ = server_->bind_to_any_port(HOST);
  18746. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18747. server_->wait_until_ready();
  18748. }
  18749. void TearDown() override {
  18750. server_->stop();
  18751. if (server_thread_.joinable()) { server_thread_.join(); }
  18752. }
  18753. std::unique_ptr<SSLServer> server_;
  18754. std::thread server_thread_;
  18755. int port_ = 0;
  18756. };
  18757. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18758. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18759. "/ws-echo");
  18760. client.enable_server_certificate_verification(false);
  18761. ASSERT_TRUE(client.connect());
  18762. ASSERT_TRUE(client.is_open());
  18763. ASSERT_TRUE(client.send("Hello WSS"));
  18764. std::string msg;
  18765. EXPECT_EQ(ws::Text, client.read(msg));
  18766. EXPECT_EQ("Hello WSS", msg);
  18767. client.close();
  18768. }
  18769. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18770. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18771. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18772. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18773. // client (without calling close() first) is the only path that runs
  18774. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18775. // bug exactly.
  18776. //
  18777. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18778. // when linked against an instrumented libssl; run under Valgrind to catch it
  18779. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18780. // suite (the freed session otherwise stalls on the close handshake) — this test
  18781. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18782. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18783. {
  18784. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18785. "/ws-echo");
  18786. client.enable_server_certificate_verification(false);
  18787. client.set_read_timeout(2, 0);
  18788. client.set_write_timeout(2, 0);
  18789. ASSERT_TRUE(client.connect());
  18790. ASSERT_TRUE(client.is_open());
  18791. ASSERT_TRUE(client.send("still open"));
  18792. // Intentionally do NOT call client.close(): leaving scope runs
  18793. // shutdown_and_close() with the WebSocket still open, which must send the
  18794. // close frame while the TLS session is still alive.
  18795. }
  18796. }
  18797. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18798. // shutdown_and_close() at the start of connect(), reproducing the same
  18799. // use-after-free within the test body rather than at scope exit. The second
  18800. // connect must succeed and echo, proving the close handshake ran over a live
  18801. // session. See the note above about memory-tool requirements.
  18802. TEST_F(WebSocketSSLIntegrationTest,
  18803. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18804. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18805. "/ws-echo");
  18806. client.enable_server_certificate_verification(false);
  18807. client.set_read_timeout(2, 0);
  18808. client.set_write_timeout(2, 0);
  18809. ASSERT_TRUE(client.connect());
  18810. ASSERT_TRUE(client.is_open());
  18811. ASSERT_TRUE(client.send("still open"));
  18812. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18813. // the still-open connection, which must not touch a freed TLS session.
  18814. ASSERT_TRUE(client.connect());
  18815. ASSERT_TRUE(client.is_open());
  18816. ASSERT_TRUE(client.send("after reconnect"));
  18817. std::string msg;
  18818. EXPECT_EQ(ws::Text, client.read(msg));
  18819. EXPECT_EQ("after reconnect", msg);
  18820. client.close();
  18821. }
  18822. #endif
  18823. #ifdef CPPHTTPLIB_SSL_ENABLED
  18824. class WebSocketSSLCATest : public ::testing::Test {
  18825. protected:
  18826. void SetUp() override {
  18827. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18828. SERVER_PRIVATE_KEY_FILE);
  18829. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18830. std::string msg;
  18831. while (ws.read(msg)) {
  18832. ws.send(msg);
  18833. }
  18834. });
  18835. port_ = server_->bind_to_any_port("127.0.0.1");
  18836. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18837. server_->wait_until_ready();
  18838. }
  18839. void TearDown() override {
  18840. server_->stop();
  18841. if (server_thread_.joinable()) { server_thread_.join(); }
  18842. }
  18843. std::string url() const {
  18844. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18845. }
  18846. std::unique_ptr<SSLServer> server_;
  18847. std::thread server_thread_;
  18848. int port_ = 0;
  18849. };
  18850. // A custom CA loaded as PEM verifies the server with full certificate
  18851. // verification enabled
  18852. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18853. ws::WebSocketClient client(url());
  18854. std::string cert;
  18855. read_file(SERVER_CERT2_FILE, cert);
  18856. client.load_ca_cert_store(cert.c_str(), cert.size());
  18857. ASSERT_TRUE(client.connect());
  18858. ASSERT_TRUE(client.send("hello"));
  18859. std::string msg;
  18860. EXPECT_EQ(ws::Text, client.read(msg));
  18861. EXPECT_EQ("hello", msg);
  18862. client.close();
  18863. }
  18864. // A custom CA that does not cover the server must fail verification (the
  18865. // custom CA is exclusive; system certs are not loaded alongside it)
  18866. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18867. ws::WebSocketClient client(url());
  18868. std::string cert;
  18869. read_file(CLIENT_CA_CERT_FILE, cert);
  18870. client.load_ca_cert_store(cert.c_str(), cert.size());
  18871. auto res = client.connect();
  18872. ASSERT_FALSE(res);
  18873. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18874. EXPECT_EQ(-1, res.status());
  18875. EXPECT_NE(0u, res.ssl_backend_error());
  18876. }
  18877. // The same CA as a file path rather than PEM in memory
  18878. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18879. ws::WebSocketClient client(url());
  18880. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18881. ASSERT_TRUE(client.connect());
  18882. ASSERT_TRUE(client.send("hello"));
  18883. std::string msg;
  18884. EXPECT_EQ(ws::Text, client.read(msg));
  18885. EXPECT_EQ("hello", msg);
  18886. client.close();
  18887. }
  18888. // ...and a CA file that does not cover the server still fails, so it is the
  18889. // path above that decides the outcome
  18890. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18891. ws::WebSocketClient client(url());
  18892. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18893. ASSERT_FALSE(client.connect());
  18894. }
  18895. // Regression test: reconnecting with a native custom CA store used to reuse
  18896. // a store handle the previous TLS context had already freed (use-after-free
  18897. // under the OpenSSL backend). The context now lives as long as the client.
  18898. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18899. ws::WebSocketClient client(url());
  18900. std::string cert;
  18901. read_file(SERVER_CERT2_FILE, cert);
  18902. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18903. ASSERT_TRUE(client.connect());
  18904. client.close();
  18905. ASSERT_TRUE(client.connect());
  18906. ASSERT_TRUE(client.send("again"));
  18907. std::string msg;
  18908. EXPECT_EQ(ws::Text, client.read(msg));
  18909. EXPECT_EQ("again", msg);
  18910. client.close();
  18911. }
  18912. // Regression test: a certificate with a trusted chain but no identity match
  18913. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18914. // verification entirely for IP hosts, so this connection succeeded there.
  18915. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18916. // chain verification while the identity check must still fail.
  18917. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18919. ASSERT_TRUE(svr.is_valid());
  18920. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18921. std::string msg;
  18922. while (ws.read(msg)) {
  18923. ws.send(msg);
  18924. }
  18925. });
  18926. auto port = svr.bind_to_any_port("127.0.0.1");
  18927. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18928. auto se = detail::scope_exit([&] {
  18929. svr.stop();
  18930. t.join();
  18931. });
  18932. svr.wait_until_ready();
  18933. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18934. "/echo");
  18935. std::string cert;
  18936. read_file(SERVER_CERT_FILE, cert);
  18937. client.load_ca_cert_store(cert.c_str(), cert.size());
  18938. ASSERT_FALSE(client.connect());
  18939. }
  18940. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18941. // SNI, so nothing binds the host name to the TLS session. These bind the
  18942. // server to "localhost" instead, the only shape that exercises the SNI and
  18943. // hostname-verification path with certificate verification left enabled.
  18944. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18945. protected:
  18946. void Start(const char *cert_file) {
  18947. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18948. SERVER_PRIVATE_KEY_FILE);
  18949. ASSERT_TRUE(server_->is_valid());
  18950. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18951. std::string msg;
  18952. while (ws.read(msg)) {
  18953. ws.send(msg);
  18954. }
  18955. });
  18956. port_ = server_->bind_to_any_port("localhost");
  18957. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18958. server_->wait_until_ready();
  18959. }
  18960. void TearDown() override {
  18961. if (server_) { server_->stop(); }
  18962. if (server_thread_.joinable()) { server_thread_.join(); }
  18963. }
  18964. std::string url() const {
  18965. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18966. }
  18967. std::unique_ptr<SSLServer> server_;
  18968. std::thread server_thread_;
  18969. int port_ = 0;
  18970. };
  18971. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18972. // out and the connection is usable
  18973. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18974. Start(SERVER_CERT2_FILE);
  18975. ws::WebSocketClient client(url());
  18976. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18977. ASSERT_TRUE(client.connect());
  18978. ASSERT_TRUE(client.send("hello"));
  18979. std::string msg;
  18980. EXPECT_EQ(ws::Text, client.read(msg));
  18981. EXPECT_EQ("hello", msg);
  18982. client.close();
  18983. }
  18984. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18985. // while the identity check must still reject "localhost"
  18986. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18987. Start(SERVER_CERT_FILE);
  18988. ws::WebSocketClient client(url());
  18989. client.set_ca_cert_path(SERVER_CERT_FILE);
  18990. auto res = client.connect();
  18991. ASSERT_FALSE(res);
  18992. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18993. EXPECT_EQ(-1, res.status());
  18994. }
  18995. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18996. // disabled: the chain is still checked, only the identity check is skipped
  18997. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18998. Start(SERVER_CERT_FILE);
  18999. ws::WebSocketClient client(url());
  19000. client.set_ca_cert_path(SERVER_CERT_FILE);
  19001. client.enable_server_hostname_verification(false);
  19002. ASSERT_TRUE(client.connect());
  19003. ASSERT_TRUE(client.send("hello"));
  19004. std::string msg;
  19005. EXPECT_EQ(ws::Text, client.read(msg));
  19006. EXPECT_EQ("hello", msg);
  19007. client.close();
  19008. }
  19009. // A CA that did not sign the server certificate fails the chain, even though
  19010. // the name would match
  19011. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19012. Start(SERVER_CERT2_FILE);
  19013. ws::WebSocketClient client(url());
  19014. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19015. ASSERT_FALSE(client.connect());
  19016. }
  19017. // With verification disabled, neither the chain nor the name is checked
  19018. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19019. Start(SERVER_CERT_FILE);
  19020. ws::WebSocketClient client(url());
  19021. client.enable_server_certificate_verification(false);
  19022. ASSERT_TRUE(client.connect());
  19023. ASSERT_TRUE(client.send("hello"));
  19024. std::string msg;
  19025. EXPECT_EQ(ws::Text, client.read(msg));
  19026. EXPECT_EQ("hello", msg);
  19027. client.close();
  19028. }
  19029. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19030. protected:
  19031. void SetUp() override {
  19032. server_ = httplib::detail::make_unique<SSLServer>(
  19033. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19034. ASSERT_TRUE(server_->is_valid());
  19035. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19036. std::string msg;
  19037. while (ws.read(msg)) {
  19038. ws.send(msg);
  19039. }
  19040. });
  19041. port_ = server_->bind_to_any_port("localhost");
  19042. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19043. server_->wait_until_ready();
  19044. }
  19045. void TearDown() override {
  19046. server_->stop();
  19047. if (server_thread_.joinable()) { server_thread_.join(); }
  19048. }
  19049. std::string url() const {
  19050. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19051. }
  19052. void ConnectWithClientCert(const std::string &client_cert_file,
  19053. const std::string &client_private_key_file,
  19054. const char *private_key_password) {
  19055. std::string cert_pem, key_pem;
  19056. read_file(client_cert_file, cert_pem);
  19057. read_file(client_private_key_file, key_pem);
  19058. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19059. key_pem.c_str(), key_pem.size(),
  19060. private_key_password};
  19061. ws::WebSocketClient client(url(), pem);
  19062. ASSERT_TRUE(client.is_valid());
  19063. client.enable_server_certificate_verification(false);
  19064. ASSERT_TRUE(client.connect());
  19065. ASSERT_TRUE(client.send("hello"));
  19066. std::string msg;
  19067. EXPECT_EQ(ws::Text, client.read(msg));
  19068. EXPECT_EQ("hello", msg);
  19069. client.close();
  19070. }
  19071. std::unique_ptr<SSLServer> server_;
  19072. std::thread server_thread_;
  19073. int port_ = 0;
  19074. };
  19075. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19076. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19077. }
  19078. // Control for the tests above: the fixture's server really does require a
  19079. // client certificate, so it is the PEM the constructor installed that decides
  19080. // the outcome.
  19081. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19082. ws::WebSocketClient client(url());
  19083. ASSERT_TRUE(client.is_valid());
  19084. client.enable_server_certificate_verification(false);
  19085. EXPECT_FALSE(client.connect());
  19086. }
  19087. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19088. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19089. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19090. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19091. }
  19092. #endif
  19093. #if !defined(_WIN32)
  19094. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19095. auto secret_dir = std::string("./symlink_test_secret");
  19096. auto served_dir = std::string("./symlink_test_served");
  19097. auto secret_file = secret_dir + "/secret.txt";
  19098. auto symlink_path = served_dir + "/escape";
  19099. // Setup: create directories and files
  19100. mkdir(secret_dir.c_str(), 0755);
  19101. mkdir(served_dir.c_str(), 0755);
  19102. {
  19103. std::ofstream ofs(secret_file);
  19104. ofs << "SECRET_DATA";
  19105. }
  19106. // Create symlink using absolute path so it resolves correctly
  19107. #ifdef PATH_MAX
  19108. char abs_secret[PATH_MAX];
  19109. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19110. #else
  19111. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19112. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19113. ASSERT_NE(nullptr, abs_secret);
  19114. #endif
  19115. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19116. auto se = detail::scope_exit([&] {
  19117. unlink(symlink_path.c_str());
  19118. unlink(secret_file.c_str());
  19119. rmdir(served_dir.c_str());
  19120. rmdir(secret_dir.c_str());
  19121. });
  19122. Server svr;
  19123. svr.set_mount_point("/", served_dir);
  19124. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19125. auto se2 = detail::scope_exit([&] {
  19126. svr.stop();
  19127. listen_thread.join();
  19128. });
  19129. svr.wait_until_ready();
  19130. Client cli("localhost", PORT);
  19131. // Symlink pointing outside base dir should be blocked
  19132. auto res = cli.Get("/escape/secret.txt");
  19133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19134. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19135. }
  19136. #endif
  19137. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19138. // A GET request with Content-Length to a static file handler must have its
  19139. // body drained before the keep-alive connection is reused. Otherwise the
  19140. // unread body bytes are interpreted as the next HTTP request.
  19141. //
  19142. // The body is sent AFTER receiving the first response (as in the original
  19143. // PoC) so that the stream_line_reader cannot buffer it together with the
  19144. // headers of the first request.
  19145. Server svr;
  19146. svr.set_mount_point("/", "./www");
  19147. std::atomic<int> smuggled_count(0);
  19148. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19149. smuggled_count++;
  19150. res.set_content("oops", "text/plain");
  19151. });
  19152. auto port = svr.bind_to_any_port("localhost");
  19153. thread t = thread([&] { svr.listen_after_bind(); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. });
  19158. svr.wait_until_ready();
  19159. auto error = Error::Success;
  19160. auto sock = detail::create_client_socket(
  19161. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19162. /*connection_timeout_sec=*/2, 0,
  19163. /*read_timeout_sec=*/2, 0,
  19164. /*write_timeout_sec=*/2, 0, std::string(), error);
  19165. ASSERT_NE(INVALID_SOCKET, sock);
  19166. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19167. // The "smuggled" request will be sent as the body of the outer GET
  19168. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19169. "Host: localhost\r\n"
  19170. "Connection: close\r\n"
  19171. "\r\n";
  19172. // Step 1: Send only the outer request headers (no body yet)
  19173. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19174. "Host: localhost\r\n"
  19175. "Content-Length: " +
  19176. std::to_string(smuggled.size()) +
  19177. "\r\n"
  19178. "\r\n";
  19179. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19180. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19181. // Step 2: Read the first response (server serves file without reading body)
  19182. std::string first_response;
  19183. char buf[4096];
  19184. for (;;) {
  19185. auto n = recv(sock, buf, sizeof(buf), 0);
  19186. if (n <= 0) break;
  19187. first_response.append(buf, static_cast<size_t>(n));
  19188. // Stop once we have a complete response (headers + body)
  19189. auto hdr_end = first_response.find("\r\n\r\n");
  19190. if (hdr_end != std::string::npos) {
  19191. // Check for Content-Length to know when the body is complete
  19192. auto cl_pos = first_response.find("Content-Length:");
  19193. if (cl_pos != std::string::npos) {
  19194. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19195. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19196. auto cl = std::stoul(
  19197. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19198. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19199. } else {
  19200. break; // No Content-Length, assume headers-only response
  19201. }
  19202. }
  19203. }
  19204. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19205. // Step 3: Now send the body, which looks like a new HTTP request.
  19206. // On a vulnerable server the keep-alive loop reads this as a second request.
  19207. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19208. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19209. // Step 4: Try to read a second response (should NOT exist after fix)
  19210. std::string second_response;
  19211. for (;;) {
  19212. auto n = recv(sock, buf, sizeof(buf), 0);
  19213. if (n <= 0) break;
  19214. second_response.append(buf, static_cast<size_t>(n));
  19215. }
  19216. // The smuggled request must NOT have been processed
  19217. EXPECT_EQ(0, smuggled_count.load());
  19218. }
  19219. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19220. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19221. // must be rejected with 400 Bad Request.
  19222. Server svr;
  19223. svr.Post("/test", [&](const Request &, Response &res) {
  19224. res.set_content("ok", "text/plain");
  19225. });
  19226. thread t = thread([&] { svr.listen(HOST, PORT); });
  19227. auto se = detail::scope_exit([&] {
  19228. svr.stop();
  19229. t.join();
  19230. ASSERT_FALSE(svr.is_running());
  19231. });
  19232. svr.wait_until_ready();
  19233. // Exact "chunked"
  19234. {
  19235. auto req = "POST /test HTTP/1.1\r\n"
  19236. "Host: localhost\r\n"
  19237. "Content-Length: 5\r\n"
  19238. "Transfer-Encoding: chunked\r\n"
  19239. "Connection: close\r\n"
  19240. "\r\n"
  19241. "hello";
  19242. std::string response;
  19243. ASSERT_TRUE(send_request(1, req, &response));
  19244. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19245. response.substr(0, response.find("\r\n")));
  19246. }
  19247. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19248. {
  19249. auto req = "POST /test HTTP/1.1\r\n"
  19250. "Host: localhost\r\n"
  19251. "Content-Length: 5\r\n"
  19252. "Transfer-Encoding: gzip, chunked\r\n"
  19253. "Connection: close\r\n"
  19254. "\r\n"
  19255. "hello";
  19256. std::string response;
  19257. ASSERT_TRUE(send_request(1, req, &response));
  19258. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19259. response.substr(0, response.find("\r\n")));
  19260. }
  19261. }
  19262. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19263. Server svr;
  19264. svr.Post("/test", [&](const Request &, Response &res) {
  19265. res.set_content("ok", "text/plain");
  19266. });
  19267. thread t = thread([&] { svr.listen(HOST, PORT); });
  19268. auto se = detail::scope_exit([&] {
  19269. svr.stop();
  19270. t.join();
  19271. ASSERT_FALSE(svr.is_running());
  19272. });
  19273. svr.wait_until_ready();
  19274. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19275. // length cannot be determined, so the server must answer 400 and close
  19276. // rather than treat the request as bodyless and leave the body in the
  19277. // socket for the next request to pick up.
  19278. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19279. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19280. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19281. std::string response;
  19282. ASSERT_TRUE(send_request(1, req, &response));
  19283. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19284. response.substr(0, response.find("\r\n")))
  19285. << transfer_encoding;
  19286. }
  19287. // RFC 9110 5.3: the codings may also be split across several
  19288. // Transfer-Encoding lines, which combine in the order they were received.
  19289. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19290. // just like the single-line "chunked, gzip" above.
  19291. {
  19292. auto req = "POST /test HTTP/1.1\r\n"
  19293. "Host: localhost\r\n"
  19294. "Transfer-Encoding: chunked\r\n"
  19295. "Transfer-Encoding: gzip\r\n"
  19296. "\r\n"
  19297. "0\r\n\r\n";
  19298. std::string response;
  19299. ASSERT_TRUE(send_request(1, req, &response));
  19300. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19301. response.substr(0, response.find("\r\n")));
  19302. }
  19303. // A sequence ending in chunked stays valid.
  19304. auto req = "POST /test HTTP/1.1\r\n"
  19305. "Host: localhost\r\n"
  19306. "Transfer-Encoding: gzip, chunked\r\n"
  19307. "Connection: close\r\n"
  19308. "\r\n"
  19309. "0\r\n\r\n";
  19310. std::string response;
  19311. ASSERT_TRUE(send_request(1, req, &response));
  19312. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19313. // ...including when it is spread over several lines.
  19314. auto split_req = "POST /test HTTP/1.1\r\n"
  19315. "Host: localhost\r\n"
  19316. "Transfer-Encoding: gzip\r\n"
  19317. "Transfer-Encoding: chunked\r\n"
  19318. "Connection: close\r\n"
  19319. "\r\n"
  19320. "0\r\n\r\n";
  19321. std::string split_response;
  19322. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19323. EXPECT_EQ("HTTP/1.1 200 OK",
  19324. split_response.substr(0, split_response.find("\r\n")));
  19325. }
  19326. // Regression for issue #2450: a DELETE without Content-Length on a
  19327. // keep-alive connection must not let the post-response drain consume the
  19328. // next request's bytes.
  19329. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19330. Server svr;
  19331. std::atomic<int> delete_count(0);
  19332. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19333. delete_count++;
  19334. res.status = StatusCode::NoContent_204;
  19335. });
  19336. auto port = svr.bind_to_any_port(HOST);
  19337. thread t = thread([&] { svr.listen_after_bind(); });
  19338. auto se = detail::scope_exit([&] {
  19339. svr.stop();
  19340. t.join();
  19341. });
  19342. svr.wait_until_ready();
  19343. auto error = Error::Success;
  19344. auto sock = detail::create_client_socket(
  19345. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19346. /*connection_timeout_sec=*/2, 0,
  19347. /*read_timeout_sec=*/2, 0,
  19348. /*write_timeout_sec=*/2, 0, std::string(), error);
  19349. ASSERT_NE(INVALID_SOCKET, sock);
  19350. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19351. auto send_request_and_read_response = [&](const std::string &req,
  19352. std::string &out) -> bool {
  19353. auto sent = send(sock, req.data(), req.size(), 0);
  19354. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19355. char buf[4096];
  19356. for (;;) {
  19357. auto n = recv(sock, buf, sizeof(buf), 0);
  19358. if (n <= 0) { return !out.empty(); }
  19359. out.append(buf, static_cast<size_t>(n));
  19360. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19361. }
  19362. };
  19363. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19364. "Host: localhost\r\n"
  19365. "\r\n";
  19366. std::string resp1;
  19367. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19368. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19369. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19370. "Host: localhost\r\n"
  19371. "Connection: close\r\n"
  19372. "\r\n";
  19373. std::string resp2;
  19374. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19375. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19376. EXPECT_EQ(2, delete_count.load());
  19377. }
  19378. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19379. Server svr;
  19380. svr.Post("/ingest", [&](const Request &, Response &res,
  19381. const ContentReader &content_reader) {
  19382. auto consumed = content_reader([](const char *, size_t) { return false; });
  19383. EXPECT_FALSE(consumed);
  19384. res.status = StatusCode::Conflict_409;
  19385. res.set_header("Connection", "close");
  19386. });
  19387. auto port = svr.bind_to_any_port(HOST);
  19388. thread t = thread([&] { svr.listen_after_bind(); });
  19389. auto se = detail::scope_exit([&] {
  19390. svr.stop();
  19391. t.join();
  19392. });
  19393. svr.wait_until_ready();
  19394. auto error = Error::Success;
  19395. auto sock = detail::create_client_socket(
  19396. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19397. /*connection_timeout_sec=*/2, 0,
  19398. /*read_timeout_sec=*/1, 0,
  19399. /*write_timeout_sec=*/2, 0, std::string(), error);
  19400. ASSERT_NE(INVALID_SOCKET, sock);
  19401. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19402. std::string request = "POST /ingest HTTP/1.1\r\n"
  19403. "Host: localhost\r\n"
  19404. "Transfer-Encoding: chunked\r\n"
  19405. "\r\n"
  19406. "4\r\n"
  19407. "data\r\n";
  19408. auto sent = send(sock, request.data(), request.size(), 0);
  19409. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19410. std::string response;
  19411. ssize_t received = 0;
  19412. do {
  19413. char buf[4096];
  19414. received = recv(sock, buf, sizeof(buf), 0);
  19415. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19416. } while (received > 0);
  19417. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19418. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19419. EXPECT_EQ(0, received);
  19420. }
  19421. namespace no_proxy_test {
  19422. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19423. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19424. // calling listen().
  19425. class ScopedServer {
  19426. public:
  19427. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19428. ~ScopedServer() {
  19429. svr_.stop();
  19430. if (th_.joinable()) { th_.join(); }
  19431. }
  19432. Server &svr() { return svr_; }
  19433. int port() const { return port_; }
  19434. void listen() {
  19435. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19436. svr_.wait_until_ready();
  19437. }
  19438. private:
  19439. Server svr_;
  19440. std::thread th_;
  19441. int port_ = 0;
  19442. };
  19443. class ProxyAndTargetServers {
  19444. public:
  19445. ProxyAndTargetServers() {
  19446. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19447. proxy_hits_++;
  19448. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19449. res.set_content("via-proxy", "text/plain");
  19450. });
  19451. target_.Get(".*", [this](const Request &req, Response &res) {
  19452. target_hits_++;
  19453. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19454. res.set_content("direct", "text/plain");
  19455. });
  19456. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19457. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19458. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19459. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19460. proxy_mock_.wait_until_ready();
  19461. target_.wait_until_ready();
  19462. }
  19463. ~ProxyAndTargetServers() {
  19464. proxy_mock_.stop();
  19465. target_.stop();
  19466. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19467. if (target_thread_.joinable()) { target_thread_.join(); }
  19468. }
  19469. Server &proxy_mock() { return proxy_mock_; }
  19470. Server &target() { return target_; }
  19471. int proxy_port() const { return proxy_port_; }
  19472. int target_port() const { return target_port_; }
  19473. int proxy_hits() const { return proxy_hits_.load(); }
  19474. int target_hits() const { return target_hits_.load(); }
  19475. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19476. void reset_counters() {
  19477. proxy_hits_ = 0;
  19478. target_hits_ = 0;
  19479. last_had_proxy_authz_ = false;
  19480. }
  19481. private:
  19482. Server proxy_mock_;
  19483. Server target_;
  19484. std::thread proxy_thread_;
  19485. std::thread target_thread_;
  19486. int proxy_port_ = 0;
  19487. int target_port_ = 0;
  19488. std::atomic<int> proxy_hits_{0};
  19489. std::atomic<int> target_hits_{0};
  19490. std::atomic<bool> last_had_proxy_authz_{false};
  19491. };
  19492. inline std::unique_ptr<Client> make_client(const std::string &host,
  19493. ProxyAndTargetServers &s) {
  19494. auto cli = detail::make_unique<Client>(host, s.target_port());
  19495. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19496. cli->set_proxy("127.0.0.1", s.proxy_port());
  19497. return cli;
  19498. }
  19499. } // namespace no_proxy_test
  19500. using no_proxy_test::make_client;
  19501. using no_proxy_test::ProxyAndTargetServers;
  19502. TEST(NoProxyTest, ExactHostnameBypasses) {
  19503. ProxyAndTargetServers s;
  19504. auto cli = make_client("example.com", s);
  19505. cli->set_no_proxy({"example.com"});
  19506. auto res = cli->Get("/");
  19507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19508. EXPECT_EQ(0, s.proxy_hits());
  19509. EXPECT_EQ(1, s.target_hits());
  19510. }
  19511. TEST(NoProxyTest, SubdomainBypasses) {
  19512. ProxyAndTargetServers s;
  19513. auto cli = make_client("foo.example.com", s);
  19514. cli->set_no_proxy({"example.com"});
  19515. auto res = cli->Get("/");
  19516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19517. EXPECT_EQ(0, s.proxy_hits());
  19518. EXPECT_EQ(1, s.target_hits());
  19519. }
  19520. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19521. // Regression guard: "evilexample.com" must not be considered a subdomain
  19522. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19523. // check would let traffic bypass the proxy and leak credentials direct
  19524. // to the attacker host.
  19525. ProxyAndTargetServers s;
  19526. auto cli = make_client("evilexample.com", s);
  19527. cli->set_no_proxy({"example.com"});
  19528. auto res = cli->Get("/");
  19529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19530. EXPECT_GE(s.proxy_hits(), 1);
  19531. EXPECT_EQ(0, s.target_hits());
  19532. }
  19533. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19534. ProxyAndTargetServers s;
  19535. auto cli = make_client("example.com.evil.com", s);
  19536. cli->set_no_proxy({"example.com"});
  19537. auto res = cli->Get("/");
  19538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19539. EXPECT_GE(s.proxy_hits(), 1);
  19540. EXPECT_EQ(0, s.target_hits());
  19541. }
  19542. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19543. ProxyAndTargetServers s;
  19544. auto cli = make_client("example.com", s);
  19545. cli->set_no_proxy({".example.com"});
  19546. auto res = cli->Get("/");
  19547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19548. EXPECT_EQ(0, s.proxy_hits());
  19549. EXPECT_EQ(1, s.target_hits());
  19550. }
  19551. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19552. ProxyAndTargetServers s;
  19553. auto cli = make_client("Example.COM", s);
  19554. cli->set_no_proxy({"EXAMPLE.com"});
  19555. auto res = cli->Get("/");
  19556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19557. EXPECT_EQ(0, s.proxy_hits());
  19558. EXPECT_EQ(1, s.target_hits());
  19559. }
  19560. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19561. ProxyAndTargetServers s;
  19562. auto cli = make_client("example.com.", s);
  19563. cli->set_no_proxy({"example.com"});
  19564. auto res = cli->Get("/");
  19565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19566. EXPECT_EQ(0, s.proxy_hits());
  19567. EXPECT_EQ(1, s.target_hits());
  19568. }
  19569. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19570. // Trailing dots must be normalized on BOTH sides — host and entry.
  19571. // An implementation that only strips the host-side trailing dot would
  19572. // fail to match host "example.com" against entry "example.com." because
  19573. // a literal substring search would compare 11 chars against 12.
  19574. ProxyAndTargetServers s;
  19575. auto cli = make_client("example.com", s);
  19576. cli->set_no_proxy({"example.com."});
  19577. auto res = cli->Get("/");
  19578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19579. EXPECT_EQ(0, s.proxy_hits());
  19580. EXPECT_EQ(1, s.target_hits());
  19581. }
  19582. TEST(NoProxyTest, WildcardBypassesEverything) {
  19583. ProxyAndTargetServers s;
  19584. auto cli = make_client("anything.invalid.test", s);
  19585. cli->set_no_proxy({"*"});
  19586. auto res = cli->Get("/");
  19587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19588. EXPECT_EQ(0, s.proxy_hits());
  19589. EXPECT_EQ(1, s.target_hits());
  19590. }
  19591. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19592. ProxyAndTargetServers s;
  19593. Client cli("127.0.0.1", s.target_port());
  19594. cli.set_proxy("127.0.0.1", s.proxy_port());
  19595. cli.set_no_proxy({"127.0.0.1"});
  19596. auto res = cli.Get("/");
  19597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19598. EXPECT_EQ(0, s.proxy_hits());
  19599. EXPECT_EQ(1, s.target_hits());
  19600. }
  19601. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19602. ProxyAndTargetServers s;
  19603. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19604. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19605. cli.set_proxy("127.0.0.1", s.proxy_port());
  19606. cli.set_no_proxy({"::1"});
  19607. auto res = cli.Get("/");
  19608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19609. EXPECT_EQ(0, s.proxy_hits());
  19610. EXPECT_EQ(1, s.target_hits());
  19611. }
  19612. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19613. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19614. // must still be recognized as IPv6 for CIDR matching. Implementations
  19615. // that detect IPv6 only when the host begins with '[' would parse the
  19616. // host as a hostname and miss the match.
  19617. ProxyAndTargetServers s;
  19618. Client cli("fe80::1", s.target_port());
  19619. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19620. cli.set_proxy("127.0.0.1", s.proxy_port());
  19621. cli.set_no_proxy({"fe80::/10"});
  19622. auto res = cli.Get("/");
  19623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19624. EXPECT_EQ(0, s.proxy_hits());
  19625. EXPECT_EQ(1, s.target_hits());
  19626. }
  19627. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19628. ProxyAndTargetServers s;
  19629. Client cli("::1", s.target_port());
  19630. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19631. cli.set_proxy("127.0.0.1", s.proxy_port());
  19632. cli.set_no_proxy({"[::1]"});
  19633. auto res = cli.Get("/");
  19634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19635. EXPECT_EQ(0, s.proxy_hits());
  19636. EXPECT_EQ(1, s.target_hits());
  19637. }
  19638. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19639. ProxyAndTargetServers s;
  19640. Client cli("fe80::1", s.target_port());
  19641. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19642. cli.set_proxy("127.0.0.1", s.proxy_port());
  19643. cli.set_no_proxy({"[fe80::]/10"});
  19644. auto res = cli.Get("/");
  19645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19646. EXPECT_EQ(0, s.proxy_hits());
  19647. EXPECT_EQ(1, s.target_hits());
  19648. }
  19649. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19650. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19651. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19652. // tricks via address-family conversion.
  19653. ProxyAndTargetServers s;
  19654. Client cli("::ffff:127.0.0.1", s.target_port());
  19655. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19656. cli.set_proxy("127.0.0.1", s.proxy_port());
  19657. cli.set_no_proxy({"127.0.0.1"});
  19658. auto res = cli.Get("/");
  19659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19660. EXPECT_GE(s.proxy_hits(), 1);
  19661. EXPECT_EQ(0, s.target_hits());
  19662. }
  19663. TEST(NoProxyTest, IPv4CidrMatch) {
  19664. ProxyAndTargetServers s;
  19665. Client cli("127.0.0.1", s.target_port());
  19666. cli.set_proxy("127.0.0.1", s.proxy_port());
  19667. cli.set_no_proxy({"127.0.0.0/8"});
  19668. auto res = cli.Get("/");
  19669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19670. EXPECT_EQ(0, s.proxy_hits());
  19671. EXPECT_EQ(1, s.target_hits());
  19672. }
  19673. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19674. ProxyAndTargetServers s;
  19675. Client cli("127.0.0.1", s.target_port());
  19676. cli.set_proxy("127.0.0.1", s.proxy_port());
  19677. cli.set_no_proxy({"10.0.0.0/8"});
  19678. auto res = cli.Get("/");
  19679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19680. EXPECT_GE(s.proxy_hits(), 1);
  19681. EXPECT_EQ(0, s.target_hits());
  19682. }
  19683. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19684. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19685. // IPv4 target matches.
  19686. ProxyAndTargetServers s;
  19687. Client cli("127.0.0.1", s.target_port());
  19688. cli.set_proxy("127.0.0.1", s.proxy_port());
  19689. cli.set_no_proxy({"0.0.0.0/0"});
  19690. auto res = cli.Get("/");
  19691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19692. EXPECT_EQ(0, s.proxy_hits());
  19693. EXPECT_EQ(1, s.target_hits());
  19694. }
  19695. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19696. ProxyAndTargetServers s;
  19697. Client cli("127.0.0.1", s.target_port());
  19698. cli.set_proxy("127.0.0.1", s.proxy_port());
  19699. cli.set_no_proxy({"127.0.0.1"});
  19700. auto res = cli.Get("/");
  19701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19702. EXPECT_EQ(0, s.proxy_hits());
  19703. EXPECT_EQ(1, s.target_hits());
  19704. }
  19705. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19706. ProxyAndTargetServers s;
  19707. Client cli("127.0.0.1", s.target_port());
  19708. cli.set_proxy("127.0.0.1", s.proxy_port());
  19709. cli.set_no_proxy({"127.0.0.0/33"});
  19710. auto res = cli.Get("/");
  19711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19712. EXPECT_GE(s.proxy_hits(), 1);
  19713. EXPECT_EQ(0, s.target_hits());
  19714. }
  19715. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19716. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19717. ProxyAndTargetServers s;
  19718. Client cli("127.0.0.1", s.target_port());
  19719. cli.set_proxy("127.0.0.1", s.proxy_port());
  19720. cli.set_no_proxy({"127.0.0.1/"});
  19721. auto res = cli.Get("/");
  19722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19723. EXPECT_GE(s.proxy_hits(), 1);
  19724. EXPECT_EQ(0, s.target_hits());
  19725. }
  19726. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19727. ProxyAndTargetServers s;
  19728. auto cli = make_client("internal.corp", s);
  19729. cli->set_proxy_basic_auth("u", "p");
  19730. cli->set_no_proxy({"internal.corp"});
  19731. auto res = cli->Get("/");
  19732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19733. EXPECT_EQ(1, s.target_hits());
  19734. EXPECT_EQ(0, s.proxy_hits());
  19735. EXPECT_FALSE(s.last_had_proxy_authz())
  19736. << "Proxy-Authorization must not be sent direct to the target";
  19737. }
  19738. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19739. ProxyAndTargetServers s;
  19740. auto cli = make_client("public.example", s);
  19741. cli->set_proxy_basic_auth("u", "p");
  19742. cli->set_no_proxy({"internal.corp"}); // does not match
  19743. auto res = cli->Get("/");
  19744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19745. EXPECT_GE(s.proxy_hits(), 1);
  19746. EXPECT_TRUE(s.last_had_proxy_authz());
  19747. }
  19748. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19749. ProxyAndTargetServers s;
  19750. auto cli = make_client("anything.test", s);
  19751. auto res = cli->Get("/");
  19752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19753. EXPECT_GE(s.proxy_hits(), 1);
  19754. EXPECT_EQ(0, s.target_hits());
  19755. }
  19756. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19757. ProxyAndTargetServers s;
  19758. auto cli = make_client("example.com", s);
  19759. cli->set_no_proxy({"example.com:8080"});
  19760. auto res = cli->Get("/");
  19761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19762. EXPECT_GE(s.proxy_hits(), 1);
  19763. EXPECT_EQ(0, s.target_hits());
  19764. }
  19765. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19766. ProxyAndTargetServers s;
  19767. auto cli = make_client("anything.test", s);
  19768. cli->set_no_proxy({"", " ", "\t"});
  19769. auto res = cli->Get("/");
  19770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19771. EXPECT_GE(s.proxy_hits(), 1);
  19772. EXPECT_EQ(0, s.target_hits());
  19773. }
  19774. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19775. // An entry with leading/trailing whitespace must still match — env-style
  19776. // values are commonly pasted with stray spaces and an implementation
  19777. // that feeds the raw token directly to inet_pton would fail to match
  19778. // valid CIDRs because of the spaces.
  19779. ProxyAndTargetServers s;
  19780. Client cli("127.0.0.1", s.target_port());
  19781. cli.set_proxy("127.0.0.1", s.proxy_port());
  19782. cli.set_no_proxy({" 127.0.0.0/8 "});
  19783. auto res = cli.Get("/");
  19784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19785. EXPECT_EQ(0, s.proxy_hits());
  19786. EXPECT_EQ(1, s.target_hits());
  19787. }
  19788. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19789. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19790. // go direct and must NOT carry Proxy-Authorization.
  19791. std::atomic<int> proxy_hits{0};
  19792. std::atomic<int> target_hits{0};
  19793. std::atomic<bool> target_saw_authz{false};
  19794. no_proxy_test::ScopedServer proxy_mock, target;
  19795. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19796. proxy_hits++;
  19797. res.status = 302;
  19798. res.set_header("Location", "http://127.0.0.1:" +
  19799. std::to_string(target.port()) + "/landed");
  19800. });
  19801. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19802. target_hits++;
  19803. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19804. res.set_content("direct", "text/plain");
  19805. });
  19806. proxy_mock.listen();
  19807. target.listen();
  19808. Client cli("public.example", target.port());
  19809. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19810. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19811. cli.set_proxy_basic_auth("u", "p");
  19812. cli.set_no_proxy({"127.0.0.1"});
  19813. cli.set_follow_location(true);
  19814. auto res = cli.Get("/redir");
  19815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19816. EXPECT_GE(proxy_hits.load(), 1);
  19817. EXPECT_GE(target_hits.load(), 1);
  19818. EXPECT_FALSE(target_saw_authz.load());
  19819. }
  19820. #ifdef CPPHTTPLIB_SSL_ENABLED
  19821. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19822. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19823. // proxy creds would be sent to the (possibly hostile) origin.
  19824. std::atomic<int> target_hits{0};
  19825. std::atomic<bool> target_saw_proxy_authz{false};
  19826. no_proxy_test::ScopedServer target;
  19827. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19828. target_hits++;
  19829. if (req.has_header("Proxy-Authorization")) {
  19830. target_saw_proxy_authz = true;
  19831. }
  19832. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19833. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19834. "nonce=\"abc\", algorithm=MD5");
  19835. });
  19836. target.listen();
  19837. // The proxy address is set to the target's port: the bypass MUST kick in;
  19838. // if it doesn't, the test still routes "via proxy" to the same server and
  19839. // the Proxy-Authorization assertion below catches the leak.
  19840. Client cli("evil.example", target.port());
  19841. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19842. cli.set_proxy("127.0.0.1", target.port());
  19843. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19844. cli.set_no_proxy({"evil.example"});
  19845. auto res = cli.Get("/x");
  19846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19847. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19848. EXPECT_EQ(1, target_hits.load());
  19849. EXPECT_FALSE(target_saw_proxy_authz.load());
  19850. }
  19851. #endif
  19852. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19853. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19854. std::atomic<int> proxy_hits{0};
  19855. std::atomic<int> bypass_hits{0};
  19856. std::atomic<bool> proxy_saw_c_url{false};
  19857. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19858. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19859. proxy_hits++;
  19860. if (req.path.find("/start") != std::string::npos) {
  19861. res.status = 302;
  19862. res.set_header("Location", "http://127.0.0.1:" +
  19863. std::to_string(bypass_server.port()) +
  19864. "/middle");
  19865. return;
  19866. }
  19867. if (req.path.find("/end") != std::string::npos) {
  19868. proxy_saw_c_url = true;
  19869. res.set_content("c-via-proxy", "text/plain");
  19870. return;
  19871. }
  19872. res.set_content("unexpected", "text/plain");
  19873. });
  19874. // public.example's "advertised" port is arbitrary (the request never lands
  19875. // there — it goes through the proxy), but use a dynamic value to stay
  19876. // friendly with sharded parallel runs.
  19877. int public_port = bypass_server.port();
  19878. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19879. bypass_hits++;
  19880. res.status = 302;
  19881. res.set_header("Location", "http://public.example:" +
  19882. std::to_string(public_port) + "/end");
  19883. });
  19884. proxy_mock.listen();
  19885. bypass_server.listen();
  19886. Client cli("public.example", public_port);
  19887. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19888. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19889. cli.set_no_proxy({"127.0.0.1"});
  19890. cli.set_follow_location(true);
  19891. auto res = cli.Get("/start");
  19892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19893. EXPECT_EQ(StatusCode::OK_200, res->status);
  19894. EXPECT_EQ("c-via-proxy", res->body);
  19895. EXPECT_GE(proxy_hits.load(), 2);
  19896. EXPECT_GE(bypass_hits.load(), 1);
  19897. EXPECT_TRUE(proxy_saw_c_url.load());
  19898. }
  19899. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19900. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19901. // request reconnects to the correct endpoint.
  19902. std::atomic<int> proxy_hits{0};
  19903. std::atomic<int> target_hits{0};
  19904. no_proxy_test::ScopedServer proxy_mock, target;
  19905. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19906. proxy_hits++;
  19907. res.set_content("via-proxy", "text/plain");
  19908. });
  19909. target.svr().Get(".*", [&](const Request &, Response &res) {
  19910. target_hits++;
  19911. res.set_content("direct", "text/plain");
  19912. });
  19913. proxy_mock.listen();
  19914. target.listen();
  19915. Client cli("public.example", target.port());
  19916. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19917. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19918. cli.set_keep_alive(true);
  19919. auto res1 = cli.Get("/a");
  19920. ASSERT_TRUE(res1);
  19921. EXPECT_EQ("via-proxy", res1->body);
  19922. EXPECT_EQ(1, proxy_hits.load());
  19923. EXPECT_EQ(0, target_hits.load());
  19924. cli.set_no_proxy({"public.example"});
  19925. auto res2 = cli.Get("/b");
  19926. ASSERT_TRUE(res2);
  19927. EXPECT_EQ("direct", res2->body);
  19928. EXPECT_EQ(1, proxy_hits.load());
  19929. EXPECT_EQ(1, target_hits.load());
  19930. }
  19931. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19932. namespace proxy_tunnel_test {
  19933. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19934. class ScopedSSLServer {
  19935. public:
  19936. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19937. port_ = svr_.bind_to_any_port("127.0.0.1");
  19938. }
  19939. ~ScopedSSLServer() {
  19940. svr_.stop();
  19941. if (th_.joinable()) { th_.join(); }
  19942. }
  19943. SSLServer &svr() { return svr_; }
  19944. int port() const { return port_; }
  19945. void listen() {
  19946. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19947. svr_.wait_until_ready();
  19948. }
  19949. private:
  19950. SSLServer svr_;
  19951. std::thread th_;
  19952. int port_ = 0;
  19953. };
  19954. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19955. class ScopedConnectProxy {
  19956. public:
  19957. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19958. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19959. if (listen_fd_ < 0) { return; }
  19960. int yes = 1;
  19961. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19962. sockaddr_in a{};
  19963. a.sin_family = AF_INET;
  19964. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19965. a.sin_port = 0;
  19966. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19967. return;
  19968. }
  19969. socklen_t alen = sizeof(a);
  19970. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19971. 0) {
  19972. return;
  19973. }
  19974. port_ = ntohs(a.sin_port);
  19975. if (::listen(listen_fd_, 1) != 0) { return; }
  19976. th_ = std::thread([this] { run(); });
  19977. }
  19978. ~ScopedConnectProxy() {
  19979. stop_ = true;
  19980. if (listen_fd_ >= 0) {
  19981. ::shutdown(listen_fd_, SHUT_RDWR);
  19982. ::close(listen_fd_);
  19983. }
  19984. if (th_.joinable()) { th_.join(); }
  19985. }
  19986. int port() const { return port_; }
  19987. int connect_hits() const { return connect_hits_.load(); }
  19988. private:
  19989. void run() {
  19990. while (!stop_.load()) {
  19991. fd_set rfds;
  19992. FD_ZERO(&rfds);
  19993. FD_SET(listen_fd_, &rfds);
  19994. timeval tv{0, 100 * 1000};
  19995. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19996. if (sel <= 0) { continue; }
  19997. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19998. if (client_fd < 0) { continue; }
  19999. std::string req;
  20000. char buf[2048];
  20001. while (req.find("\r\n\r\n") == std::string::npos) {
  20002. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20003. if (n <= 0) { break; }
  20004. req.append(buf, static_cast<size_t>(n));
  20005. }
  20006. if (req.compare(0, 7, "CONNECT") != 0) {
  20007. ::close(client_fd);
  20008. continue;
  20009. }
  20010. connect_hits_++;
  20011. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20012. ::send(client_fd, ok, std::strlen(ok), 0);
  20013. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20014. sockaddr_in o{};
  20015. o.sin_family = AF_INET;
  20016. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20017. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20018. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20019. 0) {
  20020. ::close(client_fd);
  20021. ::close(origin_fd);
  20022. continue;
  20023. }
  20024. auto forward = [](int from, int to) {
  20025. char b[8192];
  20026. for (;;) {
  20027. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20028. if (n <= 0) { break; }
  20029. ssize_t off = 0;
  20030. while (off < n) {
  20031. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20032. if (s <= 0) {
  20033. off = n;
  20034. break;
  20035. }
  20036. off += s;
  20037. }
  20038. }
  20039. ::shutdown(to, SHUT_WR);
  20040. };
  20041. std::thread t1([&] { forward(client_fd, origin_fd); });
  20042. std::thread t2([&] { forward(origin_fd, client_fd); });
  20043. t1.join();
  20044. t2.join();
  20045. ::close(client_fd);
  20046. ::close(origin_fd);
  20047. }
  20048. }
  20049. int forward_port_ = -1;
  20050. int listen_fd_ = -1;
  20051. int port_ = 0;
  20052. std::thread th_;
  20053. std::atomic<bool> stop_{false};
  20054. std::atomic<int> connect_hits_{0};
  20055. };
  20056. } // namespace proxy_tunnel_test
  20057. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20058. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20059. // retry; otherwise proxy creds would be sent to the origin.
  20060. std::atomic<int> origin_hits{0};
  20061. std::atomic<bool> origin_saw_proxy_authz{false};
  20062. proxy_tunnel_test::ScopedSSLServer origin;
  20063. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20064. origin_hits++;
  20065. if (req.has_header("Proxy-Authorization")) {
  20066. origin_saw_proxy_authz = true;
  20067. }
  20068. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20069. res.set_header("Proxy-Authenticate",
  20070. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20071. "algorithm=MD5");
  20072. });
  20073. origin.listen();
  20074. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20075. ASSERT_NE(0, proxy.port());
  20076. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20077. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20078. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20079. // and answer with its own status, making this test flaky.
  20080. SSLClient cli("127.0.0.1", origin.port());
  20081. cli.enable_server_certificate_verification(false);
  20082. cli.set_proxy("127.0.0.1", proxy.port());
  20083. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20084. auto res = cli.Get("/x");
  20085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20086. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20087. EXPECT_EQ(1, origin_hits.load());
  20088. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20089. EXPECT_EQ(1, proxy.connect_hits());
  20090. }
  20091. #endif