test.cc 770 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000
  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. "Content-Length: " +
  12958. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  12959. std::string response;
  12960. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  12961. ASSERT_GE(response.size(), 12u) << "no response";
  12962. EXPECT_EQ("200", response.substr(9, 3));
  12963. }
  12964. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  12965. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  12966. // ignored, including when it does not arrive in the same read as the
  12967. // close-delimiter itself.
  12968. expect_split_multipart_ok("--zzzz\r\n"
  12969. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12970. "\r\n"
  12971. "text1"
  12972. "\r\n--zzzz--",
  12973. "\r\nthis epilogue must be ignored\r\n");
  12974. }
  12975. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  12976. // The initial boundary may be preceded by a preamble of any length and may
  12977. // straddle a read boundary. Discarding data while waiting for it must not
  12978. // throw away a partial boundary sitting at the end of the buffer.
  12979. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  12980. "zz\r\n"
  12981. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12982. "\r\n"
  12983. "text1"
  12984. "\r\n--zzzz--\r\n");
  12985. }
  12986. TEST(MakeFileBodyTest, Basic) {
  12987. const std::string file_content(4096, 'Z');
  12988. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12989. {
  12990. std::ofstream ofs(tmp_path, std::ios::binary);
  12991. ofs.write(file_content.data(),
  12992. static_cast<std::streamsize>(file_content.size()));
  12993. }
  12994. auto handled = false;
  12995. Server svr;
  12996. svr.Post("/upload", [&](const Request &req, Response &res) {
  12997. EXPECT_EQ(file_content, req.body);
  12998. handled = true;
  12999. res.status = StatusCode::OK_200;
  13000. });
  13001. auto port = svr.bind_to_any_port(HOST);
  13002. auto t = thread([&] { svr.listen_after_bind(); });
  13003. auto se = detail::scope_exit([&] {
  13004. svr.stop();
  13005. t.join();
  13006. ASSERT_FALSE(svr.is_running());
  13007. ASSERT_TRUE(handled);
  13008. std::remove(tmp_path.c_str());
  13009. });
  13010. svr.wait_until_ready();
  13011. auto fb = make_file_body(tmp_path);
  13012. ASSERT_GT(fb.first, 0u);
  13013. Client cli(HOST, port);
  13014. auto res =
  13015. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13017. EXPECT_EQ(StatusCode::OK_200, res->status);
  13018. }
  13019. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13020. static constexpr unsigned int number_of_tasks{1000000};
  13021. std::atomic_uint count{0};
  13022. std::unique_ptr<TaskQueue> task_queue{
  13023. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13024. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13025. auto queued = task_queue->enqueue(
  13026. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13027. EXPECT_TRUE(queued);
  13028. }
  13029. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13030. task_queue->shutdown();
  13031. #else
  13032. EXPECT_NO_THROW(task_queue->shutdown());
  13033. #endif
  13034. EXPECT_EQ(number_of_tasks, count.load());
  13035. }
  13036. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13037. static constexpr unsigned int number_of_tasks{1000000};
  13038. static constexpr unsigned int qlimit{2};
  13039. unsigned int queued_count{0};
  13040. std::atomic_uint count{0};
  13041. std::unique_ptr<TaskQueue> task_queue{
  13042. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13043. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13044. if (task_queue->enqueue(
  13045. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13046. queued_count++;
  13047. }
  13048. }
  13049. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13050. task_queue->shutdown();
  13051. #else
  13052. EXPECT_NO_THROW(task_queue->shutdown());
  13053. #endif
  13054. EXPECT_EQ(queued_count, count.load());
  13055. EXPECT_TRUE(queued_count <= number_of_tasks);
  13056. EXPECT_TRUE(queued_count >= qlimit);
  13057. }
  13058. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13059. // Use a short idle timeout so a dynamic thread spawns, times out and
  13060. // exits during the test, and the pool keeps working afterwards.
  13061. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13062. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13063. /*idle_timeout_sec=*/1}};
  13064. std::atomic_uint count{0};
  13065. std::condition_variable cv;
  13066. std::mutex mtx;
  13067. bool release = false;
  13068. // Block the base thread so the second task spawns a dynamic thread.
  13069. EXPECT_TRUE(task_queue->enqueue([&] {
  13070. std::unique_lock<std::mutex> lock(mtx);
  13071. while (!release) {
  13072. cv.wait(lock);
  13073. }
  13074. count++;
  13075. }));
  13076. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13077. // Let the dynamic thread finish its task and exceed the idle timeout.
  13078. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13079. {
  13080. std::unique_lock<std::mutex> lock(mtx);
  13081. release = true;
  13082. }
  13083. cv.notify_all();
  13084. // The pool must still accept and run tasks after the dynamic thread exited.
  13085. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13086. task_queue->shutdown();
  13087. EXPECT_EQ(3u, count.load());
  13088. }
  13089. TEST(TaskQueueTest, MaxQueuedRequests) {
  13090. static constexpr unsigned int qlimit{3};
  13091. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13092. std::condition_variable sem_cv;
  13093. std::mutex sem_mtx;
  13094. int credits = 0;
  13095. bool queued;
  13096. /* Fill up the queue with tasks that will block until we give them credits to
  13097. * complete. */
  13098. for (unsigned int n = 0; n <= qlimit;) {
  13099. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13100. std::unique_lock<std::mutex> lock(sem_mtx);
  13101. while (credits <= 0) {
  13102. sem_cv.wait(lock);
  13103. }
  13104. /* Consume the credit and signal the test code if they are all gone. */
  13105. if (--credits == 0) { sem_cv.notify_one(); }
  13106. });
  13107. if (n < qlimit) {
  13108. /* The first qlimit enqueues must succeed. */
  13109. EXPECT_TRUE(queued);
  13110. } else {
  13111. /* The last one will succeed only when the worker thread
  13112. * starts and dequeues the first blocking task. Although
  13113. * not necessary for the correctness of this test, we sleep for
  13114. * a short while to avoid busy waiting. */
  13115. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13116. }
  13117. if (queued) { n++; }
  13118. }
  13119. /* Further enqueues must fail since the queue is full. */
  13120. for (auto i = 0; i < 4; i++) {
  13121. queued = task_queue->enqueue([] {});
  13122. EXPECT_FALSE(queued);
  13123. }
  13124. /* Give the credits to allow the previous tasks to complete. */
  13125. {
  13126. std::unique_lock<std::mutex> lock(sem_mtx);
  13127. credits += qlimit + 1;
  13128. }
  13129. sem_cv.notify_all();
  13130. /* Wait for all the credits to be consumed. */
  13131. {
  13132. std::unique_lock<std::mutex> lock(sem_mtx);
  13133. while (credits > 0) {
  13134. sem_cv.wait(lock);
  13135. }
  13136. }
  13137. /* Check that we are able again to enqueue at least qlimit tasks. */
  13138. for (unsigned int i = 0; i < qlimit; i++) {
  13139. queued = task_queue->enqueue([] {});
  13140. EXPECT_TRUE(queued);
  13141. }
  13142. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13143. task_queue->shutdown();
  13144. #else
  13145. EXPECT_NO_THROW(task_queue->shutdown());
  13146. #endif
  13147. }
  13148. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13149. Server svr;
  13150. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13151. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13152. });
  13153. svr.Get("/hello", [](const Request &req, Response &res) {
  13154. res.set_content(req.get_param_value("key"), "text/plain");
  13155. });
  13156. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13157. auto se = detail::scope_exit([&] {
  13158. svr.stop();
  13159. thread.join();
  13160. ASSERT_FALSE(svr.is_running());
  13161. });
  13162. svr.wait_until_ready();
  13163. {
  13164. Client cli(HOST, PORT);
  13165. cli.set_follow_location(true);
  13166. auto res = cli.Get("/");
  13167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13168. EXPECT_EQ(StatusCode::OK_200, res->status);
  13169. EXPECT_EQ("val&key2=val2", res->body);
  13170. }
  13171. }
  13172. #endif
  13173. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13174. Server svr;
  13175. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13176. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13177. });
  13178. svr.Get("/hello", [](const Request &req, Response &res) {
  13179. res.set_content(req.get_param_value("key"), "text/plain");
  13180. });
  13181. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13182. auto se = detail::scope_exit([&] {
  13183. svr.stop();
  13184. thread.join();
  13185. ASSERT_FALSE(svr.is_running());
  13186. });
  13187. svr.wait_until_ready();
  13188. {
  13189. Client cli(HOST, PORT);
  13190. cli.set_follow_location(true);
  13191. auto res = cli.Get("/");
  13192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13193. EXPECT_EQ(StatusCode::OK_200, res->status);
  13194. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13195. }
  13196. }
  13197. TEST(RedirectTest, RedirectWithPlusInPath) {
  13198. Server svr;
  13199. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13200. res.set_redirect("/a+b");
  13201. });
  13202. // Route pattern uses regex; escape + as \\+
  13203. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13204. res.set_content(req.path, "text/plain");
  13205. });
  13206. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13207. auto se = detail::scope_exit([&] {
  13208. svr.stop();
  13209. thread.join();
  13210. ASSERT_FALSE(svr.is_running());
  13211. });
  13212. svr.wait_until_ready();
  13213. {
  13214. Client cli(HOST, PORT);
  13215. cli.set_follow_location(true);
  13216. auto res = cli.Get("/");
  13217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13218. EXPECT_EQ(StatusCode::OK_200, res->status);
  13219. EXPECT_EQ("/a+b", res->body);
  13220. }
  13221. }
  13222. #ifdef CPPHTTPLIB_SSL_ENABLED
  13223. TEST(RedirectTest, Issue2185_Online) {
  13224. SSLClient client("github.com");
  13225. client.set_follow_location(true);
  13226. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13227. "Coollab-Windows.zip");
  13228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13229. EXPECT_EQ(StatusCode::OK_200, res->status);
  13230. EXPECT_EQ(9920427U, res->body.size());
  13231. }
  13232. #endif
  13233. TEST(VulnerabilityTest, CRLFInjection) {
  13234. Server svr;
  13235. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13236. res.set_content("Hello 1", "text/plain");
  13237. });
  13238. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13239. res.set_content("Hello 2", "text/plain");
  13240. });
  13241. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13242. res.set_content("Hello 3", "text/plain");
  13243. });
  13244. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13245. res.set_content("Hello 4", "text/plain");
  13246. });
  13247. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13248. for (const auto &x : req.headers) {
  13249. auto key = x.first;
  13250. EXPECT_STRNE("evil", key.c_str());
  13251. }
  13252. });
  13253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. thread.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. {
  13261. Client cli(HOST, PORT);
  13262. cli.Post("/test1", "A=B",
  13263. "application/x-www-form-urlencoded\r\nevil: hello1");
  13264. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13265. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13266. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13267. }
  13268. }
  13269. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13270. auto server_thread = std::thread([] {
  13271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13272. default_socket_options(srv);
  13273. sockaddr_in addr{};
  13274. addr.sin_family = AF_INET;
  13275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13276. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13277. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13278. ::listen(srv, 1);
  13279. sockaddr_in cli_addr{};
  13280. socklen_t cli_len = sizeof(cli_addr);
  13281. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13282. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13283. std::string buf_all;
  13284. char buf[2048];
  13285. ssize_t n;
  13286. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13287. buf_all.append(buf, static_cast<size_t>(n));
  13288. size_t pos;
  13289. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13290. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13291. auto e = request_block.find("\r\n");
  13292. if (e != std::string::npos) {
  13293. auto request_line = request_block.substr(0, e);
  13294. std::string msg =
  13295. "CRLF injection detected in request line: '" + request_line + "'";
  13296. EXPECT_FALSE(true) << msg;
  13297. }
  13298. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13299. ::send(cli,
  13300. #ifdef _WIN32
  13301. static_cast<const char *>(resp.c_str()),
  13302. static_cast<int>(resp.size()),
  13303. #else
  13304. resp.c_str(), resp.size(),
  13305. #endif
  13306. 0);
  13307. buf_all.erase(0, pos + 4);
  13308. }
  13309. }
  13310. detail::close_socket(cli);
  13311. detail::close_socket(srv);
  13312. });
  13313. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13314. auto cli = Client("127.0.0.1", PORT + 1);
  13315. auto headers = Headers{
  13316. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13317. {"Connection", "keep-alive"}};
  13318. auto res = cli.Get("/hi", headers);
  13319. EXPECT_FALSE(res);
  13320. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13321. server_thread.join();
  13322. }
  13323. TEST(PathParamsTest, StaticMatch) {
  13324. const auto pattern = "/users/all";
  13325. detail::PathParamsMatcher matcher(pattern);
  13326. Request request;
  13327. request.path = "/users/all";
  13328. ASSERT_TRUE(matcher.match(request));
  13329. std::unordered_map<std::string, std::string> expected_params = {};
  13330. EXPECT_EQ(request.path_params, expected_params);
  13331. }
  13332. TEST(PathParamsTest, StaticMismatch) {
  13333. const auto pattern = "/users/all";
  13334. detail::PathParamsMatcher matcher(pattern);
  13335. Request request;
  13336. request.path = "/users/1";
  13337. ASSERT_FALSE(matcher.match(request));
  13338. }
  13339. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13340. const auto pattern = "/users/:id/subscriptions";
  13341. detail::PathParamsMatcher matcher(pattern);
  13342. Request request;
  13343. request.path = "/users/42/subscriptions";
  13344. ASSERT_TRUE(matcher.match(request));
  13345. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13346. EXPECT_EQ(request.path_params, expected_params);
  13347. }
  13348. TEST(PathParamsTest, SingleParamInTheEnd) {
  13349. const auto pattern = "/users/:id";
  13350. detail::PathParamsMatcher matcher(pattern);
  13351. Request request;
  13352. request.path = "/users/24";
  13353. ASSERT_TRUE(matcher.match(request));
  13354. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13355. EXPECT_EQ(request.path_params, expected_params);
  13356. }
  13357. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13358. const auto pattern = "/users/:id/";
  13359. detail::PathParamsMatcher matcher(pattern);
  13360. Request request;
  13361. request.path = "/users/42/";
  13362. ASSERT_TRUE(matcher.match(request));
  13363. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13364. EXPECT_EQ(request.path_params, expected_params);
  13365. }
  13366. TEST(PathParamsTest, EmptyParam) {
  13367. const auto pattern = "/users/:id/";
  13368. detail::PathParamsMatcher matcher(pattern);
  13369. Request request;
  13370. request.path = "/users//";
  13371. ASSERT_TRUE(matcher.match(request));
  13372. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13373. EXPECT_EQ(request.path_params, expected_params);
  13374. }
  13375. TEST(PathParamsTest, FragmentMismatch) {
  13376. const auto pattern = "/users/:id/";
  13377. detail::PathParamsMatcher matcher(pattern);
  13378. Request request;
  13379. request.path = "/admins/24/";
  13380. ASSERT_FALSE(matcher.match(request));
  13381. }
  13382. TEST(PathParamsTest, ExtraFragments) {
  13383. const auto pattern = "/users/:id";
  13384. detail::PathParamsMatcher matcher(pattern);
  13385. Request request;
  13386. request.path = "/users/42/subscriptions";
  13387. ASSERT_FALSE(matcher.match(request));
  13388. }
  13389. TEST(PathParamsTest, MissingTrailingParam) {
  13390. const auto pattern = "/users/:id";
  13391. detail::PathParamsMatcher matcher(pattern);
  13392. Request request;
  13393. request.path = "/users";
  13394. ASSERT_FALSE(matcher.match(request));
  13395. }
  13396. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13397. const auto pattern = "/users/:id/subscriptions";
  13398. detail::PathParamsMatcher matcher(pattern);
  13399. Request request;
  13400. request.path = "/users/subscriptions";
  13401. ASSERT_FALSE(matcher.match(request));
  13402. }
  13403. TEST(PathParamsTest, MultipleParams) {
  13404. const auto pattern = "/users/:userid/subscriptions/:subid";
  13405. detail::PathParamsMatcher matcher(pattern);
  13406. Request request;
  13407. request.path = "/users/42/subscriptions/2";
  13408. ASSERT_TRUE(matcher.match(request));
  13409. std::unordered_map<std::string, std::string> expected_params = {
  13410. {"userid", "42"}, {"subid", "2"}};
  13411. EXPECT_EQ(request.path_params, expected_params);
  13412. }
  13413. TEST(PathParamsTest, SequenceOfParams) {
  13414. const auto pattern = "/values/:x/:y/:z";
  13415. detail::PathParamsMatcher matcher(pattern);
  13416. Request request;
  13417. request.path = "/values/1/2/3";
  13418. ASSERT_TRUE(matcher.match(request));
  13419. std::unordered_map<std::string, std::string> expected_params = {
  13420. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13421. EXPECT_EQ(request.path_params, expected_params);
  13422. }
  13423. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13424. const auto pattern = "/prefix:suffix";
  13425. detail::PathParamsMatcher matcher(pattern);
  13426. Request request;
  13427. request.path = "/prefix:suffix";
  13428. ASSERT_TRUE(matcher.match(request));
  13429. const std::unordered_map<std::string, std::string> expected_params = {};
  13430. EXPECT_EQ(request.path_params, expected_params);
  13431. }
  13432. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13433. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13434. // calling thread's stack on a long enough path for a quantified pattern;
  13435. // RegexMatcher must refuse to run regex matching on paths beyond
  13436. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13437. detail::RegexMatcher matcher("/files/(.*)");
  13438. Request within_limit;
  13439. within_limit.path = "/files/" + std::string(10, 'A');
  13440. EXPECT_TRUE(matcher.match(within_limit));
  13441. Request over_limit;
  13442. over_limit.path =
  13443. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13444. EXPECT_FALSE(matcher.match(over_limit));
  13445. }
  13446. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13447. Server svr;
  13448. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13449. res.set_content("ok", "text/plain");
  13450. });
  13451. auto port = svr.bind_to_any_port(HOST);
  13452. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13453. auto se = detail::scope_exit([&] {
  13454. svr.stop();
  13455. thread.join();
  13456. ASSERT_FALSE(svr.is_running());
  13457. });
  13458. svr.wait_until_ready();
  13459. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13460. // request URI limit; this used to be able to crash the process.
  13461. std::string path =
  13462. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13463. std::string req = "GET " + path +
  13464. " HTTP/1.1\r\n"
  13465. "Host: " +
  13466. std::string(HOST) + ":" + std::to_string(port) +
  13467. "\r\n"
  13468. "Connection: close\r\n"
  13469. "\r\n";
  13470. std::string response;
  13471. ASSERT_TRUE(send_request(5, req, &response, port));
  13472. EXPECT_NE(std::string::npos, response.find("404"));
  13473. }
  13474. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13475. Server svr;
  13476. auto handler = [](const Request & /*req*/, Response &res) {
  13477. res.set_content("hit", "text/plain");
  13478. };
  13479. // No regex metacharacter, so this one is compared literally
  13480. svr.Get("/literal/route", handler);
  13481. // '.' is a regex metacharacter, so this one must keep regex semantics
  13482. svr.Get("/a.c", handler);
  13483. auto port = svr.bind_to_any_port(HOST);
  13484. std::thread t([&]() { svr.listen_after_bind(); });
  13485. auto se = detail::scope_exit([&] {
  13486. svr.stop();
  13487. t.join();
  13488. ASSERT_FALSE(svr.is_running());
  13489. });
  13490. svr.wait_until_ready();
  13491. Client cli(HOST, port);
  13492. struct {
  13493. const char *path;
  13494. int status;
  13495. } cases[] = {
  13496. {"/literal/route", StatusCode::OK_200},
  13497. {"/literal/routes", StatusCode::NotFound_404},
  13498. {"/literal/rout", StatusCode::NotFound_404},
  13499. {"/abc", StatusCode::OK_200},
  13500. {"/a.c", StatusCode::OK_200},
  13501. };
  13502. for (const auto &x : cases) {
  13503. auto res = cli.Get(x.path);
  13504. ASSERT_TRUE(res) << x.path;
  13505. EXPECT_EQ(x.status, res->status) << x.path;
  13506. }
  13507. }
  13508. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13509. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13510. // from exhausting the stack, so it must only constrain routes that actually
  13511. // run a regular expression. A literal route is matched by comparison and
  13512. // stays usable at any length.
  13513. Server svr;
  13514. const std::string pattern =
  13515. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13516. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13517. res.set_content("hit", "text/plain");
  13518. });
  13519. auto port = svr.bind_to_any_port(HOST);
  13520. std::thread t([&]() { svr.listen_after_bind(); });
  13521. auto se = detail::scope_exit([&] {
  13522. svr.stop();
  13523. t.join();
  13524. ASSERT_FALSE(svr.is_running());
  13525. });
  13526. svr.wait_until_ready();
  13527. Client cli(HOST, port);
  13528. auto res = cli.Get(pattern);
  13529. ASSERT_TRUE(res);
  13530. EXPECT_EQ(StatusCode::OK_200, res->status);
  13531. }
  13532. TEST(ParseUrlTest, VariousPatterns) {
  13533. {
  13534. detail::UrlComponents uc;
  13535. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13536. EXPECT_EQ("http", uc.scheme);
  13537. EXPECT_EQ("example.com", uc.host);
  13538. EXPECT_EQ("8080", uc.port);
  13539. EXPECT_EQ("/path", uc.path);
  13540. EXPECT_EQ("?q=1", uc.query);
  13541. }
  13542. {
  13543. detail::UrlComponents uc;
  13544. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13545. EXPECT_EQ("https", uc.scheme);
  13546. EXPECT_EQ("example.com", uc.host);
  13547. EXPECT_TRUE(uc.port.empty());
  13548. EXPECT_EQ("/path", uc.path);
  13549. }
  13550. {
  13551. detail::UrlComponents uc;
  13552. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13553. EXPECT_EQ("::1", uc.host);
  13554. EXPECT_EQ("8080", uc.port);
  13555. EXPECT_EQ("/path", uc.path);
  13556. }
  13557. {
  13558. detail::UrlComponents uc;
  13559. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13560. }
  13561. {
  13562. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13563. // the path while the connection still targets the bracketed host.
  13564. detail::UrlComponents uc;
  13565. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13566. }
  13567. {
  13568. detail::UrlComponents uc;
  13569. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13570. }
  13571. {
  13572. detail::UrlComponents uc;
  13573. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13574. EXPECT_EQ("::1", uc.host);
  13575. EXPECT_TRUE(uc.port.empty());
  13576. EXPECT_EQ("/path", uc.path);
  13577. }
  13578. {
  13579. detail::UrlComponents uc;
  13580. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13581. EXPECT_TRUE(uc.scheme.empty());
  13582. EXPECT_EQ("example.com", uc.host);
  13583. EXPECT_EQ("/path", uc.path);
  13584. EXPECT_EQ("?q=1", uc.query);
  13585. }
  13586. {
  13587. detail::UrlComponents uc;
  13588. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13589. EXPECT_TRUE(uc.host.empty());
  13590. EXPECT_EQ("/path", uc.path);
  13591. EXPECT_EQ("?q=1", uc.query);
  13592. }
  13593. {
  13594. detail::UrlComponents uc;
  13595. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13596. EXPECT_EQ("example.com", uc.host);
  13597. EXPECT_EQ("8080", uc.port);
  13598. }
  13599. {
  13600. // Unix socket path — must not be parsed as host
  13601. detail::UrlComponents uc;
  13602. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13603. EXPECT_TRUE(uc.host.empty());
  13604. }
  13605. {
  13606. detail::UrlComponents uc;
  13607. ASSERT_TRUE(detail::parse_url("", uc));
  13608. EXPECT_TRUE(uc.host.empty());
  13609. EXPECT_TRUE(uc.path.empty());
  13610. }
  13611. {
  13612. detail::UrlComponents uc;
  13613. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13614. }
  13615. {
  13616. detail::UrlComponents uc;
  13617. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13618. }
  13619. {
  13620. // Accepted by parse_url; callers restrict to http/https
  13621. detail::UrlComponents uc;
  13622. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13623. EXPECT_EQ("ftp", uc.scheme);
  13624. }
  13625. {
  13626. detail::UrlComponents uc;
  13627. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13628. }
  13629. {
  13630. detail::UrlComponents uc;
  13631. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13632. }
  13633. }
  13634. TEST(ParseUrlTest, FragmentHandling) {
  13635. {
  13636. detail::UrlComponents uc;
  13637. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13638. EXPECT_EQ("/path", uc.path);
  13639. EXPECT_TRUE(uc.query.empty());
  13640. }
  13641. {
  13642. detail::UrlComponents uc;
  13643. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13644. EXPECT_TRUE(uc.path.empty());
  13645. EXPECT_TRUE(uc.query.empty());
  13646. }
  13647. }
  13648. TEST(ParseUrlTest, UserinfoHandling) {
  13649. // Userinfo with @ but no colon — host includes @
  13650. detail::UrlComponents uc;
  13651. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13652. EXPECT_EQ("user@host.com", uc.host);
  13653. EXPECT_EQ("/path", uc.path);
  13654. }
  13655. TEST(ParseUrlTest, IPv6EdgeCases) {
  13656. {
  13657. detail::UrlComponents uc;
  13658. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13659. EXPECT_TRUE(uc.scheme.empty());
  13660. EXPECT_EQ("::1", uc.host);
  13661. EXPECT_EQ("8080", uc.port);
  13662. }
  13663. {
  13664. // Zone ID '%25' is not in [a-fA-F0-9:]
  13665. detail::UrlComponents uc;
  13666. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13667. }
  13668. }
  13669. TEST(ParseUrlTest, SchemeEdgeCases) {
  13670. {
  13671. detail::UrlComponents uc;
  13672. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13673. }
  13674. {
  13675. detail::UrlComponents uc;
  13676. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13677. }
  13678. {
  13679. detail::UrlComponents uc;
  13680. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13681. }
  13682. }
  13683. TEST(ParseUrlTest, PortEdgeCases) {
  13684. {
  13685. detail::UrlComponents uc;
  13686. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13687. EXPECT_TRUE(uc.port.empty());
  13688. EXPECT_EQ("/path", uc.path);
  13689. }
  13690. {
  13691. // parse_url accepts any port string; validation is done by parse_port
  13692. detail::UrlComponents uc;
  13693. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13694. EXPECT_EQ("abc", uc.port);
  13695. }
  13696. }
  13697. TEST(ParseUrlTest, WebSocketPatterns) {
  13698. {
  13699. detail::UrlComponents uc;
  13700. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13701. EXPECT_EQ("ws", uc.scheme);
  13702. EXPECT_EQ("echo.example.com", uc.host);
  13703. EXPECT_EQ("8080", uc.port);
  13704. EXPECT_EQ("/ws", uc.path);
  13705. }
  13706. {
  13707. detail::UrlComponents uc;
  13708. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13709. EXPECT_EQ("wss", uc.scheme);
  13710. EXPECT_EQ("echo.example.com", uc.host);
  13711. EXPECT_TRUE(uc.port.empty());
  13712. EXPECT_EQ("/ws", uc.path);
  13713. }
  13714. }
  13715. TEST(ParseUrlTest, QueryOnly) {
  13716. detail::UrlComponents uc;
  13717. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13718. EXPECT_TRUE(uc.host.empty());
  13719. EXPECT_TRUE(uc.path.empty());
  13720. EXPECT_EQ("?q=1&r=2", uc.query);
  13721. }
  13722. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13723. detail::UrlComponents uc;
  13724. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13725. EXPECT_TRUE(uc.scheme.empty());
  13726. EXPECT_EQ("example.com", uc.host);
  13727. EXPECT_EQ("443", uc.port);
  13728. EXPECT_EQ("/path", uc.path);
  13729. }
  13730. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13731. // If ipv6 regex working, regex match codepath is taken.
  13732. // else port will default to 80 in Client impl
  13733. int clientImplMagicPort = 80;
  13734. int port = 4321;
  13735. // above ports must be different to avoid false negative
  13736. EXPECT_NE(clientImplMagicPort, port);
  13737. std::string ipV6TestURL = "http://[ff06::c3]";
  13738. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13739. CLIENT_PRIVATE_KEY_FILE);
  13740. EXPECT_EQ(cli.port(), port);
  13741. }
  13742. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13743. auto file_path = "./www/dir/index.html";
  13744. auto dir_path = "./www/dir";
  13745. detail::FileStat stat_file(file_path);
  13746. EXPECT_TRUE(stat_file.is_file());
  13747. EXPECT_FALSE(stat_file.is_dir());
  13748. detail::FileStat stat_dir(dir_path);
  13749. EXPECT_FALSE(stat_dir.is_file());
  13750. EXPECT_TRUE(stat_dir.is_dir());
  13751. }
  13752. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13753. // IPv4 with default HTTP port (80)
  13754. EXPECT_EQ("example.com",
  13755. detail::make_host_and_port_string("example.com", 80, false));
  13756. // IPv4 with default HTTPS port (443)
  13757. EXPECT_EQ("example.com",
  13758. detail::make_host_and_port_string("example.com", 443, true));
  13759. // IPv4 with non-default HTTP port
  13760. EXPECT_EQ("example.com:8080",
  13761. detail::make_host_and_port_string("example.com", 8080, false));
  13762. // IPv4 with non-default HTTPS port
  13763. EXPECT_EQ("example.com:8443",
  13764. detail::make_host_and_port_string("example.com", 8443, true));
  13765. // IPv6 with default HTTP port (80)
  13766. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13767. // IPv6 with default HTTPS port (443)
  13768. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13769. // IPv6 with non-default HTTP port
  13770. EXPECT_EQ("[::1]:8080",
  13771. detail::make_host_and_port_string("::1", 8080, false));
  13772. // IPv6 with non-default HTTPS port
  13773. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13774. // IPv6 full address with default port
  13775. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13776. detail::make_host_and_port_string(
  13777. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13778. // IPv6 full address with non-default port
  13779. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13780. detail::make_host_and_port_string(
  13781. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13782. // IPv6 localhost with non-default port
  13783. EXPECT_EQ("[::1]:3000",
  13784. detail::make_host_and_port_string("::1", 3000, false));
  13785. // IPv6 with zone ID (link-local address) with default port
  13786. EXPECT_EQ("[fe80::1%eth0]",
  13787. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13788. // IPv6 with zone ID (link-local address) with non-default port
  13789. EXPECT_EQ("[fe80::1%eth0]:8080",
  13790. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13791. // Edge case: Port 443 with is_ssl=false (should add port)
  13792. EXPECT_EQ("example.com:443",
  13793. detail::make_host_and_port_string("example.com", 443, false));
  13794. // Edge case: Port 80 with is_ssl=true (should add port)
  13795. EXPECT_EQ("example.com:80",
  13796. detail::make_host_and_port_string("example.com", 80, true));
  13797. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13798. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13799. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13800. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13801. // Security fix: Already bracketed IPv6 should not get double brackets
  13802. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13803. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13804. EXPECT_EQ("[::1]:8080",
  13805. detail::make_host_and_port_string("[::1]", 8080, false));
  13806. EXPECT_EQ("[2001:db8::1]:8080",
  13807. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13808. EXPECT_EQ("[fe80::1%eth0]",
  13809. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13810. EXPECT_EQ("[fe80::1%eth0]:8080",
  13811. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13812. // Edge case: Empty host (should return as-is)
  13813. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13814. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13815. // This is a known limitation but shouldn't crash
  13816. EXPECT_EQ("[host:name]",
  13817. detail::make_host_and_port_string("host:name", 80, false));
  13818. // Port number edge cases (no validation, but should not crash)
  13819. EXPECT_EQ("example.com:0",
  13820. detail::make_host_and_port_string("example.com", 0, false));
  13821. EXPECT_EQ("example.com:-1",
  13822. detail::make_host_and_port_string("example.com", -1, false));
  13823. EXPECT_EQ("example.com:65535",
  13824. detail::make_host_and_port_string("example.com", 65535, false));
  13825. EXPECT_EQ("example.com:65536",
  13826. detail::make_host_and_port_string("example.com", 65536, false));
  13827. }
  13828. #ifdef CPPHTTPLIB_SSL_ENABLED
  13829. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13830. httplib::SSLClient cli("roblox.com", 443);
  13831. cli.set_follow_location(true);
  13832. auto res = cli.Get("/");
  13833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13834. EXPECT_EQ(StatusCode::OK_200, res->status);
  13835. }
  13836. #endif
  13837. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13838. Server svr;
  13839. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13840. EXPECT_EQ(res.status, 400);
  13841. });
  13842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. thread.join();
  13846. ASSERT_FALSE(svr.is_running());
  13847. });
  13848. svr.wait_until_ready();
  13849. Client cli(HOST, PORT);
  13850. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13851. }
  13852. TEST(InvalidHeaderCharsTest, is_field_name) {
  13853. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13854. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13855. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13856. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  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("token@123"));
  13860. EXPECT_FALSE(detail::fields::is_field_name(""));
  13861. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13862. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13863. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13864. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13865. }
  13866. TEST(InvalidHeaderCharsTest, is_field_value) {
  13867. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13868. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13869. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13870. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13871. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13872. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13873. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13874. EXPECT_TRUE(detail::fields::is_field_value(""));
  13875. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13876. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13877. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13878. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13879. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13880. }
  13881. TEST(InvalidHeaderCharsTest, OnServer) {
  13882. Server svr;
  13883. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13884. std::string header = "Not Set";
  13885. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13886. res.set_header(header, "value");
  13887. res.set_content("Page Content Page Content", "text/plain");
  13888. });
  13889. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13890. std::string header = "Not Set";
  13891. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13892. res.set_header("X-Test", header);
  13893. res.set_content("Page Content Page Content", "text/plain");
  13894. });
  13895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13896. auto se = detail::scope_exit([&] {
  13897. svr.stop();
  13898. thread.join();
  13899. ASSERT_FALSE(svr.is_running());
  13900. });
  13901. svr.wait_until_ready();
  13902. Client cli(HOST, PORT);
  13903. {
  13904. auto res = cli.Get(
  13905. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13907. EXPECT_EQ("Page Content Page Content", res->body);
  13908. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13909. }
  13910. {
  13911. auto res = cli.Get(
  13912. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. EXPECT_EQ("Page Content Page Content", res->body);
  13915. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13916. }
  13917. }
  13918. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13919. auto handled = false;
  13920. Server svr;
  13921. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13922. thread t = thread([&] { svr.listen(HOST, PORT); });
  13923. auto se = detail::scope_exit([&] {
  13924. svr.stop();
  13925. t.join();
  13926. ASSERT_FALSE(svr.is_running());
  13927. ASSERT_FALSE(handled);
  13928. });
  13929. svr.wait_until_ready();
  13930. auto req = "POST /test HTTP/1.1\r\n"
  13931. "Content-Length: x\r\n"
  13932. "\r\n";
  13933. std::string response;
  13934. ASSERT_TRUE(send_request(1, req, &response));
  13935. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13936. response.substr(0, response.find("\r\n")));
  13937. }
  13938. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13939. // case-insensitive, and a server that receives a 100-continue expectation in
  13940. // an HTTP/1.0 request MUST ignore it.
  13941. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13942. std::string response;
  13943. ASSERT_TRUE(send_request(1, req, &response, port));
  13944. *got_100 = response.find("100 Continue") != std::string::npos;
  13945. }
  13946. class ExpectTokenTest : public ::testing::Test {
  13947. protected:
  13948. void SetUp() override {
  13949. svr_.Post("/p", [](const Request &, Response &res) {
  13950. res.set_content("ok", "text/plain");
  13951. });
  13952. port_ = svr_.bind_to_any_port(HOST);
  13953. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13954. svr_.wait_until_ready();
  13955. }
  13956. void TearDown() override {
  13957. svr_.stop();
  13958. if (thread_.joinable()) { thread_.join(); }
  13959. }
  13960. std::string request(const char *version, const char *expect_value) const {
  13961. return std::string("POST /p ") + version +
  13962. "\r\n"
  13963. "Host: localhost\r\n"
  13964. "Content-Length: 2\r\n"
  13965. "Connection: close\r\n"
  13966. "Expect: " +
  13967. expect_value +
  13968. "\r\n"
  13969. "\r\n"
  13970. "hi";
  13971. }
  13972. Server svr_;
  13973. int port_ = 0;
  13974. thread thread_;
  13975. };
  13976. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13977. bool got_100 = false;
  13978. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13979. EXPECT_TRUE(got_100);
  13980. }
  13981. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13982. bool got_100 = true;
  13983. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13984. EXPECT_FALSE(got_100);
  13985. }
  13986. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13987. bool got_100 = false;
  13988. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13989. EXPECT_TRUE(got_100);
  13990. }
  13991. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13992. bool got_100 = false;
  13993. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13994. EXPECT_TRUE(got_100);
  13995. }
  13996. #ifndef _WIN32
  13997. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13998. static constexpr char reject[] = "Unauthorized";
  13999. static constexpr char accept[] = "Upload accepted";
  14000. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14001. Server svr;
  14002. svr.set_expect_100_continue_handler(
  14003. [](const Request & /*req*/, Response &res) {
  14004. res.status = StatusCode::Unauthorized_401;
  14005. res.set_content(reject, "text/plain");
  14006. return res.status;
  14007. });
  14008. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14009. res.set_content(accept, "text/plain");
  14010. });
  14011. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14012. auto se = detail::scope_exit([&] {
  14013. svr.stop();
  14014. thread.join();
  14015. ASSERT_FALSE(svr.is_running());
  14016. });
  14017. svr.wait_until_ready();
  14018. {
  14019. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14020. curl_easy_init(), &curl_easy_cleanup};
  14021. ASSERT_NE(curl, nullptr);
  14022. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14023. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14024. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14025. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14026. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14027. &curl_slist_free_all};
  14028. ASSERT_NE(list, nullptr);
  14029. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14030. struct read_data {
  14031. size_t read_size;
  14032. size_t total_size;
  14033. } data = {0, total_size};
  14034. using read_callback_t =
  14035. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14036. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14037. void *userdata) -> size_t {
  14038. read_data *d = (read_data *)userdata;
  14039. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14040. std::fill_n(ptr, size * nmemb, 'A');
  14041. d->read_size += size * nmemb;
  14042. return size * nmemb;
  14043. };
  14044. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14045. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14046. std::vector<char> buffer;
  14047. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14048. using write_callback_t =
  14049. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14050. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14051. void *userdata) -> size_t {
  14052. std::vector<char> *buf = (std::vector<char> *)userdata;
  14053. buf->reserve(buf->size() + size * nmemb + 1);
  14054. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14055. return size * nmemb;
  14056. };
  14057. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14058. {
  14059. const auto res = curl_easy_perform(curl.get());
  14060. ASSERT_EQ(res, CURLE_OK);
  14061. }
  14062. {
  14063. auto response_code = long{};
  14064. const auto res =
  14065. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14066. ASSERT_EQ(res, CURLE_OK);
  14067. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14068. }
  14069. {
  14070. auto dl = curl_off_t{};
  14071. const auto res =
  14072. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14073. ASSERT_EQ(res, CURLE_OK);
  14074. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14075. }
  14076. {
  14077. buffer.push_back('\0');
  14078. ASSERT_STRCASEEQ(buffer.data(), reject);
  14079. }
  14080. }
  14081. }
  14082. #endif
  14083. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14084. // Regression test for #2458.
  14085. //
  14086. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14087. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14088. // ticket can make the client socket spuriously readable during the
  14089. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14090. // the client withholds the body and then blocks reading a response that never
  14091. // comes, failing with `Failed to read connection`.
  14092. //
  14093. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14094. // within the timeout. This raw OpenSSL server deliberately never sends
  14095. // `100 Continue`; the client must still deliver the body and receive 200.
  14096. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14097. signal(SIGPIPE, SIG_IGN);
  14098. const auto port = PORT + 4;
  14099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14100. ASSERT_NE(srv, INVALID_SOCKET);
  14101. int opt = 1;
  14102. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14103. sockaddr_in addr{};
  14104. addr.sin_family = AF_INET;
  14105. addr.sin_port = htons(static_cast<uint16_t>(port));
  14106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14107. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14108. ASSERT_EQ(0, ::listen(srv, 1));
  14109. std::atomic<size_t> server_body_bytes{0};
  14110. auto server_thread = std::thread([&] {
  14111. sockaddr_in cli_addr{};
  14112. socklen_t cli_len = sizeof(cli_addr);
  14113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14114. if (cli == INVALID_SOCKET) { return; }
  14115. // Bound the lifetime of the server side so a buggy client (which never
  14116. // sends the body) cannot make this thread block forever on join.
  14117. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14118. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14119. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14120. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14121. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14122. SSL *ssl = SSL_new(ctx);
  14123. SSL_set_fd(ssl, static_cast<int>(cli));
  14124. if (SSL_accept(ssl) > 0) {
  14125. // Read the request headers. Reading here also flushes the TLS 1.3
  14126. // session tickets to the client. Deliberately do NOT send
  14127. // `100 Continue`.
  14128. std::string buf;
  14129. char tmp[1024];
  14130. while (buf.find("\r\n\r\n") == std::string::npos) {
  14131. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14132. if (n <= 0) { break; }
  14133. buf.append(tmp, static_cast<size_t>(n));
  14134. }
  14135. // A correct client sends the body now; count what arrives.
  14136. auto pos = buf.find("\r\n\r\n");
  14137. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14138. while (body < 4096) {
  14139. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14140. if (n <= 0) { break; }
  14141. body += static_cast<size_t>(n);
  14142. }
  14143. server_body_bytes = body;
  14144. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14145. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14146. SSL_shutdown(ssl);
  14147. }
  14148. SSL_free(ssl);
  14149. detail::close_socket(cli);
  14150. SSL_CTX_free(ctx);
  14151. });
  14152. auto se = detail::scope_exit([&] {
  14153. server_thread.join();
  14154. detail::close_socket(srv);
  14155. });
  14156. SSLClient cli("127.0.0.1", port);
  14157. cli.enable_server_certificate_verification(false);
  14158. cli.set_connection_timeout(5, 0);
  14159. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14160. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14161. std::string body(4096, 'A');
  14162. auto res = cli.Put("/api/test", body, "application/json");
  14163. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14164. EXPECT_EQ(StatusCode::OK_200, res->status);
  14165. EXPECT_EQ(body.size(), server_body_bytes.load());
  14166. }
  14167. #endif
  14168. template <typename S, typename C>
  14169. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14170. svr.Get("/stream", [&](const Request &, Response &res) {
  14171. auto data = new std::string("01234567890123456789");
  14172. res.set_content_provider(
  14173. data->size(), "text/plain",
  14174. [&, data](size_t offset, size_t length, DataSink &sink) {
  14175. const size_t DATA_CHUNK_SIZE = 4;
  14176. const auto &d = *data;
  14177. std::this_thread::sleep_for(std::chrono::seconds(1));
  14178. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14179. return true;
  14180. },
  14181. [data](bool success) {
  14182. EXPECT_FALSE(success);
  14183. delete data;
  14184. });
  14185. });
  14186. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14187. auto i = new size_t(0);
  14188. res.set_content_provider(
  14189. "text/plain",
  14190. [i](size_t, DataSink &sink) {
  14191. if (*i < 5) {
  14192. std::this_thread::sleep_for(std::chrono::seconds(1));
  14193. sink.write("abcd", 4);
  14194. (*i)++;
  14195. } else {
  14196. sink.done();
  14197. }
  14198. return true;
  14199. },
  14200. [i](bool success) {
  14201. EXPECT_FALSE(success);
  14202. delete i;
  14203. });
  14204. });
  14205. svr.Get("/chunked", [&](const Request &, Response &res) {
  14206. auto i = new size_t(0);
  14207. res.set_chunked_content_provider(
  14208. "text/plain",
  14209. [i](size_t, DataSink &sink) {
  14210. if (*i < 5) {
  14211. std::this_thread::sleep_for(std::chrono::seconds(1));
  14212. sink.os << "abcd";
  14213. (*i)++;
  14214. } else {
  14215. sink.done();
  14216. }
  14217. return true;
  14218. },
  14219. [i](bool success) {
  14220. EXPECT_FALSE(success);
  14221. delete i;
  14222. });
  14223. });
  14224. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14225. auto se = detail::scope_exit([&] {
  14226. svr.stop();
  14227. listen_thread.join();
  14228. ASSERT_FALSE(svr.is_running());
  14229. });
  14230. svr.wait_until_ready();
  14231. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14232. {
  14233. auto start = std::chrono::steady_clock::now();
  14234. auto res = cli.Get("/stream");
  14235. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14236. std::chrono::steady_clock::now() - start)
  14237. .count();
  14238. ASSERT_FALSE(res);
  14239. EXPECT_EQ(Error::Read, res.error());
  14240. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14241. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14242. }
  14243. {
  14244. auto start = std::chrono::steady_clock::now();
  14245. auto res = cli.Get("/stream_without_length");
  14246. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14247. std::chrono::steady_clock::now() - start)
  14248. .count();
  14249. ASSERT_FALSE(res);
  14250. EXPECT_EQ(Error::Read, res.error());
  14251. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14252. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14253. }
  14254. {
  14255. auto start = std::chrono::steady_clock::now();
  14256. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14257. EXPECT_EQ("abcd", string(data, data_length));
  14258. return true;
  14259. });
  14260. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14261. std::chrono::steady_clock::now() - start)
  14262. .count();
  14263. ASSERT_FALSE(res);
  14264. EXPECT_EQ(Error::Read, res.error());
  14265. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14266. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14267. }
  14268. }
  14269. TEST(MaxTimeoutTest, ContentStream) {
  14270. time_t timeout = 2000;
  14271. time_t threshold = 200;
  14272. Server svr;
  14273. Client cli("localhost", PORT);
  14274. max_timeout_test(svr, cli, timeout, threshold);
  14275. }
  14276. #ifdef CPPHTTPLIB_SSL_ENABLED
  14277. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14278. time_t timeout = 2000;
  14279. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14281. SSLClient cli("localhost", PORT);
  14282. cli.enable_server_certificate_verification(false);
  14283. max_timeout_test(svr, cli, timeout, threshold);
  14284. }
  14285. #endif
  14286. class EventDispatcher {
  14287. public:
  14288. EventDispatcher() {}
  14289. bool wait_event(DataSink *sink) {
  14290. unique_lock<mutex> lk(m_);
  14291. int id = id_;
  14292. // Wait with timeout to prevent hanging if client disconnects
  14293. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14294. [&] { return cid_ == id; })) {
  14295. return false; // Timeout occurred
  14296. }
  14297. sink->write(message_.data(), message_.size());
  14298. return true;
  14299. }
  14300. void send_event(const string &message) {
  14301. lock_guard<mutex> lk(m_);
  14302. cid_ = id_++;
  14303. message_ = message;
  14304. cv_.notify_all();
  14305. }
  14306. private:
  14307. mutex m_;
  14308. condition_variable cv_;
  14309. atomic_int id_{0};
  14310. atomic_int cid_{-1};
  14311. string message_;
  14312. };
  14313. TEST(ClientInThreadTest, Issue2068) {
  14314. EventDispatcher ed;
  14315. Server svr;
  14316. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14317. res.set_chunked_content_provider("text/event-stream",
  14318. [&](size_t /*offset*/, DataSink &sink) {
  14319. return ed.wait_event(&sink);
  14320. });
  14321. });
  14322. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14323. svr.wait_until_ready();
  14324. thread event_thread([&] {
  14325. int id = 0;
  14326. while (svr.is_running()) {
  14327. this_thread::sleep_for(chrono::milliseconds(500));
  14328. std::stringstream ss;
  14329. ss << "data: " << id << "\n\n";
  14330. ed.send_event(ss.str());
  14331. id++;
  14332. }
  14333. });
  14334. auto se = detail::scope_exit([&] {
  14335. svr.stop();
  14336. listen_thread.join();
  14337. event_thread.join();
  14338. ASSERT_FALSE(svr.is_running());
  14339. });
  14340. {
  14341. auto client = detail::make_unique<Client>(HOST, PORT);
  14342. client->set_read_timeout(std::chrono::minutes(10));
  14343. std::atomic<bool> stop{false};
  14344. std::thread t([&] {
  14345. client->Get("/event1",
  14346. [&](const char *, size_t) -> bool { return !stop; });
  14347. });
  14348. std::this_thread::sleep_for(std::chrono::seconds(2));
  14349. stop = true;
  14350. client->stop();
  14351. t.join();
  14352. // Reset client after thread has finished
  14353. client.reset();
  14354. }
  14355. }
  14356. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14357. auto handled = false;
  14358. Server svr;
  14359. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14360. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14361. auto se = detail::scope_exit([&] {
  14362. svr.stop();
  14363. t.join();
  14364. ASSERT_FALSE(svr.is_running());
  14365. ASSERT_FALSE(handled);
  14366. });
  14367. svr.wait_until_ready();
  14368. // Two Content-Length headers with different values — must be rejected
  14369. auto req = "POST /test HTTP/1.1\r\n"
  14370. "Content-Length: 5\r\n"
  14371. "Content-Length: 10\r\n"
  14372. "\r\n"
  14373. "hello";
  14374. std::string response;
  14375. ASSERT_TRUE(send_request(1, req, &response));
  14376. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14377. response.substr(0, response.find("\r\n")));
  14378. }
  14379. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14380. auto handled = false;
  14381. Server svr;
  14382. svr.Post("/test", [&](const Request &, Response &res) {
  14383. handled = true;
  14384. res.set_content("ok", "text/plain");
  14385. });
  14386. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. t.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. ASSERT_TRUE(handled);
  14392. });
  14393. svr.wait_until_ready();
  14394. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14395. auto req = "POST /test HTTP/1.1\r\n"
  14396. "Content-Length: 5\r\n"
  14397. "Content-Length: 5\r\n"
  14398. "\r\n"
  14399. "hello";
  14400. std::string response;
  14401. ASSERT_TRUE(send_request(1, req, &response));
  14402. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14403. }
  14404. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14405. Server svr;
  14406. svr.Get("/", [](const Request &req, Response &res) {
  14407. EXPECT_EQ(2U, req.trailers.size());
  14408. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14409. // Denied
  14410. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14411. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14412. // Accepted
  14413. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14414. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14415. EXPECT_TRUE(req.has_trailer("X-World"));
  14416. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14417. res.set_content("ok", "text/plain");
  14418. });
  14419. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14420. auto se = detail::scope_exit([&] {
  14421. svr.stop();
  14422. t.join();
  14423. ASSERT_FALSE(svr.is_running());
  14424. });
  14425. svr.wait_until_ready();
  14426. const std::string req = "GET / HTTP/1.1\r\n"
  14427. "Transfer-Encoding: chunked\r\n"
  14428. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14429. "\r\n"
  14430. "0\r\n"
  14431. "Content-Length: 10\r\n"
  14432. "Host: internal.local\r\n"
  14433. "Content-Type: malicious/content\r\n"
  14434. "Cookie: any\r\n"
  14435. "Set-Cookie: any\r\n"
  14436. "X-Forwarded-For: attacker.com\r\n"
  14437. "X-Real-Ip: 1.1.1.1\r\n"
  14438. "X-Hello: hello\r\n"
  14439. "X-World: world\r\n"
  14440. "\r\n";
  14441. std::string res;
  14442. ASSERT_TRUE(send_request(1, req, &res));
  14443. }
  14444. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14445. // several field lines, and the combined value is what has to be parsed. A
  14446. // Trailer field split across lines therefore declares every name it lists;
  14447. // reading only the first line silently drops the trailers the later lines
  14448. // declare. The prohibited-trailer filter still applies to every line.
  14449. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14450. Server svr;
  14451. size_t observed_trailer_count = 0;
  14452. std::string observed_hello;
  14453. std::string observed_world;
  14454. bool observed_content_length = true;
  14455. svr.Get("/", [&](const Request &req, Response &res) {
  14456. observed_trailer_count = req.trailers.size();
  14457. observed_hello = req.get_trailer_value("X-Hello");
  14458. observed_world = req.get_trailer_value("X-World");
  14459. observed_content_length = req.has_trailer("Content-Length");
  14460. res.set_content("ok", "text/plain");
  14461. });
  14462. auto port = svr.bind_to_any_port(HOST);
  14463. thread t = thread([&]() { svr.listen_after_bind(); });
  14464. auto se = detail::scope_exit([&] {
  14465. svr.stop();
  14466. t.join();
  14467. ASSERT_FALSE(svr.is_running());
  14468. });
  14469. svr.wait_until_ready();
  14470. const std::string req = "GET / HTTP/1.1\r\n"
  14471. "Transfer-Encoding: chunked\r\n"
  14472. "Trailer: X-Hello\r\n"
  14473. "Trailer: X-World, Content-Length\r\n"
  14474. "\r\n"
  14475. "0\r\n"
  14476. "X-Hello: hello\r\n"
  14477. "X-World: world\r\n"
  14478. "Content-Length: 10\r\n"
  14479. "\r\n";
  14480. std::string res;
  14481. ASSERT_TRUE(send_request(1, req, &res, port));
  14482. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14483. // Accepted: both field lines contribute to the declared set
  14484. EXPECT_EQ(2U, observed_trailer_count);
  14485. EXPECT_EQ(observed_hello, "hello");
  14486. EXPECT_EQ(observed_world, "world");
  14487. // Denied: a prohibited name stays prohibited on a later field line
  14488. EXPECT_FALSE(observed_content_length);
  14489. }
  14490. // A direct client that is not listed in trusted_proxies must not be able to
  14491. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14492. // the peer address on the actual TCP connection determines whether the
  14493. // header is honored.
  14494. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14495. Server svr;
  14496. // Deliberately does NOT include the loopback address the test client
  14497. // actually connects from, so the direct connection is not a trusted proxy.
  14498. svr.set_trusted_proxies({"203.0.113.66"});
  14499. std::string observed_remote_addr;
  14500. svr.Get("/ip", [&](const Request &req, Response &res) {
  14501. observed_remote_addr = req.remote_addr;
  14502. res.set_content("ok", "text/plain");
  14503. });
  14504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14505. auto se = detail::scope_exit([&] {
  14506. svr.stop();
  14507. t.join();
  14508. ASSERT_FALSE(svr.is_running());
  14509. });
  14510. svr.wait_until_ready();
  14511. Client cli(HOST, PORT);
  14512. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. EXPECT_EQ(StatusCode::OK_200, res->status);
  14515. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14516. // ignored entirely and the real connection-level address retained.
  14517. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14518. observed_remote_addr == "127.0.0.1");
  14519. }
  14520. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14521. Server svr;
  14522. std::string observed_remote_addr;
  14523. std::string observed_xff;
  14524. svr.Get("/ip", [&](const Request &req, Response &res) {
  14525. observed_remote_addr = req.remote_addr;
  14526. observed_xff = req.get_header_value("X-Forwarded-For");
  14527. res.set_content("ok", "text/plain");
  14528. });
  14529. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14530. auto se = detail::scope_exit([&] {
  14531. svr.stop();
  14532. t.join();
  14533. ASSERT_FALSE(svr.is_running());
  14534. });
  14535. svr.wait_until_ready();
  14536. Client cli(HOST, PORT);
  14537. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14539. EXPECT_EQ(StatusCode::OK_200, res->status);
  14540. EXPECT_EQ(observed_xff, "203.0.113.66");
  14541. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14542. observed_remote_addr == "127.0.0.1");
  14543. }
  14544. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14545. Server svr;
  14546. svr.set_trusted_proxies({"203.0.113.66"});
  14547. std::string observed_remote_addr;
  14548. std::string observed_xff;
  14549. svr.Get("/ip", [&](const Request &req, Response &res) {
  14550. observed_remote_addr = req.remote_addr;
  14551. observed_xff = req.get_header_value("X-Forwarded-For");
  14552. res.set_content("ok", "text/plain");
  14553. });
  14554. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14555. auto se = detail::scope_exit([&] {
  14556. svr.stop();
  14557. t.join();
  14558. ASSERT_FALSE(svr.is_running());
  14559. });
  14560. svr.wait_until_ready();
  14561. Client cli(HOST, PORT);
  14562. auto res = cli.Get("/ip");
  14563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14564. EXPECT_EQ(StatusCode::OK_200, res->status);
  14565. EXPECT_EQ(observed_xff, "");
  14566. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14567. observed_remote_addr == "127.0.0.1");
  14568. }
  14569. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14570. Server svr;
  14571. // Include the loopback address the test client actually connects from, so
  14572. // the direct connection itself is recognized as the trusted proxy hop.
  14573. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14574. std::string observed_remote_addr;
  14575. std::string observed_xff;
  14576. svr.Get("/ip", [&](const Request &req, Response &res) {
  14577. observed_remote_addr = req.remote_addr;
  14578. observed_xff = req.get_header_value("X-Forwarded-For");
  14579. res.set_content("ok", "text/plain");
  14580. });
  14581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14582. auto se = detail::scope_exit([&] {
  14583. svr.stop();
  14584. t.join();
  14585. ASSERT_FALSE(svr.is_running());
  14586. });
  14587. svr.wait_until_ready();
  14588. Client cli(HOST, PORT);
  14589. auto res = cli.Get(
  14590. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14592. EXPECT_EQ(StatusCode::OK_200, res->status);
  14593. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14594. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14595. }
  14596. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14597. Server svr;
  14598. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14599. std::string observed_remote_addr;
  14600. std::string observed_xff;
  14601. svr.Get("/ip", [&](const Request &req, Response &res) {
  14602. observed_remote_addr = req.remote_addr;
  14603. observed_xff = req.get_header_value("X-Forwarded-For");
  14604. res.set_content("ok", "text/plain");
  14605. });
  14606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. ASSERT_FALSE(svr.is_running());
  14611. });
  14612. svr.wait_until_ready();
  14613. Client cli(HOST, PORT);
  14614. auto res = cli.Get(
  14615. "/ip",
  14616. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14618. EXPECT_EQ(StatusCode::OK_200, res->status);
  14619. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14620. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14621. }
  14622. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14623. Server svr;
  14624. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14625. std::string observed_remote_addr;
  14626. std::string observed_xff;
  14627. svr.Get("/ip", [&](const Request &req, Response &res) {
  14628. observed_remote_addr = req.remote_addr;
  14629. observed_xff = req.get_header_value("X-Forwarded-For");
  14630. res.set_content("ok", "text/plain");
  14631. });
  14632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14633. auto se = detail::scope_exit([&] {
  14634. svr.stop();
  14635. t.join();
  14636. ASSERT_FALSE(svr.is_running());
  14637. });
  14638. svr.wait_until_ready();
  14639. Client cli(HOST, PORT);
  14640. auto res = cli.Get(
  14641. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14643. EXPECT_EQ(StatusCode::OK_200, res->status);
  14644. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14645. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14646. // and must not be selected.
  14647. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14648. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14649. }
  14650. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14651. Server svr;
  14652. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14653. std::string observed_remote_addr;
  14654. svr.Get("/ip", [&](const Request &req, Response &res) {
  14655. observed_remote_addr = req.remote_addr;
  14656. res.set_content("ok", "text/plain");
  14657. });
  14658. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14659. auto se = detail::scope_exit([&] {
  14660. svr.stop();
  14661. t.join();
  14662. ASSERT_FALSE(svr.is_running());
  14663. });
  14664. svr.wait_until_ready();
  14665. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14666. // a forged address and the trusted proxy's own address; the forged value must
  14667. // not win over the address the trusted proxy actually recorded.
  14668. Client cli(HOST, PORT);
  14669. auto res = cli.Get(
  14670. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14672. EXPECT_EQ(StatusCode::OK_200, res->status);
  14673. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14674. }
  14675. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14676. Server svr;
  14677. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14678. std::string observed_remote_addr;
  14679. std::string observed_xff;
  14680. svr.Get("/ip", [&](const Request &req, Response &res) {
  14681. observed_remote_addr = req.remote_addr;
  14682. observed_xff = req.get_header_value("X-Forwarded-For");
  14683. res.set_content("ok", "text/plain");
  14684. });
  14685. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14686. auto se = detail::scope_exit([&] {
  14687. svr.stop();
  14688. t.join();
  14689. ASSERT_FALSE(svr.is_running());
  14690. });
  14691. svr.wait_until_ready();
  14692. Client cli(HOST, PORT);
  14693. auto res = cli.Get(
  14694. "/ip",
  14695. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14697. EXPECT_EQ(StatusCode::OK_200, res->status);
  14698. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14699. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14700. }
  14701. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14702. Server svr;
  14703. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14704. std::string observed_remote_addr;
  14705. std::string observed_xff;
  14706. svr.Get("/ip", [&](const Request &req, Response &res) {
  14707. observed_remote_addr = req.remote_addr;
  14708. observed_xff = req.get_header_value("X-Forwarded-For");
  14709. res.set_content("ok", "text/plain");
  14710. });
  14711. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14712. auto se = detail::scope_exit([&] {
  14713. svr.stop();
  14714. t.join();
  14715. ASSERT_FALSE(svr.is_running());
  14716. });
  14717. svr.wait_until_ready();
  14718. std::string raw_req =
  14719. "GET /ip HTTP/1.1\r\n"
  14720. "Host: localhost\r\n"
  14721. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14722. "Connection: close\r\n"
  14723. "\r\n";
  14724. std::string out;
  14725. ASSERT_TRUE(send_request(5, raw_req, &out));
  14726. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14727. // Header parser trims surrounding whitespace of the header value
  14728. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14729. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14730. }
  14731. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14732. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14733. // their own X-Forwarded-For as a separate field line rather than extending the
  14734. // one the client sent, so every occurrence has to be taken into account.
  14735. // Reading only the first one hands back the address the client chose.
  14736. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14737. Server svr;
  14738. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14739. std::string observed_remote_addr;
  14740. size_t observed_xff_count = 0;
  14741. svr.Get("/ip", [&](const Request &req, Response &res) {
  14742. observed_remote_addr = req.remote_addr;
  14743. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14744. res.set_content("ok", "text/plain");
  14745. });
  14746. auto port = svr.bind_to_any_port(HOST);
  14747. thread t = thread([&]() { svr.listen_after_bind(); });
  14748. auto se = detail::scope_exit([&] {
  14749. svr.stop();
  14750. t.join();
  14751. ASSERT_FALSE(svr.is_running());
  14752. });
  14753. svr.wait_until_ready();
  14754. // The client supplies the first field line; the trusted proxy appends the
  14755. // address it observed as a second one.
  14756. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14757. "Host: localhost\r\n"
  14758. "X-Forwarded-For: 1.2.3.4\r\n"
  14759. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14760. "Connection: close\r\n"
  14761. "\r\n";
  14762. std::string out;
  14763. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14764. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14765. EXPECT_EQ(observed_xff_count, 2U);
  14766. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14767. // The same chain spread over one field line per hop derives the same client
  14768. // address, i.e. the split and the comma-joined representations agree.
  14769. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14770. "Host: localhost\r\n"
  14771. "X-Forwarded-For: 1.2.3.4\r\n"
  14772. "X-Forwarded-For: 198.51.100.23\r\n"
  14773. "X-Forwarded-For: 192.0.2.45\r\n"
  14774. "Connection: close\r\n"
  14775. "\r\n";
  14776. out.clear();
  14777. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14778. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14779. EXPECT_EQ(observed_xff_count, 3U);
  14780. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14781. }
  14782. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14783. // crash the server (it used to call front() on an empty vector inside
  14784. // get_client_ip). The connection-level remote address must be retained instead.
  14785. static void run_malformed_xff_test(const std::string &xff_value) {
  14786. Server svr;
  14787. svr.set_trusted_proxies({"192.0.2.45"});
  14788. std::string observed_remote_addr;
  14789. svr.Get("/ip", [&](const Request &req, Response &res) {
  14790. observed_remote_addr = req.remote_addr;
  14791. res.set_content("ok", "text/plain");
  14792. });
  14793. int port = 0;
  14794. thread t = thread([&]() {
  14795. port = svr.bind_to_any_port(HOST);
  14796. svr.listen_after_bind();
  14797. });
  14798. auto se = detail::scope_exit([&] {
  14799. svr.stop();
  14800. t.join();
  14801. ASSERT_FALSE(svr.is_running());
  14802. });
  14803. svr.wait_until_ready();
  14804. Client cli(HOST, port);
  14805. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14807. EXPECT_EQ(StatusCode::OK_200, res->status);
  14808. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14809. observed_remote_addr == "127.0.0.1");
  14810. }
  14811. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14812. run_malformed_xff_test("");
  14813. }
  14814. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14815. run_malformed_xff_test(",");
  14816. }
  14817. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14818. run_malformed_xff_test(", , ,");
  14819. }
  14820. // The same rule applies to Accept: a request whose acceptable types are spread
  14821. // over several field lines must be negotiated against all of them.
  14822. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14823. // case-insensitive connection options. Comparing the whole field value against
  14824. // one option misses a client that sends several of them, and misses every
  14825. // casing but the one written in the comparison.
  14826. //
  14827. // Sends req, reads the response, then reuses the same socket for a second
  14828. // request to find out whether the server kept the connection.
  14829. static void probe_connection_reuse(int port, const std::string &req,
  14830. bool *announced_close, bool *reusable) {
  14831. auto error = Error::Success;
  14832. auto sock = detail::create_client_socket(
  14833. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14834. /*connection_timeout_sec=*/5, 0,
  14835. /*read_timeout_sec=*/1, 0,
  14836. /*write_timeout_sec=*/5, 0, std::string(), error);
  14837. ASSERT_NE(sock, INVALID_SOCKET);
  14838. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14839. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14840. "Host: localhost\r\n"
  14841. "Connection: close\r\n"
  14842. "\r\n";
  14843. std::string first_response;
  14844. std::string second_response;
  14845. detail::process_client_socket(
  14846. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14847. [&](Stream &strm) {
  14848. if (strm.write(req.data(), req.size()) !=
  14849. static_cast<ssize_t>(req.size())) {
  14850. return false;
  14851. }
  14852. char buf[512];
  14853. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14854. // Headers plus the two-byte body of the handler below
  14855. while (reader.getline()) {
  14856. first_response += reader.ptr();
  14857. if (first_response.find("ok") != std::string::npos) { break; }
  14858. }
  14859. if (strm.write(second.data(), second.size()) !=
  14860. static_cast<ssize_t>(second.size())) {
  14861. return true;
  14862. }
  14863. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14864. while (reader2.getline()) {
  14865. second_response += reader2.ptr();
  14866. if (second_response.find("ok") != std::string::npos) { break; }
  14867. }
  14868. return true;
  14869. });
  14870. *announced_close =
  14871. first_response.find("Connection: close") != std::string::npos;
  14872. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14873. }
  14874. class ConnectionTokenTest : public ::testing::Test {
  14875. protected:
  14876. void SetUp() override {
  14877. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14878. res.set_content("ok", "text/plain");
  14879. });
  14880. port_ = svr_.bind_to_any_port(HOST);
  14881. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14882. svr_.wait_until_ready();
  14883. }
  14884. void TearDown() override {
  14885. svr_.stop();
  14886. if (thread_.joinable()) { thread_.join(); }
  14887. }
  14888. Server svr_;
  14889. int port_ = 0;
  14890. thread thread_;
  14891. };
  14892. // "close" alongside another option still closes the connection, and the
  14893. // response says so rather than leaving the peer to discover it.
  14894. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14895. bool announced_close = false;
  14896. bool reusable = true;
  14897. probe_connection_reuse(port_,
  14898. "GET /keepalive HTTP/1.1\r\n"
  14899. "Host: localhost\r\n"
  14900. "Connection: keep-alive, close\r\n"
  14901. "\r\n",
  14902. &announced_close, &reusable);
  14903. EXPECT_TRUE(announced_close);
  14904. EXPECT_FALSE(reusable);
  14905. }
  14906. // "close" split over two field lines is the same list, so it is honored too.
  14907. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14908. bool announced_close = false;
  14909. bool reusable = true;
  14910. probe_connection_reuse(port_,
  14911. "GET /keepalive HTTP/1.1\r\n"
  14912. "Host: localhost\r\n"
  14913. "Connection: keep-alive\r\n"
  14914. "Connection: close\r\n"
  14915. "\r\n",
  14916. &announced_close, &reusable);
  14917. EXPECT_TRUE(announced_close);
  14918. EXPECT_FALSE(reusable);
  14919. }
  14920. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14921. // keep-alive in the spelling everyone actually sends keeps its connection.
  14922. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14923. bool announced_close = false;
  14924. bool reusable = false;
  14925. probe_connection_reuse(port_,
  14926. "GET /keepalive HTTP/1.0\r\n"
  14927. "Host: localhost\r\n"
  14928. "Connection: keep-alive\r\n"
  14929. "\r\n",
  14930. &announced_close, &reusable);
  14931. EXPECT_FALSE(announced_close);
  14932. EXPECT_TRUE(reusable);
  14933. }
  14934. // A token the value merely contains is not the token itself.
  14935. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14936. bool announced_close = false;
  14937. bool reusable = false;
  14938. probe_connection_reuse(port_,
  14939. "GET /keepalive HTTP/1.1\r\n"
  14940. "Host: localhost\r\n"
  14941. "Connection: notclose\r\n"
  14942. "\r\n",
  14943. &announced_close, &reusable);
  14944. EXPECT_FALSE(announced_close);
  14945. EXPECT_TRUE(reusable);
  14946. }
  14947. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14948. Server svr;
  14949. std::vector<std::string> observed_types;
  14950. svr.Get("/", [&](const Request &req, Response &res) {
  14951. observed_types = req.accept_content_types;
  14952. res.set_content("ok", "text/plain");
  14953. });
  14954. auto port = svr.bind_to_any_port(HOST);
  14955. thread t = thread([&]() { svr.listen_after_bind(); });
  14956. auto se = detail::scope_exit([&] {
  14957. svr.stop();
  14958. t.join();
  14959. ASSERT_FALSE(svr.is_running());
  14960. });
  14961. svr.wait_until_ready();
  14962. Client cli(HOST, port);
  14963. Headers headers;
  14964. headers.emplace("Accept", "text/plain;q=0.5");
  14965. headers.emplace("Accept", "application/json");
  14966. auto res = cli.Get("/", headers);
  14967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14968. EXPECT_EQ(StatusCode::OK_200, res->status);
  14969. // Sorted by q-value, so the second field line's type comes first
  14970. ASSERT_EQ(2U, observed_types.size());
  14971. EXPECT_EQ("application/json", observed_types[0]);
  14972. EXPECT_EQ("text/plain", observed_types[1]);
  14973. }
  14974. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14975. // empty field line must not contribute a bare comma to the combined value.
  14976. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14977. // turn a legal request into 400 Bad Request.
  14978. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14979. Server svr;
  14980. std::vector<std::string> observed_types;
  14981. svr.Get("/", [&](const Request &req, Response &res) {
  14982. observed_types = req.accept_content_types;
  14983. res.set_content("ok", "text/plain");
  14984. });
  14985. auto port = svr.bind_to_any_port(HOST);
  14986. thread t = thread([&]() { svr.listen_after_bind(); });
  14987. auto se = detail::scope_exit([&] {
  14988. svr.stop();
  14989. t.join();
  14990. ASSERT_FALSE(svr.is_running());
  14991. });
  14992. svr.wait_until_ready();
  14993. // Empty first field line, then a real one
  14994. std::string raw_req = "GET / HTTP/1.1\r\n"
  14995. "Host: localhost\r\n"
  14996. "Accept:\r\n"
  14997. "Accept: application/json\r\n"
  14998. "Connection: close\r\n"
  14999. "\r\n";
  15000. std::string out;
  15001. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15002. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15003. ASSERT_EQ(1U, observed_types.size());
  15004. EXPECT_EQ("application/json", observed_types[0]);
  15005. }
  15006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15007. // An encoding offered on a later Accept-Encoding field line is still offered.
  15008. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15009. Server svr;
  15010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15011. res.set_content(std::string(1024, 'x'), "text/plain");
  15012. });
  15013. auto port = svr.bind_to_any_port(HOST);
  15014. thread t = thread([&]() { svr.listen_after_bind(); });
  15015. auto se = detail::scope_exit([&] {
  15016. svr.stop();
  15017. t.join();
  15018. ASSERT_FALSE(svr.is_running());
  15019. });
  15020. svr.wait_until_ready();
  15021. Client cli(HOST, port);
  15022. cli.set_decompress(false);
  15023. Headers headers;
  15024. headers.emplace("Accept-Encoding", "identity");
  15025. headers.emplace("Accept-Encoding", "gzip");
  15026. auto res = cli.Get("/", headers);
  15027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15028. EXPECT_EQ(StatusCode::OK_200, res->status);
  15029. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15030. }
  15031. #endif
  15032. #ifndef _WIN32
  15033. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15034. Server svr;
  15035. svr.Post("/post", [&](const Request &req, Response &res) {
  15036. res.set_content(req.body, "text/plain");
  15037. });
  15038. svr.Put("/put", [&](const Request &req, Response &res) {
  15039. res.set_content(req.body, "text/plain");
  15040. });
  15041. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15042. res.set_content(req.body, "text/plain");
  15043. });
  15044. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15045. res.set_content(req.body, "text/plain");
  15046. });
  15047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15048. auto se = detail::scope_exit([&] {
  15049. svr.stop();
  15050. t.join();
  15051. ASSERT_FALSE(svr.is_running());
  15052. });
  15053. svr.wait_until_ready();
  15054. std::string resp;
  15055. // POST without Content-Length
  15056. ASSERT_TRUE(send_request(5,
  15057. "POST /post HTTP/1.1\r\n"
  15058. "Host: localhost\r\n"
  15059. "Connection: close\r\n"
  15060. "\r\n",
  15061. &resp));
  15062. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15063. // PUT without Content-Length
  15064. resp.clear();
  15065. ASSERT_TRUE(send_request(5,
  15066. "PUT /put HTTP/1.1\r\n"
  15067. "Host: localhost\r\n"
  15068. "Connection: close\r\n"
  15069. "\r\n",
  15070. &resp));
  15071. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15072. // PATCH without Content-Length
  15073. resp.clear();
  15074. ASSERT_TRUE(send_request(5,
  15075. "PATCH /patch HTTP/1.1\r\n"
  15076. "Host: localhost\r\n"
  15077. "Connection: close\r\n"
  15078. "\r\n",
  15079. &resp));
  15080. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15081. // DELETE without Content-Length
  15082. resp.clear();
  15083. ASSERT_TRUE(send_request(5,
  15084. "DELETE /delete HTTP/1.1\r\n"
  15085. "Host: localhost\r\n"
  15086. "Connection: close\r\n"
  15087. "\r\n",
  15088. &resp));
  15089. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15090. }
  15091. #endif
  15092. //==============================================================================
  15093. // open_stream() Tests
  15094. //==============================================================================
  15095. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15096. std::string result;
  15097. char buf[8192];
  15098. ssize_t n;
  15099. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15100. result.append(buf, static_cast<size_t>(n));
  15101. }
  15102. return result;
  15103. }
  15104. // Mock stream for unit tests
  15105. class MockStream : public Stream {
  15106. public:
  15107. std::string data;
  15108. size_t pos = 0;
  15109. ssize_t error_after = -1; // -1 = no error
  15110. explicit MockStream(const std::string &d, ssize_t err = -1)
  15111. : data(d), error_after(err) {}
  15112. bool is_readable() const override { return true; }
  15113. bool wait_readable() const override { return true; }
  15114. bool wait_writable() const override { return true; }
  15115. ssize_t read(char *ptr, size_t size) override {
  15116. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15117. if (pos >= data.size()) return 0;
  15118. size_t limit =
  15119. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15120. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15121. std::memcpy(ptr, data.data() + pos, to_read);
  15122. pos += to_read;
  15123. return static_cast<ssize_t>(to_read);
  15124. }
  15125. ssize_t write(const char *, size_t) override { return -1; }
  15126. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15127. ip = "127.0.0.1";
  15128. port = 0;
  15129. }
  15130. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15131. ip = "127.0.0.1";
  15132. port = 0;
  15133. }
  15134. socket_t socket() const override { return INVALID_SOCKET; }
  15135. time_t duration() const override { return 0; }
  15136. };
  15137. TEST(StreamHandleTest, Basic) {
  15138. ClientImpl::StreamHandle handle;
  15139. EXPECT_FALSE(handle.is_valid());
  15140. handle.response = detail::make_unique<Response>();
  15141. handle.error = Error::Connection;
  15142. EXPECT_FALSE(handle.is_valid());
  15143. handle.error = Error::Success;
  15144. EXPECT_TRUE(handle.is_valid());
  15145. }
  15146. TEST(BodyReaderTest, Basic) {
  15147. MockStream stream("Hello, World!");
  15148. detail::BodyReader reader;
  15149. reader.stream = &stream;
  15150. reader.content_length = 13;
  15151. char buf[32];
  15152. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15153. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15154. EXPECT_TRUE(reader.eof);
  15155. }
  15156. TEST(BodyReaderTest, NoStream) {
  15157. detail::BodyReader reader;
  15158. char buf[32];
  15159. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15160. EXPECT_EQ(Error::Connection, reader.last_error);
  15161. }
  15162. TEST(BodyReaderTest, Error) {
  15163. MockStream stream("Hello, World!", 5);
  15164. detail::BodyReader reader;
  15165. reader.stream = &stream;
  15166. reader.content_length = 13;
  15167. char buf[32];
  15168. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15169. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15170. EXPECT_EQ(Error::Read, reader.last_error);
  15171. }
  15172. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15173. // Mock-based StreamHandle tests relying on private internals are removed.
  15174. class OpenStreamTest : public ::testing::Test {
  15175. protected:
  15176. void SetUp() override {
  15177. svr_.Get("/hello", [](const Request &, Response &res) {
  15178. res.set_content("Hello World!", "text/plain");
  15179. });
  15180. svr_.Get("/large", [](const Request &, Response &res) {
  15181. res.set_content(std::string(10000, 'X'), "text/plain");
  15182. });
  15183. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15184. res.set_content("Hello World!", "image/jpeg");
  15185. res.set_header("Content-Encoding", "UTF-8");
  15186. });
  15187. svr_.Get("/chunked", [](const Request &, Response &res) {
  15188. res.set_chunked_content_provider("text/plain",
  15189. [](size_t offset, DataSink &sink) {
  15190. if (offset < 15) {
  15191. sink.write("chunk", 5);
  15192. return true;
  15193. }
  15194. sink.done();
  15195. return true;
  15196. });
  15197. });
  15198. svr_.Get("/compressible", [](const Request &, Response &res) {
  15199. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15200. DataSink &sink) {
  15201. if (offset < 100 * 1024) {
  15202. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15203. sink.write(chunk.data(), chunk.size());
  15204. return true;
  15205. }
  15206. sink.done();
  15207. return true;
  15208. });
  15209. });
  15210. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15211. [](const Request & /*req*/, Response &res) {
  15212. auto i = new int(0);
  15213. res.set_header("Trailer", "Content-Length, X-Allowed");
  15214. res.set_chunked_content_provider(
  15215. "text/plain",
  15216. [i](size_t /*offset*/, DataSink &sink) {
  15217. switch (*i) {
  15218. case 0: sink.os << "123"; break;
  15219. case 1: sink.os << "456"; break;
  15220. case 2: sink.os << "789"; break;
  15221. case 3: {
  15222. sink.done_with_trailer(
  15223. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15224. } break;
  15225. }
  15226. (*i)++;
  15227. return true;
  15228. },
  15229. [i](bool success) {
  15230. EXPECT_TRUE(success);
  15231. delete i;
  15232. });
  15233. });
  15234. // Echo headers endpoint for header-related tests
  15235. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15236. std::string body;
  15237. for (const auto &h : req.headers) {
  15238. body.append(h.first);
  15239. body.push_back(':');
  15240. body.append(h.second);
  15241. body.push_back('\n');
  15242. }
  15243. res.set_content(body, "text/plain");
  15244. });
  15245. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15246. std::string body;
  15247. for (const auto &h : req.headers) {
  15248. body.append(h.first);
  15249. body.push_back(':');
  15250. body.append(h.second);
  15251. body.push_back('\n');
  15252. }
  15253. res.set_content(body, "text/plain");
  15254. });
  15255. port_ = svr_.bind_to_any_port("127.0.0.1");
  15256. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15257. svr_.wait_until_ready();
  15258. }
  15259. void TearDown() override {
  15260. svr_.stop();
  15261. if (thread_.joinable()) thread_.join();
  15262. }
  15263. Server svr_;
  15264. std::thread thread_;
  15265. int port_ = 0;
  15266. };
  15267. TEST_F(OpenStreamTest, Basic) {
  15268. Client cli("127.0.0.1", port_);
  15269. auto handle = cli.open_stream("GET", "/hello");
  15270. EXPECT_TRUE(handle.is_valid());
  15271. EXPECT_EQ("Hello World!", read_all(handle));
  15272. }
  15273. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15274. Client cli("127.0.0.1", port_);
  15275. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15276. ASSERT_TRUE(handle.is_valid());
  15277. EXPECT_EQ("Hello World!", read_all(handle));
  15278. }
  15279. TEST_F(OpenStreamTest, SmallBuffer) {
  15280. Client cli("127.0.0.1", port_);
  15281. auto handle = cli.open_stream("GET", "/hello");
  15282. std::string result;
  15283. char buf[4];
  15284. ssize_t n;
  15285. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15286. result.append(buf, static_cast<size_t>(n));
  15287. EXPECT_EQ("Hello World!", result);
  15288. }
  15289. TEST_F(OpenStreamTest, DefaultHeaders) {
  15290. Client cli("127.0.0.1", port_);
  15291. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15292. {
  15293. auto handle = cli.open_stream("GET", "/echo-headers");
  15294. ASSERT_TRUE(handle.is_valid());
  15295. auto body = read_all(handle);
  15296. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15297. std::string::npos);
  15298. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15299. std::string::npos);
  15300. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15301. }
  15302. // open_stream POST with body and no explicit content_type should NOT add
  15303. // text/plain Content-Type (behavior differs from non-streaming path), but
  15304. // should include Content-Length
  15305. {
  15306. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15307. ASSERT_TRUE(handle.is_valid());
  15308. auto body = read_all(handle);
  15309. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15310. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15311. }
  15312. // open_stream POST with explicit Content-Type should preserve it
  15313. {
  15314. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15315. {{"Content-Type", "application/custom"}},
  15316. "{}", "application/custom");
  15317. ASSERT_TRUE(handle.is_valid());
  15318. auto body = read_all(handle);
  15319. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15320. }
  15321. // User-specified User-Agent must not be overwritten for stream API
  15322. {
  15323. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15324. {{"User-Agent", "MyAgent/1.2"}});
  15325. ASSERT_TRUE(handle.is_valid());
  15326. auto body = read_all(handle);
  15327. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15328. }
  15329. }
  15330. TEST_F(OpenStreamTest, Large) {
  15331. Client cli("127.0.0.1", port_);
  15332. auto handle = cli.open_stream("GET", "/large");
  15333. EXPECT_EQ(10000u, read_all(handle).size());
  15334. }
  15335. TEST_F(OpenStreamTest, ConnectionError) {
  15336. Client cli("127.0.0.1", 9999);
  15337. auto handle = cli.open_stream("GET", "/hello");
  15338. EXPECT_FALSE(handle.is_valid());
  15339. }
  15340. TEST_F(OpenStreamTest, Chunked) {
  15341. Client cli("127.0.0.1", port_);
  15342. auto handle = cli.open_stream("GET", "/chunked");
  15343. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15344. "Transfer-Encoding") == "chunked");
  15345. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15346. }
  15347. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15348. Client cli("127.0.0.1", port_);
  15349. auto handle =
  15350. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15351. ASSERT_TRUE(handle.is_valid());
  15352. // Consume body to allow trailers to be received/parsed
  15353. auto body = read_all(handle);
  15354. // Explicitly parse trailers (ensure trailers are available for assertion)
  15355. handle.parse_trailers_if_needed();
  15356. EXPECT_EQ(std::string("123456789"), body);
  15357. // The response should include a Trailer header declaring both names
  15358. ASSERT_TRUE(handle.response);
  15359. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15360. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15361. handle.response->get_header_value("Trailer"));
  15362. // Prohibited trailer must not be present
  15363. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15364. // Allowed trailer should be present
  15365. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15366. EXPECT_EQ(std::string("yes"),
  15367. handle.response->get_trailer_value("X-Allowed"));
  15368. // Verify trailers are NOT present as regular headers
  15369. EXPECT_EQ(std::string(""),
  15370. handle.response->get_header_value("Content-Length"));
  15371. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15372. }
  15373. static std::thread serve_single_response(std::promise<int> &port_promise,
  15374. const std::string &response) {
  15375. return std::thread([&port_promise, response] {
  15376. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15377. default_socket_options(srv);
  15378. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15379. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15380. sockaddr_in addr{};
  15381. addr.sin_family = AF_INET;
  15382. addr.sin_port = htons(0); // Let OS assign a free port
  15383. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15384. int opt = 1;
  15385. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15386. #ifdef _WIN32
  15387. reinterpret_cast<const char *>(&opt),
  15388. #else
  15389. &opt,
  15390. #endif
  15391. sizeof(opt));
  15392. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15393. ::listen(srv, 1) != 0) {
  15394. port_promise.set_value(-1);
  15395. detail::close_socket(srv);
  15396. return;
  15397. }
  15398. socklen_t addr_len = sizeof(addr);
  15399. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15400. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15401. sockaddr_in cli_addr{};
  15402. socklen_t cli_len = sizeof(cli_addr);
  15403. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15404. if (cli != INVALID_SOCKET) {
  15405. // Read the complete HTTP request (until the blank line that terminates
  15406. // headers) before sending the response. If the server closes the socket
  15407. // while the client's request data is still unread in the kernel receive
  15408. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15409. // connection on both sides: it discards the client's receive buffer
  15410. // (which already holds our response) and causes any in-progress write on
  15411. // the client to fail with ECONNRESET. Reading all request data first
  15412. // ensures close() emits a graceful FIN.
  15413. {
  15414. char rbuf[256];
  15415. std::string req;
  15416. while (req.find("\r\n\r\n") == std::string::npos) {
  15417. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15418. if (n <= 0) { break; }
  15419. req.append(rbuf, static_cast<size_t>(n));
  15420. }
  15421. }
  15422. ::send(cli,
  15423. #ifdef _WIN32
  15424. static_cast<const char *>(response.c_str()),
  15425. static_cast<int>(response.size()),
  15426. #else
  15427. response.c_str(), response.size(),
  15428. #endif
  15429. 0);
  15430. detail::close_socket(cli);
  15431. }
  15432. detail::close_socket(srv);
  15433. });
  15434. }
  15435. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15436. #ifndef _WIN32
  15437. signal(SIGPIPE, SIG_IGN);
  15438. #endif
  15439. std::promise<int> port_promise;
  15440. auto port_future = port_promise.get_future();
  15441. auto server_thread =
  15442. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15443. "Content-Type: text/plain\r\n"
  15444. "Content-Length: not-a-number\r\n"
  15445. "Connection: close\r\n"
  15446. "\r\n"
  15447. "hello");
  15448. auto port = port_future.get();
  15449. ASSERT_GT(port, 0);
  15450. Client cli("127.0.0.1", port);
  15451. auto handle = cli.open_stream("GET", "/");
  15452. EXPECT_FALSE(handle.is_valid());
  15453. server_thread.join();
  15454. }
  15455. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15456. #ifndef _WIN32
  15457. signal(SIGPIPE, SIG_IGN);
  15458. #endif
  15459. std::promise<int> port_promise;
  15460. auto port_future = port_promise.get_future();
  15461. auto server_thread = serve_single_response(
  15462. port_promise, "HTTP/1.1 200 OK\r\n"
  15463. "Content-Type: text/plain\r\n"
  15464. "Content-Length: 99999999999999999999999999\r\n"
  15465. "Connection: close\r\n"
  15466. "\r\n"
  15467. "hello");
  15468. auto port = port_future.get();
  15469. ASSERT_GT(port, 0);
  15470. // Historically std::stoull would throw std::out_of_range here and crash
  15471. // the process, then parsing silently clamped to a bogus framing length and
  15472. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15473. // so the stream fails to open, matching the not-a-number case above. The
  15474. // process still must NOT terminate.
  15475. Client cli("127.0.0.1", port);
  15476. auto handle = cli.open_stream("GET", "/");
  15477. EXPECT_FALSE(handle.is_valid());
  15478. server_thread.join();
  15479. }
  15480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15481. TEST_F(OpenStreamTest, Gzip) {
  15482. Client cli("127.0.0.1", port_);
  15483. auto handle = cli.open_stream("GET", "/compressible", {},
  15484. {{"Accept-Encoding", "gzip"}});
  15485. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15486. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15487. }
  15488. #endif
  15489. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15490. TEST_F(OpenStreamTest, Brotli) {
  15491. Client cli("127.0.0.1", port_);
  15492. auto handle =
  15493. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15494. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15495. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15496. }
  15497. #endif
  15498. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15499. TEST_F(OpenStreamTest, Zstd) {
  15500. Client cli("127.0.0.1", port_);
  15501. auto handle = cli.open_stream("GET", "/compressible", {},
  15502. {{"Accept-Encoding", "zstd"}});
  15503. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15504. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15505. }
  15506. #endif
  15507. #ifdef CPPHTTPLIB_SSL_ENABLED
  15508. class SSLOpenStreamTest : public ::testing::Test {
  15509. protected:
  15510. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15511. void SetUp() override {
  15512. svr_.Get("/hello", [](const Request &, Response &res) {
  15513. res.set_content("Hello SSL World!", "text/plain");
  15514. });
  15515. svr_.Get("/chunked", [](const Request &, Response &res) {
  15516. res.set_chunked_content_provider("text/plain",
  15517. [](size_t offset, DataSink &sink) {
  15518. if (offset < 15) {
  15519. sink.write("chunk", 5);
  15520. return true;
  15521. }
  15522. sink.done();
  15523. return true;
  15524. });
  15525. });
  15526. svr_.Post("/echo", [](const Request &req, Response &res) {
  15527. res.set_content(req.body, req.get_header_value("Content-Type"));
  15528. });
  15529. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15530. std::string body = req.body;
  15531. res.set_chunked_content_provider(
  15532. "text/plain", [body](size_t offset, DataSink &sink) {
  15533. if (offset < body.size()) {
  15534. sink.write(body.data() + offset, body.size() - offset);
  15535. }
  15536. sink.done();
  15537. return true;
  15538. });
  15539. });
  15540. port_ = svr_.bind_to_any_port("127.0.0.1");
  15541. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15542. svr_.wait_until_ready();
  15543. }
  15544. void TearDown() override {
  15545. svr_.stop();
  15546. if (thread_.joinable()) thread_.join();
  15547. }
  15548. SSLServer svr_;
  15549. std::thread thread_;
  15550. int port_ = 0;
  15551. };
  15552. TEST_F(SSLOpenStreamTest, Basic) {
  15553. SSLClient cli("127.0.0.1", port_);
  15554. cli.enable_server_certificate_verification(false);
  15555. auto handle = cli.open_stream("GET", "/hello");
  15556. ASSERT_TRUE(handle.is_valid());
  15557. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15558. }
  15559. TEST_F(SSLOpenStreamTest, Chunked) {
  15560. SSLClient cli("127.0.0.1", port_);
  15561. cli.enable_server_certificate_verification(false);
  15562. auto handle = cli.open_stream("GET", "/chunked");
  15563. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15564. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15565. "Transfer-Encoding") == "chunked");
  15566. auto body = read_all(handle);
  15567. EXPECT_EQ("chunkchunkchunk", body);
  15568. }
  15569. TEST_F(SSLOpenStreamTest, Post) {
  15570. SSLClient cli("127.0.0.1", port_);
  15571. cli.enable_server_certificate_verification(false);
  15572. auto handle =
  15573. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15574. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15575. EXPECT_EQ(200, handle.response->status);
  15576. auto body = read_all(handle);
  15577. EXPECT_EQ("Hello SSL POST", body);
  15578. }
  15579. TEST_F(SSLOpenStreamTest, PostChunked) {
  15580. SSLClient cli("127.0.0.1", port_);
  15581. cli.enable_server_certificate_verification(false);
  15582. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15583. "Chunked SSL Data", "text/plain");
  15584. ASSERT_TRUE(handle.is_valid());
  15585. EXPECT_EQ(200, handle.response->status);
  15586. auto body = read_all(handle);
  15587. EXPECT_EQ("Chunked SSL Data", body);
  15588. }
  15589. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15590. // Content-Length is terminated by the server closing the connection. When the
  15591. // SSL peer sends a close_notify after the body, the client must treat it as a
  15592. // clean EOF and return a successful response rather than an error.
  15593. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15595. ASSERT_TRUE(svr.is_valid());
  15596. svr.set_keep_alive_max_count(1);
  15597. const std::string expected_body = "Hello from connection-close response!";
  15598. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15599. res.set_content_provider("text/plain",
  15600. [&](size_t offset, DataSink &sink) -> bool {
  15601. if (offset < expected_body.size()) {
  15602. sink.write(expected_body.data() + offset,
  15603. expected_body.size() - offset);
  15604. }
  15605. sink.done();
  15606. return true;
  15607. });
  15608. });
  15609. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15610. auto se = detail::scope_exit([&] {
  15611. svr.stop();
  15612. listen_thread.join();
  15613. ASSERT_FALSE(svr.is_running());
  15614. });
  15615. svr.wait_until_ready();
  15616. SSLClient cli(HOST, PORT);
  15617. cli.enable_server_certificate_verification(false);
  15618. auto res = cli.Get("/no-content-length");
  15619. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15620. EXPECT_EQ(StatusCode::OK_200, res->status);
  15621. EXPECT_EQ(expected_body, res->body);
  15622. }
  15623. #endif // CPPHTTPLIB_SSL_ENABLED
  15624. //==============================================================================
  15625. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15626. // results for various scenarios.
  15627. //==============================================================================
  15628. TEST(ParityTest, GetVsOpenStream) {
  15629. Server svr;
  15630. const std::string path = "/parity";
  15631. const std::string content = "Parity test content: hello world";
  15632. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15633. res.set_content(content, "text/plain");
  15634. });
  15635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15636. auto se = detail::scope_exit([&] {
  15637. svr.stop();
  15638. t.join();
  15639. ASSERT_FALSE(svr.is_running());
  15640. });
  15641. svr.wait_until_ready();
  15642. Client cli(HOST, PORT);
  15643. // Non-stream path
  15644. auto r1 = cli.Get(path);
  15645. ASSERT_TRUE(r1);
  15646. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15647. // Stream path
  15648. auto h = cli.open_stream("GET", path);
  15649. ASSERT_TRUE(h.is_valid());
  15650. EXPECT_EQ(r1->body, read_all(h));
  15651. }
  15652. // Helper to compress data with provided compressor type T
  15653. template <typename Compressor>
  15654. static std::string compress_payload_for_parity(const std::string &in) {
  15655. std::string out;
  15656. Compressor compressor;
  15657. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15658. [&](const char *data, size_t n) {
  15659. out.append(data, n);
  15660. return true;
  15661. });
  15662. EXPECT_TRUE(ok);
  15663. return out;
  15664. }
  15665. // Helper function for compression parity tests
  15666. template <typename Compressor>
  15667. static void test_compression_parity(const std::string &original,
  15668. const std::string &path,
  15669. const std::string &encoding) {
  15670. const std::string compressed =
  15671. compress_payload_for_parity<Compressor>(original);
  15672. Server svr;
  15673. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15674. res.set_content(compressed, "application/octet-stream");
  15675. res.set_header("Content-Encoding", encoding);
  15676. });
  15677. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15678. auto se = detail::scope_exit([&] {
  15679. svr.stop();
  15680. t.join();
  15681. ASSERT_FALSE(svr.is_running());
  15682. });
  15683. svr.wait_until_ready();
  15684. Client cli(HOST, PORT);
  15685. // Non-streaming
  15686. {
  15687. auto res = cli.Get(path);
  15688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15689. EXPECT_EQ(StatusCode::OK_200, res->status);
  15690. EXPECT_EQ(original, res->body);
  15691. }
  15692. // Streaming
  15693. {
  15694. auto h = cli.open_stream("GET", path);
  15695. ASSERT_TRUE(h.is_valid());
  15696. EXPECT_EQ(original, read_all(h));
  15697. }
  15698. }
  15699. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15700. TEST(ParityTest, Gzip) {
  15701. test_compression_parity<detail::gzip_compressor>(
  15702. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15703. }
  15704. #endif
  15705. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15706. TEST(ParityTest, Brotli) {
  15707. test_compression_parity<detail::brotli_compressor>(
  15708. "Hello, brotli parity test payload", "/parity-br", "br");
  15709. }
  15710. #endif
  15711. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15712. TEST(ParityTest, Zstd) {
  15713. test_compression_parity<detail::zstd_compressor>(
  15714. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15715. }
  15716. #endif
  15717. //==============================================================================
  15718. // New Stream API Tests
  15719. //==============================================================================
  15720. inline std::string read_body(httplib::stream::Result &result) {
  15721. std::string body;
  15722. while (result.next()) {
  15723. body.append(result.data(), result.size());
  15724. }
  15725. return body;
  15726. }
  15727. TEST(ClientConnectionTest, Basic) {
  15728. httplib::ClientConnection conn;
  15729. EXPECT_FALSE(conn.is_open());
  15730. conn.sock = 1;
  15731. EXPECT_TRUE(conn.is_open());
  15732. httplib::ClientConnection conn2(std::move(conn));
  15733. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15734. conn2.sock = INVALID_SOCKET;
  15735. }
  15736. // Unified test server for all stream::* tests
  15737. class StreamApiTest : public ::testing::Test {
  15738. protected:
  15739. void SetUp() override {
  15740. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15741. res.set_content("Hello World!", "text/plain");
  15742. });
  15743. svr_.Get("/echo-params",
  15744. [](const httplib::Request &req, httplib::Response &res) {
  15745. std::string r;
  15746. for (const auto &p : req.params) {
  15747. if (!r.empty()) r += "&";
  15748. r += p.first + "=" + p.second;
  15749. }
  15750. res.set_content(r, "text/plain");
  15751. });
  15752. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15753. res.set_content(req.body, req.get_header_value("Content-Type"));
  15754. });
  15755. svr_.Post("/echo-headers",
  15756. [](const httplib::Request &req, httplib::Response &res) {
  15757. std::string r;
  15758. for (const auto &h : req.headers)
  15759. r += h.first + ": " + h.second + "\n";
  15760. res.set_content(r, "text/plain");
  15761. });
  15762. svr_.Post("/echo-params",
  15763. [](const httplib::Request &req, httplib::Response &res) {
  15764. std::string r = "params:";
  15765. for (const auto &p : req.params)
  15766. r += p.first + "=" + p.second + ";";
  15767. res.set_content(r + " body:" + req.body, "text/plain");
  15768. });
  15769. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15770. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15771. });
  15772. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15773. res.set_content("PUT:" + req.body, "text/plain");
  15774. });
  15775. svr_.Patch("/echo",
  15776. [](const httplib::Request &req, httplib::Response &res) {
  15777. res.set_content("PATCH:" + req.body, "text/plain");
  15778. });
  15779. svr_.Delete(
  15780. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15781. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15782. "text/plain");
  15783. });
  15784. svr_.Get("/head-test",
  15785. [](const httplib::Request &, httplib::Response &res) {
  15786. res.set_content("body for HEAD", "text/plain");
  15787. });
  15788. svr_.Options("/options",
  15789. [](const httplib::Request &, httplib::Response &res) {
  15790. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15791. });
  15792. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15793. svr_.wait_until_ready();
  15794. }
  15795. void TearDown() override {
  15796. svr_.stop();
  15797. if (thread_.joinable()) thread_.join();
  15798. }
  15799. httplib::Server svr_;
  15800. std::thread thread_;
  15801. };
  15802. // stream::Get tests
  15803. TEST_F(StreamApiTest, GetBasic) {
  15804. httplib::Client cli(HOST, PORT);
  15805. auto result = httplib::stream::Get(cli, "/hello");
  15806. ASSERT_TRUE(result.is_valid());
  15807. EXPECT_EQ(200, result.status());
  15808. EXPECT_EQ("Hello World!", read_body(result));
  15809. }
  15810. TEST_F(StreamApiTest, GetWithParams) {
  15811. httplib::Client cli(HOST, PORT);
  15812. httplib::Params params{{"foo", "bar"}};
  15813. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15814. ASSERT_TRUE(result.is_valid());
  15815. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15816. }
  15817. TEST_F(StreamApiTest, GetConnectionError) {
  15818. httplib::Client cli(HOST, 9999);
  15819. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15820. }
  15821. TEST_F(StreamApiTest, Get404) {
  15822. httplib::Client cli(HOST, PORT);
  15823. auto result = httplib::stream::Get(cli, "/nonexistent");
  15824. EXPECT_TRUE(result.is_valid());
  15825. EXPECT_EQ(404, result.status());
  15826. }
  15827. // stream::Post tests
  15828. TEST_F(StreamApiTest, PostBasic) {
  15829. httplib::Client cli(HOST, PORT);
  15830. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15831. "application/json");
  15832. ASSERT_TRUE(result.is_valid());
  15833. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15834. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15835. }
  15836. TEST_F(StreamApiTest, PostWithHeaders) {
  15837. httplib::Client cli(HOST, PORT);
  15838. httplib::Headers headers{{"X-Custom", "value"}};
  15839. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15840. "text/plain");
  15841. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15842. }
  15843. TEST_F(StreamApiTest, PostWithParams) {
  15844. httplib::Client cli(HOST, PORT);
  15845. httplib::Params params{{"k", "v"}};
  15846. auto result =
  15847. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15848. auto body = read_body(result);
  15849. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15850. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15851. }
  15852. TEST_F(StreamApiTest, PostLarge) {
  15853. httplib::Client cli(HOST, PORT);
  15854. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15855. size_t total = 0;
  15856. while (result.next()) {
  15857. total += result.size();
  15858. }
  15859. EXPECT_EQ(100u * 1024u, total);
  15860. }
  15861. // stream::Put/Patch tests
  15862. TEST_F(StreamApiTest, PutAndPatch) {
  15863. httplib::Client cli(HOST, PORT);
  15864. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15865. EXPECT_EQ("PUT:test", read_body(put));
  15866. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15867. EXPECT_EQ("PATCH:test", read_body(patch));
  15868. }
  15869. // stream::Delete tests
  15870. TEST_F(StreamApiTest, Delete) {
  15871. httplib::Client cli(HOST, PORT);
  15872. auto del1 = httplib::stream::Delete(cli, "/resource");
  15873. EXPECT_EQ("Deleted", read_body(del1));
  15874. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15875. EXPECT_EQ("Deleted:data", read_body(del2));
  15876. }
  15877. // stream::Head/Options tests
  15878. TEST_F(StreamApiTest, HeadAndOptions) {
  15879. httplib::Client cli(HOST, PORT);
  15880. auto head = httplib::stream::Head(cli, "/head-test");
  15881. EXPECT_TRUE(head.is_valid());
  15882. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15883. auto opts = httplib::stream::Options(cli, "/options");
  15884. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15885. }
  15886. // SSL stream::* tests
  15887. #ifdef CPPHTTPLIB_SSL_ENABLED
  15888. class SSLStreamApiTest : public ::testing::Test {
  15889. protected:
  15890. void SetUp() override {
  15891. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15892. res.set_content("Hello SSL!", "text/plain");
  15893. });
  15894. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15895. res.set_content(req.body, "text/plain");
  15896. });
  15897. port_ = svr_.bind_to_any_port("127.0.0.1");
  15898. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15899. svr_.wait_until_ready();
  15900. }
  15901. void TearDown() override {
  15902. svr_.stop();
  15903. if (thread_.joinable()) thread_.join();
  15904. }
  15905. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15906. std::thread thread_;
  15907. int port_ = 0;
  15908. };
  15909. TEST_F(SSLStreamApiTest, GetAndPost) {
  15910. httplib::SSLClient cli("127.0.0.1", port_);
  15911. cli.enable_server_certificate_verification(false);
  15912. auto get = httplib::stream::Get(cli, "/hello");
  15913. EXPECT_EQ("Hello SSL!", read_body(get));
  15914. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15915. EXPECT_EQ("test", read_body(post));
  15916. }
  15917. #endif
  15918. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15919. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15920. // BodyReader
  15921. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15922. // Test that read timeout during streaming is detected
  15923. // Use a large content-length response where server delays mid-stream
  15924. Server svr;
  15925. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15926. // Send a large response with delay in the middle
  15927. res.set_content_provider(
  15928. 1000, // content_length
  15929. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15930. if (offset < 100) {
  15931. // Send first 100 bytes immediately
  15932. std::string data(100, 'A');
  15933. sink.write(data.c_str(), data.size());
  15934. return true;
  15935. }
  15936. // Then delay longer than client timeout
  15937. std::this_thread::sleep_for(std::chrono::seconds(3));
  15938. std::string data(900, 'B');
  15939. sink.write(data.c_str(), data.size());
  15940. return true;
  15941. });
  15942. });
  15943. auto port = 8091;
  15944. std::thread t([&]() { svr.listen("localhost", port); });
  15945. svr.wait_until_ready();
  15946. Client cli("localhost", port);
  15947. cli.set_read_timeout(1, 0); // 1 second timeout
  15948. auto handle = cli.open_stream("GET", "/slow-stream");
  15949. ASSERT_TRUE(handle.is_valid());
  15950. char buf[256];
  15951. ssize_t total = 0;
  15952. ssize_t n;
  15953. bool got_error = false;
  15954. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15955. total += n;
  15956. }
  15957. if (n < 0) {
  15958. got_error = true;
  15959. // Should be timeout or read error
  15960. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15961. handle.get_read_error() == Error::Read)
  15962. << "Actual error: " << to_string(handle.get_read_error());
  15963. }
  15964. // Either we got an error, or we got less data than expected
  15965. EXPECT_TRUE(got_error || total < 1000)
  15966. << "Expected timeout but got all " << total << " bytes";
  15967. svr.stop();
  15968. t.join();
  15969. }
  15970. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15971. // Test connection closed detection via BodyReader
  15972. Server svr;
  15973. std::atomic<bool> close_now{false};
  15974. svr.Get("/will-close", [&](const Request &, Response &res) {
  15975. res.set_content_provider(
  15976. 10000, // Large content_length that we won't fully send
  15977. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15978. if (offset < 100) {
  15979. std::string data(100, 'X');
  15980. sink.write(data.c_str(), data.size());
  15981. return true;
  15982. }
  15983. // Wait for signal then abort
  15984. while (!close_now) {
  15985. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15986. }
  15987. return false; // Abort - server will close connection
  15988. });
  15989. });
  15990. auto port = 8092;
  15991. std::thread t([&]() { svr.listen("localhost", port); });
  15992. svr.wait_until_ready();
  15993. Client cli("localhost", port);
  15994. auto handle = cli.open_stream("GET", "/will-close");
  15995. ASSERT_TRUE(handle.is_valid());
  15996. char buf[256];
  15997. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15998. EXPECT_GT(n, 0) << "First read should succeed";
  15999. // Signal server to close
  16000. close_now = true;
  16001. // Keep reading until error or EOF
  16002. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16003. // Keep reading
  16004. }
  16005. // Should get an error since content_length wasn't satisfied
  16006. if (n < 0) {
  16007. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16008. handle.get_read_error() == Error::Read)
  16009. << "Actual error: " << to_string(handle.get_read_error());
  16010. }
  16011. svr.stop();
  16012. t.join();
  16013. }
  16014. #ifdef CPPHTTPLIB_SSL_ENABLED
  16015. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16016. // Test that read timeout during SSL streaming is detected
  16017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16018. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16019. res.set_content_provider(
  16020. 1000, "text/plain",
  16021. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16022. if (offset < 100) {
  16023. std::string data(100, 'A');
  16024. sink.write(data.c_str(), data.size());
  16025. return true;
  16026. }
  16027. std::this_thread::sleep_for(std::chrono::seconds(3));
  16028. std::string data(900, 'B');
  16029. sink.write(data.c_str(), data.size());
  16030. return true;
  16031. });
  16032. });
  16033. auto port = 8093;
  16034. std::thread t([&]() { svr.listen("localhost", port); });
  16035. svr.wait_until_ready();
  16036. SSLClient cli("localhost", port);
  16037. cli.enable_server_certificate_verification(false);
  16038. cli.set_read_timeout(1, 0); // 1 second timeout
  16039. auto handle = cli.open_stream("GET", "/slow-stream");
  16040. ASSERT_TRUE(handle.is_valid());
  16041. char buf[256];
  16042. ssize_t total = 0;
  16043. ssize_t n;
  16044. bool got_error = false;
  16045. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16046. total += n;
  16047. }
  16048. if (n < 0) {
  16049. got_error = true;
  16050. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16051. handle.get_read_error() == Error::Read)
  16052. << "Actual error: " << to_string(handle.get_read_error());
  16053. }
  16054. EXPECT_TRUE(got_error || total < 1000)
  16055. << "Expected timeout but got all " << total << " bytes";
  16056. svr.stop();
  16057. t.join();
  16058. }
  16059. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16060. // Test SSL connection closed detection
  16061. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16062. std::atomic<bool> close_now{false};
  16063. svr.Get("/will-close", [&](const Request &, Response &res) {
  16064. res.set_content_provider(
  16065. 10000, "text/plain",
  16066. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16067. if (offset < 100) {
  16068. std::string data(100, 'X');
  16069. sink.write(data.c_str(), data.size());
  16070. return true;
  16071. }
  16072. while (!close_now) {
  16073. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16074. }
  16075. return false;
  16076. });
  16077. });
  16078. auto port = 8094;
  16079. std::thread t([&]() { svr.listen("localhost", port); });
  16080. svr.wait_until_ready();
  16081. SSLClient cli("localhost", port);
  16082. cli.enable_server_certificate_verification(false);
  16083. auto handle = cli.open_stream("GET", "/will-close");
  16084. ASSERT_TRUE(handle.is_valid());
  16085. char buf[256];
  16086. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16087. EXPECT_GT(n, 0);
  16088. // Signal server to close
  16089. close_now = true;
  16090. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16091. // Keep reading
  16092. }
  16093. if (n < 0) {
  16094. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16095. handle.get_read_error() == Error::Read)
  16096. << "Actual error: " << to_string(handle.get_read_error());
  16097. }
  16098. svr.stop();
  16099. t.join();
  16100. }
  16101. #endif
  16102. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16103. using namespace httplib;
  16104. // Create a test file
  16105. const char *fname = "etag_testfile.txt";
  16106. const char *content = "etag-content";
  16107. {
  16108. std::ofstream ofs(fname);
  16109. ofs << content;
  16110. ASSERT_TRUE(ofs.good());
  16111. }
  16112. Server svr;
  16113. svr.set_mount_point("/static", ".");
  16114. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16115. svr.wait_until_ready();
  16116. Client cli(HOST, PORT);
  16117. // First request: should get 200 with ETag header
  16118. auto res1 = cli.Get("/static/etag_testfile.txt");
  16119. ASSERT_TRUE(res1);
  16120. ASSERT_EQ(200, res1->status);
  16121. ASSERT_TRUE(res1->has_header("ETag"));
  16122. std::string etag = res1->get_header_value("ETag");
  16123. EXPECT_FALSE(etag.empty());
  16124. // Verify ETag format: W/"hex-hex"
  16125. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16126. EXPECT_EQ('W', etag[0]);
  16127. EXPECT_EQ('/', etag[1]);
  16128. EXPECT_EQ('"', etag[2]);
  16129. EXPECT_EQ('"', etag.back());
  16130. // Exact match: expect 304 Not Modified
  16131. Headers h2 = {{"If-None-Match", etag}};
  16132. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16133. ASSERT_TRUE(res2);
  16134. EXPECT_EQ(304, res2->status);
  16135. // Wildcard match: expect 304 Not Modified
  16136. Headers h3 = {{"If-None-Match", "*"}};
  16137. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16138. ASSERT_TRUE(res3);
  16139. EXPECT_EQ(304, res3->status);
  16140. // Non-matching ETag: expect 200
  16141. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16142. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16143. ASSERT_TRUE(res4);
  16144. EXPECT_EQ(200, res4->status);
  16145. // Multiple ETags with one matching: expect 304
  16146. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16147. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16148. ASSERT_TRUE(res5);
  16149. EXPECT_EQ(304, res5->status);
  16150. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16151. // that equivalent to the single comma-separated list above, so the match on
  16152. // the second line must still be found.
  16153. Headers h6;
  16154. h6.emplace("If-None-Match", "W/\"other\"");
  16155. h6.emplace("If-None-Match", etag);
  16156. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16157. ASSERT_TRUE(res6);
  16158. EXPECT_EQ(304, res6->status);
  16159. svr.stop();
  16160. t.join();
  16161. std::remove(fname);
  16162. }
  16163. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16164. using namespace httplib;
  16165. Server svr;
  16166. svr.set_mount_point("/static", ".");
  16167. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16168. svr.wait_until_ready();
  16169. Client cli(HOST, PORT);
  16170. // Send If-None-Match: * to a non-existent file
  16171. Headers h = {{"If-None-Match", "*"}};
  16172. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16174. EXPECT_EQ(404, res->status);
  16175. svr.stop();
  16176. t.join();
  16177. }
  16178. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16179. using namespace httplib;
  16180. // Create a test file
  16181. const char *fname = "etag_boundary_testfile.txt";
  16182. const char *content = "boundary-test";
  16183. {
  16184. std::ofstream ofs(fname);
  16185. ofs << content;
  16186. ASSERT_TRUE(ofs.good());
  16187. }
  16188. Server svr;
  16189. svr.set_mount_point("/static", ".");
  16190. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16191. svr.wait_until_ready();
  16192. Client cli(HOST, PORT);
  16193. // Get the actual ETag
  16194. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16195. ASSERT_TRUE(res1);
  16196. ASSERT_EQ(200, res1->status);
  16197. ASSERT_TRUE(res1->has_header("ETag"));
  16198. std::string etag = res1->get_header_value("ETag");
  16199. // Test 1: Very long ETag value (longer than actual ETag)
  16200. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16201. Headers h1 = {{"If-None-Match", "W/"
  16202. "\"very-long-etag-value-that-is-much-longer-"
  16203. "than-the-actual-etag-value\""}};
  16204. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16205. ASSERT_TRUE(res2);
  16206. EXPECT_EQ(200, res2->status); // Should not match
  16207. // Test 2: Long string followed by wildcard
  16208. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16209. // string)
  16210. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16211. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16212. ASSERT_TRUE(res3);
  16213. EXPECT_EQ(304, res3->status); // Should match on "*"
  16214. // Test 3: Wildcard followed by long string
  16215. // Should match on "*" immediately and return 304
  16216. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16217. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16218. ASSERT_TRUE(res4);
  16219. EXPECT_EQ(304, res4->status); // Should match on "*"
  16220. // Test 4: Multiple long non-matching values
  16221. // Should NOT match and return 200 (test that all comparisons are safe)
  16222. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16223. "W/\"second-long-non-matching-value\", "
  16224. "W/\"third-long-non-matching-value\""}};
  16225. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16226. ASSERT_TRUE(res5);
  16227. EXPECT_EQ(200, res5->status); // Should not match
  16228. // Test 5: Single character that is not "*" (edge case)
  16229. Headers h5 = {{"If-None-Match", "X"}};
  16230. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16231. ASSERT_TRUE(res6);
  16232. EXPECT_EQ(200, res6->status); // Should not match
  16233. svr.stop();
  16234. t.join();
  16235. std::remove(fname);
  16236. }
  16237. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16238. using namespace httplib;
  16239. // Create a test file
  16240. const char *fname = "ims_testfile.txt";
  16241. const char *content = "if-modified-since-test";
  16242. {
  16243. std::ofstream ofs(fname);
  16244. ofs << content;
  16245. ASSERT_TRUE(ofs.good());
  16246. }
  16247. Server svr;
  16248. svr.set_mount_point("/static", ".");
  16249. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16250. svr.wait_until_ready();
  16251. Client cli(HOST, PORT);
  16252. // First request: should get 200 with Last-Modified header
  16253. auto res1 = cli.Get("/static/ims_testfile.txt");
  16254. ASSERT_TRUE(res1);
  16255. ASSERT_EQ(200, res1->status);
  16256. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16257. std::string last_modified = res1->get_header_value("Last-Modified");
  16258. EXPECT_FALSE(last_modified.empty());
  16259. // If-Modified-Since with same time: expect 304
  16260. Headers h2 = {{"If-Modified-Since", last_modified}};
  16261. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16262. ASSERT_TRUE(res2);
  16263. EXPECT_EQ(304, res2->status);
  16264. // If-Modified-Since with future time: expect 304
  16265. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16266. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16267. ASSERT_TRUE(res3);
  16268. EXPECT_EQ(304, res3->status);
  16269. // If-Modified-Since with past time: expect 200
  16270. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16271. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16272. ASSERT_TRUE(res4);
  16273. EXPECT_EQ(200, res4->status);
  16274. // If-None-Match takes precedence over If-Modified-Since
  16275. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16276. ASSERT_TRUE(res1->has_header("ETag"));
  16277. std::string etag = res1->get_header_value("ETag");
  16278. Headers h5 = {{"If-None-Match", etag},
  16279. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16280. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16281. ASSERT_TRUE(res5);
  16282. EXPECT_EQ(304, res5->status);
  16283. svr.stop();
  16284. t.join();
  16285. std::remove(fname);
  16286. }
  16287. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16288. using namespace httplib;
  16289. Server svr;
  16290. // Endpoint that returns compressible content
  16291. svr.Get("/compressible", [](const Request &, Response &res) {
  16292. // Return a large enough body to trigger compression
  16293. std::string body(1000, 'a');
  16294. res.set_content(body, "text/plain");
  16295. });
  16296. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16297. svr.wait_until_ready();
  16298. Client cli(HOST, PORT);
  16299. // Request with gzip support: should get Vary header when compressed
  16300. cli.set_compress(true);
  16301. auto res1 = cli.Get("/compressible");
  16302. ASSERT_TRUE(res1);
  16303. EXPECT_EQ(200, res1->status);
  16304. // If Content-Encoding is set, Vary should also be set
  16305. if (res1->has_header("Content-Encoding")) {
  16306. EXPECT_TRUE(res1->has_header("Vary"));
  16307. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16308. }
  16309. // Request without Accept-Encoding header: should not have compression
  16310. Headers h_no_compress;
  16311. auto res2 = cli.Get("/compressible", h_no_compress);
  16312. ASSERT_TRUE(res2);
  16313. EXPECT_EQ(200, res2->status);
  16314. // Verify Vary header is present when compression is applied
  16315. // (the exact behavior depends on server configuration)
  16316. svr.stop();
  16317. t.join();
  16318. }
  16319. TEST(ETagTest, IfRangeWithETag) {
  16320. using namespace httplib;
  16321. // Create a test file with known content
  16322. const char *fname = "if_range_testfile.txt";
  16323. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16324. {
  16325. std::ofstream ofs(fname);
  16326. ofs << content;
  16327. ASSERT_TRUE(ofs.good());
  16328. }
  16329. Server svr;
  16330. svr.set_mount_point("/static", ".");
  16331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16332. svr.wait_until_ready();
  16333. Client cli(HOST, PORT);
  16334. // First request: get ETag
  16335. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16336. ASSERT_TRUE(res1);
  16337. ASSERT_EQ(200, res1->status);
  16338. ASSERT_TRUE(res1->has_header("ETag"));
  16339. std::string etag = res1->get_header_value("ETag");
  16340. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16341. // Since our server generates weak ETags (W/"..."), If-Range with our
  16342. // ETag should NOT result in partial content - it should return full content.
  16343. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16344. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16345. ASSERT_TRUE(res2);
  16346. // Weak ETag in If-Range -> full content (200), not partial (206)
  16347. EXPECT_EQ(200, res2->status);
  16348. EXPECT_EQ(content, res2->body);
  16349. EXPECT_FALSE(res2->has_header("Content-Range"));
  16350. // Range request with non-matching If-Range (ETag): should get 200 (full
  16351. // content)
  16352. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16353. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16354. ASSERT_TRUE(res3);
  16355. EXPECT_EQ(200, res3->status);
  16356. EXPECT_EQ(content, res3->body);
  16357. EXPECT_FALSE(res3->has_header("Content-Range"));
  16358. // Range request with strong ETag (hypothetical - our server doesn't generate
  16359. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16360. // should return full content)
  16361. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16362. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16363. ASSERT_TRUE(res4);
  16364. EXPECT_EQ(200, res4->status);
  16365. EXPECT_EQ(content, res4->body);
  16366. EXPECT_FALSE(res4->has_header("Content-Range"));
  16367. svr.stop();
  16368. t.join();
  16369. std::remove(fname);
  16370. }
  16371. TEST(ETagTest, IfRangeWithDate) {
  16372. using namespace httplib;
  16373. // Create a test file
  16374. const char *fname = "if_range_date_testfile.txt";
  16375. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16376. {
  16377. std::ofstream ofs(fname);
  16378. ofs << content;
  16379. ASSERT_TRUE(ofs.good());
  16380. }
  16381. Server svr;
  16382. svr.set_mount_point("/static", ".");
  16383. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16384. svr.wait_until_ready();
  16385. Client cli(HOST, PORT);
  16386. // First request: get Last-Modified
  16387. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16388. ASSERT_TRUE(res1);
  16389. ASSERT_EQ(200, res1->status);
  16390. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16391. std::string last_modified = res1->get_header_value("Last-Modified");
  16392. // Range request with matching If-Range (date): should get 206
  16393. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16394. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16395. ASSERT_TRUE(res2);
  16396. EXPECT_EQ(206, res2->status);
  16397. EXPECT_EQ("FGHIJ", res2->body);
  16398. // Range request with old If-Range date: should get 200 (full content)
  16399. Headers h3 = {{"Range", "bytes=5-9"},
  16400. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16401. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16402. ASSERT_TRUE(res3);
  16403. EXPECT_EQ(200, res3->status);
  16404. EXPECT_EQ(content, res3->body);
  16405. // Range request with future If-Range date: should get 206
  16406. Headers h4 = {{"Range", "bytes=0-4"},
  16407. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16408. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16409. ASSERT_TRUE(res4);
  16410. EXPECT_EQ(206, res4->status);
  16411. EXPECT_EQ("ABCDE", res4->body);
  16412. svr.stop();
  16413. t.join();
  16414. std::remove(fname);
  16415. }
  16416. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16417. using namespace httplib;
  16418. const char *fname = "etag_malformed.txt";
  16419. const char *content = "malformed-etag";
  16420. {
  16421. std::ofstream ofs(fname);
  16422. ofs << content;
  16423. ASSERT_TRUE(ofs.good());
  16424. }
  16425. Server svr;
  16426. svr.set_mount_point("/static", ".");
  16427. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16428. svr.wait_until_ready();
  16429. Client cli(HOST, PORT);
  16430. // baseline: should get 200 and an ETag
  16431. auto res1 = cli.Get("/static/etag_malformed.txt");
  16432. ASSERT_TRUE(res1);
  16433. ASSERT_EQ(200, res1->status);
  16434. ASSERT_TRUE(res1->has_header("ETag"));
  16435. // Malformed ETag value (missing quotes) should be treated as non-matching
  16436. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16437. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16438. ASSERT_TRUE(res_bad);
  16439. EXPECT_EQ(200, res_bad->status);
  16440. // Whitespace-only header value should be considered invalid / non-matching
  16441. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16442. "Host: localhost\r\n"
  16443. "If-None-Match: \r\n"
  16444. "Connection: close\r\n"
  16445. "\r\n";
  16446. std::string out;
  16447. ASSERT_TRUE(send_request(5, raw_req, &out));
  16448. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16449. svr.stop();
  16450. t.join();
  16451. std::remove(fname);
  16452. }
  16453. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16454. using namespace httplib;
  16455. const char *fname = "ims_invalid_format.txt";
  16456. const char *content = "ims-bad-format";
  16457. {
  16458. std::ofstream ofs(fname);
  16459. ofs << content;
  16460. ASSERT_TRUE(ofs.good());
  16461. }
  16462. Server svr;
  16463. svr.set_mount_point("/static", ".");
  16464. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16465. svr.wait_until_ready();
  16466. Client cli(HOST, PORT);
  16467. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16468. ASSERT_TRUE(res1);
  16469. ASSERT_EQ(200, res1->status);
  16470. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16471. // If-Modified-Since with invalid format should not result in 304
  16472. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16473. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16474. ASSERT_TRUE(res_bad);
  16475. EXPECT_EQ(200, res_bad->status);
  16476. // If-Range with invalid date format should be treated as mismatch -> full
  16477. // content (200)
  16478. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16479. {"If-Range", "invalid-date"}};
  16480. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16481. ASSERT_TRUE(res_ifrange);
  16482. EXPECT_EQ(200, res_ifrange->status);
  16483. svr.stop();
  16484. t.join();
  16485. std::remove(fname);
  16486. }
  16487. TEST(ETagTest, IfRangeWithMalformedETag) {
  16488. using namespace httplib;
  16489. const char *fname = "ifrange_malformed.txt";
  16490. const std::string content = "0123456789";
  16491. {
  16492. std::ofstream ofs(fname);
  16493. ofs << content;
  16494. ASSERT_TRUE(ofs.good());
  16495. }
  16496. Server svr;
  16497. svr.set_mount_point("/static", ".");
  16498. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16499. svr.wait_until_ready();
  16500. Client cli(HOST, PORT);
  16501. // First request: get ETag
  16502. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16503. ASSERT_TRUE(res1);
  16504. ASSERT_EQ(200, res1->status);
  16505. ASSERT_TRUE(res1->has_header("ETag"));
  16506. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16507. // full content (200)
  16508. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16509. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16510. ASSERT_TRUE(res2);
  16511. EXPECT_EQ(200, res2->status);
  16512. EXPECT_EQ(content, res2->body);
  16513. svr.stop();
  16514. t.join();
  16515. std::remove(fname);
  16516. }
  16517. TEST(ETagTest, ExtremeLargeDateValues) {
  16518. using namespace httplib;
  16519. const char *fname = "ims_extreme_date.txt";
  16520. const char *content = "ims-extreme-date";
  16521. {
  16522. std::ofstream ofs(fname);
  16523. ofs << content;
  16524. ASSERT_TRUE(ofs.good());
  16525. }
  16526. Server svr;
  16527. svr.set_mount_point("/static", ".");
  16528. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16529. svr.wait_until_ready();
  16530. Client cli(HOST, PORT);
  16531. auto res1 = cli.Get(std::string("/static/") + fname);
  16532. ASSERT_TRUE(res1);
  16533. ASSERT_EQ(200, res1->status);
  16534. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16535. // Extremely large year that may overflow date parsing routines.
  16536. Headers h_large_date = {
  16537. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16538. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16539. ASSERT_TRUE(res_bad);
  16540. // Expect server to treat this as invalid/mismatch and return full content
  16541. EXPECT_EQ(200, res_bad->status);
  16542. // If-Range with extremely large date should be treated as mismatch -> full
  16543. // content (200)
  16544. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16545. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16546. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16547. ASSERT_TRUE(res_ifrange);
  16548. EXPECT_EQ(200, res_ifrange->status);
  16549. svr.stop();
  16550. t.join();
  16551. std::remove(fname);
  16552. }
  16553. TEST(ETagTest, NegativeFileModificationTime) {
  16554. using namespace httplib;
  16555. const char *fname = "ims_negative_mtime.txt";
  16556. const std::string content = "negative-mtime";
  16557. {
  16558. std::ofstream ofs(fname);
  16559. ofs << content;
  16560. ASSERT_TRUE(ofs.good());
  16561. }
  16562. // Try to set file mtime to a negative value. This may fail on some
  16563. // platforms/filesystems; if it fails, the test will still verify server
  16564. // behaves safely by performing a regular conditional request.
  16565. #if defined(__APPLE__) || defined(__linux__)
  16566. bool set_negative = false;
  16567. do {
  16568. struct timeval times[2];
  16569. // access time: now
  16570. times[0].tv_sec = time(nullptr);
  16571. times[0].tv_usec = 0;
  16572. // modification time: negative (e.g., -1)
  16573. times[1].tv_sec = -1;
  16574. times[1].tv_usec = 0;
  16575. if (utimes(fname, times) == 0) { set_negative = true; }
  16576. } while (0);
  16577. #else
  16578. bool set_negative = false;
  16579. #endif
  16580. Server svr;
  16581. svr.set_mount_point("/static", ".");
  16582. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16583. svr.wait_until_ready();
  16584. Client cli(HOST, PORT);
  16585. auto res1 = cli.Get(std::string("/static/") + fname);
  16586. ASSERT_TRUE(res1);
  16587. ASSERT_EQ(200, res1->status);
  16588. bool has_last_modified = res1->has_header("Last-Modified");
  16589. std::string last_modified;
  16590. if (has_last_modified) {
  16591. last_modified = res1->get_header_value("Last-Modified");
  16592. }
  16593. if (set_negative) {
  16594. // If we successfully set a negative mtime, ensure server returns a
  16595. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16596. // with an old date and ensure server handles it without crash.
  16597. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16598. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16599. ASSERT_TRUE(res2);
  16600. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16601. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16602. } else {
  16603. // Could not set negative mtime on this platform; fall back to verifying
  16604. // that normal invalid/malformed dates are treated safely (non-304).
  16605. Headers h_bad_date = {
  16606. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16607. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16608. ASSERT_TRUE(res_bad);
  16609. EXPECT_EQ(200, res_bad->status);
  16610. }
  16611. svr.stop();
  16612. t.join();
  16613. std::remove(fname);
  16614. }
  16615. //==============================================================================
  16616. // SSE Parsing Tests
  16617. //==============================================================================
  16618. class SSEParsingTest : public ::testing::Test {
  16619. protected:
  16620. // Test helper that mimics SSE parsing behavior
  16621. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16622. int &retry_ms) {
  16623. // Blank line signals end of event
  16624. if (line.empty() || line == "\r") { return true; }
  16625. // Lines starting with ':' are comments (ignored)
  16626. if (!line.empty() && line[0] == ':') { return false; }
  16627. // Find the colon separator
  16628. auto colon_pos = line.find(':');
  16629. if (colon_pos == std::string::npos) {
  16630. // Line with no colon is treated as field name with empty value
  16631. return false;
  16632. }
  16633. std::string field = line.substr(0, colon_pos);
  16634. std::string value;
  16635. // Value starts after colon, skip optional single space
  16636. if (colon_pos + 1 < line.size()) {
  16637. size_t value_start = colon_pos + 1;
  16638. if (line[value_start] == ' ') { value_start++; }
  16639. value = line.substr(value_start);
  16640. // Remove trailing \r if present
  16641. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16642. }
  16643. // Handle known fields
  16644. if (field == "event") {
  16645. msg.event = value;
  16646. } else if (field == "data") {
  16647. // Multiple data lines are concatenated with newlines
  16648. if (!msg.data.empty()) { msg.data += "\n"; }
  16649. msg.data += value;
  16650. } else if (field == "id") {
  16651. // Empty id is valid (clears the last event ID)
  16652. msg.id = value;
  16653. } else if (field == "retry") {
  16654. // Parse retry interval in milliseconds
  16655. {
  16656. int v = 0;
  16657. auto res =
  16658. detail::from_chars(value.data(), value.data() + value.size(), v);
  16659. if (res.ec == std::errc{}) { retry_ms = v; }
  16660. }
  16661. }
  16662. // Unknown fields are ignored per SSE spec
  16663. return false;
  16664. }
  16665. };
  16666. // Test: Single-line data
  16667. TEST_F(SSEParsingTest, SingleLineData) {
  16668. sse::SSEMessage msg;
  16669. int retry_ms = 3000;
  16670. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16671. EXPECT_EQ(msg.data, "hello");
  16672. EXPECT_EQ(msg.event, "message");
  16673. // Blank line ends event
  16674. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16675. }
  16676. // Test: Multi-line data
  16677. TEST_F(SSEParsingTest, MultiLineData) {
  16678. sse::SSEMessage msg;
  16679. int retry_ms = 3000;
  16680. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16681. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16682. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16683. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16684. }
  16685. // Test: Custom event types
  16686. TEST_F(SSEParsingTest, CustomEventType) {
  16687. sse::SSEMessage msg;
  16688. int retry_ms = 3000;
  16689. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16690. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16691. EXPECT_EQ(msg.event, "update");
  16692. EXPECT_EQ(msg.data, "payload");
  16693. }
  16694. // Test: Event ID handling
  16695. TEST_F(SSEParsingTest, EventIdHandling) {
  16696. sse::SSEMessage msg;
  16697. int retry_ms = 3000;
  16698. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16699. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16700. EXPECT_EQ(msg.id, "12345");
  16701. }
  16702. // Test: Empty event ID (clears last event ID)
  16703. TEST_F(SSEParsingTest, EmptyEventId) {
  16704. sse::SSEMessage msg;
  16705. msg.id = "previous";
  16706. int retry_ms = 3000;
  16707. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16708. EXPECT_EQ(msg.id, "");
  16709. }
  16710. // Test: Retry field parsing
  16711. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16712. sse::SSEMessage msg;
  16713. int retry_ms = 3000;
  16714. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16715. EXPECT_EQ(retry_ms, 5000);
  16716. }
  16717. // Test: Invalid retry value
  16718. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16719. sse::SSEMessage msg;
  16720. int retry_ms = 3000;
  16721. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16722. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16723. }
  16724. // Test: Comments (lines starting with :)
  16725. TEST_F(SSEParsingTest, CommentsIgnored) {
  16726. sse::SSEMessage msg;
  16727. int retry_ms = 3000;
  16728. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16729. EXPECT_EQ(msg.data, "");
  16730. EXPECT_EQ(msg.event, "message");
  16731. }
  16732. // Test: Colon in value
  16733. TEST_F(SSEParsingTest, ColonInValue) {
  16734. sse::SSEMessage msg;
  16735. int retry_ms = 3000;
  16736. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16737. EXPECT_EQ(msg.data, "hello:world:test");
  16738. }
  16739. // Test: Line with no colon (field name only)
  16740. TEST_F(SSEParsingTest, FieldNameOnly) {
  16741. sse::SSEMessage msg;
  16742. int retry_ms = 3000;
  16743. // According to SSE spec, this is treated as field name with empty value
  16744. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16745. // Since we don't recognize "data" without colon, data should be empty
  16746. EXPECT_EQ(msg.data, "");
  16747. }
  16748. // Test: Trailing \r handling
  16749. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16750. sse::SSEMessage msg;
  16751. int retry_ms = 3000;
  16752. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16753. EXPECT_EQ(msg.data, "hello");
  16754. }
  16755. // Test: Unknown fields ignored
  16756. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16757. sse::SSEMessage msg;
  16758. int retry_ms = 3000;
  16759. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16760. EXPECT_EQ(msg.data, "");
  16761. EXPECT_EQ(msg.event, "message");
  16762. }
  16763. // Test: Space after colon is optional
  16764. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16765. sse::SSEMessage msg1, msg2;
  16766. int retry_ms = 3000;
  16767. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16768. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16769. EXPECT_EQ(msg1.data, "hello");
  16770. EXPECT_EQ(msg2.data, "hello");
  16771. }
  16772. // Test: SSEMessage clear
  16773. TEST_F(SSEParsingTest, MessageClear) {
  16774. sse::SSEMessage msg;
  16775. msg.event = "custom";
  16776. msg.data = "some data";
  16777. msg.id = "123";
  16778. msg.clear();
  16779. EXPECT_EQ(msg.event, "message");
  16780. EXPECT_EQ(msg.data, "");
  16781. EXPECT_EQ(msg.id, "");
  16782. }
  16783. // Test: Complete event parsing
  16784. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16785. sse::SSEMessage msg;
  16786. int retry_ms = 3000;
  16787. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16788. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16789. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16790. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16791. // Blank line ends event
  16792. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16793. EXPECT_EQ(msg.event, "notification");
  16794. EXPECT_EQ(msg.id, "evt-42");
  16795. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16796. EXPECT_EQ(retry_ms, 1000);
  16797. }
  16798. //==============================================================================
  16799. // Integration Tests with Server
  16800. //==============================================================================
  16801. class SSEIntegrationTest : public ::testing::Test {
  16802. protected:
  16803. void SetUp() override {
  16804. stop_server_.store(false);
  16805. events_.clear();
  16806. server_ = httplib::detail::make_unique<Server>();
  16807. setup_server();
  16808. start_server();
  16809. }
  16810. void TearDown() override {
  16811. stop_server_.store(true);
  16812. event_cv_.notify_all();
  16813. server_->stop();
  16814. if (server_thread_.joinable()) { server_thread_.join(); }
  16815. }
  16816. void setup_server() {
  16817. // Simple SSE endpoint
  16818. server_->Get("/events", [this](const Request &req, Response &res) {
  16819. auto last_id = req.get_header_value("Last-Event-ID");
  16820. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16821. res.set_chunked_content_provider(
  16822. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16823. std::unique_lock<std::mutex> lock(event_mutex_);
  16824. if (event_cv_.wait_for(
  16825. lock, std::chrono::milliseconds(200), [this] {
  16826. return !events_.empty() || stop_server_.load();
  16827. })) {
  16828. if (stop_server_.load()) { return false; }
  16829. if (!events_.empty()) {
  16830. std::string event = events_.front();
  16831. events_.erase(events_.begin());
  16832. sink.write(event.data(), event.size());
  16833. return true;
  16834. }
  16835. }
  16836. return !stop_server_.load();
  16837. });
  16838. });
  16839. // Endpoint that returns error
  16840. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16841. res.status = 500;
  16842. res.set_content("Internal Server Error", "text/plain");
  16843. });
  16844. // Endpoint for custom event types
  16845. server_->Get("/custom-events", [](const Request &, Response &res) {
  16846. res.set_chunked_content_provider(
  16847. "text/event-stream", [](size_t offset, DataSink &sink) {
  16848. if (offset == 0) {
  16849. std::string event = "event: update\ndata: updated\n\n"
  16850. "event: delete\ndata: deleted\n\n";
  16851. sink.write(event.data(), event.size());
  16852. }
  16853. return false; // End stream after sending
  16854. });
  16855. });
  16856. }
  16857. void start_server() {
  16858. port_ = server_->bind_to_any_port(HOST);
  16859. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16860. // Wait for server to start
  16861. while (!server_->is_running()) {
  16862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16863. }
  16864. }
  16865. int get_port() const { return port_; }
  16866. void send_event(const std::string &event) {
  16867. std::lock_guard<std::mutex> lock(event_mutex_);
  16868. events_.push_back(event);
  16869. event_cv_.notify_all();
  16870. }
  16871. std::unique_ptr<Server> server_;
  16872. std::thread server_thread_;
  16873. std::mutex event_mutex_;
  16874. std::condition_variable event_cv_;
  16875. std::vector<std::string> events_;
  16876. std::atomic<bool> stop_server_{false};
  16877. std::string last_received_event_id_;
  16878. int port_ = 0;
  16879. };
  16880. // Test: Successful connection and on_open callback
  16881. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16882. // Add a simple endpoint that sends one event and closes
  16883. server_->Get("/simple-event", [](const Request &, Response &res) {
  16884. res.set_chunked_content_provider(
  16885. "text/event-stream", [](size_t offset, DataSink &sink) {
  16886. if (offset == 0) {
  16887. std::string event = "data: hello\n\n";
  16888. sink.write(event.data(), event.size());
  16889. }
  16890. return false; // Close stream after sending
  16891. });
  16892. });
  16893. Client client("localhost", get_port());
  16894. sse::SSEClient sse(client, "/simple-event");
  16895. std::atomic<bool> open_called{false};
  16896. std::atomic<bool> message_received{false};
  16897. sse.on_open([&open_called]() { open_called.store(true); });
  16898. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16899. if (msg.data == "hello") { message_received.store(true); }
  16900. });
  16901. sse.set_reconnect_interval(100);
  16902. sse.set_max_reconnect_attempts(1);
  16903. // Start async
  16904. sse.start_async();
  16905. // Wait for message to be processed
  16906. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16907. sse.stop();
  16908. EXPECT_TRUE(open_called.load());
  16909. EXPECT_TRUE(message_received.load());
  16910. }
  16911. // Test: on_message callback
  16912. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16913. // Endpoint that sends multiple events then closes
  16914. server_->Get("/multi-event", [](const Request &, Response &res) {
  16915. res.set_chunked_content_provider(
  16916. "text/event-stream", [](size_t offset, DataSink &sink) {
  16917. if (offset == 0) {
  16918. std::string events = "data: message1\n\ndata: message2\n\n";
  16919. sink.write(events.data(), events.size());
  16920. }
  16921. return false;
  16922. });
  16923. });
  16924. Client client("localhost", get_port());
  16925. sse::SSEClient sse(client, "/multi-event");
  16926. std::vector<std::string> received_messages;
  16927. std::mutex messages_mutex;
  16928. sse.on_message([&](const sse::SSEMessage &msg) {
  16929. std::lock_guard<std::mutex> lock(messages_mutex);
  16930. received_messages.push_back(msg.data);
  16931. });
  16932. sse.set_reconnect_interval(100);
  16933. sse.set_max_reconnect_attempts(1);
  16934. sse.start_async();
  16935. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16936. sse.stop();
  16937. std::lock_guard<std::mutex> lock(messages_mutex);
  16938. EXPECT_GE(received_messages.size(), 2u);
  16939. if (received_messages.size() >= 2) {
  16940. EXPECT_EQ(received_messages[0], "message1");
  16941. EXPECT_EQ(received_messages[1], "message2");
  16942. }
  16943. }
  16944. // Test: on_event for specific types
  16945. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16946. Client client("localhost", get_port());
  16947. sse::SSEClient sse(client, "/custom-events");
  16948. std::atomic<bool> update_received{false};
  16949. std::atomic<bool> delete_received{false};
  16950. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16951. if (msg.data == "updated") { update_received.store(true); }
  16952. });
  16953. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16954. if (msg.data == "deleted") { delete_received.store(true); }
  16955. });
  16956. sse.set_max_reconnect_attempts(1);
  16957. sse.start_async();
  16958. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16959. sse.stop();
  16960. EXPECT_TRUE(update_received.load());
  16961. EXPECT_TRUE(delete_received.load());
  16962. }
  16963. // Test: on_error callback on connection failure
  16964. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16965. // Connect to a non-existent port
  16966. Client client("localhost", 59999);
  16967. sse::SSEClient sse(client, "/events");
  16968. std::atomic<bool> error_called{false};
  16969. Error received_error = Error::Success;
  16970. sse.on_error([&](Error err) {
  16971. error_called.store(true);
  16972. received_error = err;
  16973. });
  16974. sse.set_reconnect_interval(50);
  16975. sse.set_max_reconnect_attempts(1);
  16976. sse.start_async();
  16977. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16978. sse.stop();
  16979. EXPECT_TRUE(error_called.load());
  16980. EXPECT_NE(received_error, Error::Success);
  16981. }
  16982. // Test: Last-Event-ID header sent on reconnect
  16983. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16984. // Endpoint that sends event with ID
  16985. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16986. res.set_chunked_content_provider(
  16987. "text/event-stream", [](size_t offset, DataSink &sink) {
  16988. if (offset == 0) {
  16989. std::string event = "id: evt-123\ndata: test\n\n";
  16990. sink.write(event.data(), event.size());
  16991. }
  16992. return false;
  16993. });
  16994. });
  16995. Client client("localhost", get_port());
  16996. sse::SSEClient sse(client, "/event-with-id");
  16997. std::atomic<bool> id_received{false};
  16998. sse.on_message([&](const sse::SSEMessage &msg) {
  16999. if (!msg.id.empty()) { id_received.store(true); }
  17000. });
  17001. sse.set_reconnect_interval(100);
  17002. sse.set_max_reconnect_attempts(1);
  17003. sse.start_async();
  17004. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17005. sse.stop();
  17006. EXPECT_TRUE(id_received.load());
  17007. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17008. }
  17009. // Test: Manual stop
  17010. TEST_F(SSEIntegrationTest, ManualStop) {
  17011. // Endpoint that sends one event and stays open briefly
  17012. std::atomic<bool> handler_running{true};
  17013. server_->Get("/stay-open", [&handler_running](const Request &,
  17014. Response &res) {
  17015. res.set_chunked_content_provider(
  17016. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17017. if (offset == 0) {
  17018. std::string event = "data: connected\n\n";
  17019. sink.write(event.data(), event.size());
  17020. }
  17021. // Keep connection open while handler_running is true
  17022. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17023. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17024. }
  17025. return false;
  17026. });
  17027. });
  17028. Client client("localhost", get_port());
  17029. sse::SSEClient sse(client, "/stay-open");
  17030. std::atomic<bool> connected{false};
  17031. sse.on_open([&connected]() { connected.store(true); });
  17032. sse.set_reconnect_interval(100);
  17033. sse.set_max_reconnect_attempts(1);
  17034. sse.start_async();
  17035. // Wait for connection to establish
  17036. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17037. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17038. }
  17039. EXPECT_TRUE(connected.load());
  17040. EXPECT_TRUE(sse.is_connected());
  17041. // Signal handler to stop
  17042. handler_running.store(false);
  17043. // Stop SSE client
  17044. sse.stop();
  17045. EXPECT_FALSE(sse.is_connected());
  17046. }
  17047. // Test: SSEClient with custom headers
  17048. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17049. // Setup a server endpoint that checks for custom header
  17050. std::atomic<bool> header_received{false};
  17051. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17052. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17053. header_received.store(true);
  17054. }
  17055. res.set_chunked_content_provider("text/event-stream",
  17056. [](size_t, DataSink &) { return false; });
  17057. });
  17058. Client client("localhost", get_port());
  17059. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17060. sse::SSEClient sse(client, "/header-check", headers);
  17061. sse.set_max_reconnect_attempts(1);
  17062. sse.start_async();
  17063. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17064. sse.stop();
  17065. EXPECT_TRUE(header_received.load());
  17066. }
  17067. // Test: Reconnect interval configuration
  17068. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17069. Client client("localhost", get_port());
  17070. sse::SSEClient sse(client, "/events");
  17071. auto &result = sse.set_reconnect_interval(500);
  17072. // Builder pattern should return reference to self
  17073. EXPECT_EQ(&result, &sse);
  17074. }
  17075. // Test: Max reconnect attempts
  17076. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17077. // Connect to non-existent port to force reconnects
  17078. Client client("localhost", 59998);
  17079. sse::SSEClient sse(client, "/events");
  17080. std::atomic<int> error_count{0};
  17081. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17082. sse.set_reconnect_interval(50);
  17083. sse.set_max_reconnect_attempts(2);
  17084. auto start = std::chrono::steady_clock::now();
  17085. sse.start(); // Blocking call
  17086. auto end = std::chrono::steady_clock::now();
  17087. // Should have stopped after 2 failed attempts
  17088. EXPECT_GE(error_count.load(), 2);
  17089. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17090. auto duration =
  17091. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17092. #ifdef _WIN32
  17093. // Windows is much slower for socket connection failures
  17094. EXPECT_LT(duration.count(), 7000);
  17095. #else
  17096. EXPECT_LT(duration.count(), 1000);
  17097. #endif
  17098. }
  17099. // Test: Multi-line data in integration
  17100. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17101. // Endpoint with multi-line data
  17102. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17103. res.set_chunked_content_provider(
  17104. "text/event-stream", [](size_t offset, DataSink &sink) {
  17105. if (offset == 0) {
  17106. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17107. sink.write(event.data(), event.size());
  17108. }
  17109. return false;
  17110. });
  17111. });
  17112. Client client("localhost", get_port());
  17113. sse::SSEClient sse(client, "/multiline-data");
  17114. std::string received_data;
  17115. std::mutex data_mutex;
  17116. sse.on_message([&](const sse::SSEMessage &msg) {
  17117. std::lock_guard<std::mutex> lock(data_mutex);
  17118. received_data = msg.data;
  17119. });
  17120. sse.set_reconnect_interval(100);
  17121. sse.set_max_reconnect_attempts(1);
  17122. sse.start_async();
  17123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17124. sse.stop();
  17125. std::lock_guard<std::mutex> lock(data_mutex);
  17126. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17127. }
  17128. // Test: Auto-reconnect after server disconnection
  17129. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17130. std::atomic<int> connection_count{0};
  17131. std::atomic<int> message_count{0};
  17132. // Endpoint that sends one event and closes, forcing reconnect
  17133. server_->Get("/reconnect-test",
  17134. [&connection_count](const Request &, Response &res) {
  17135. connection_count.fetch_add(1);
  17136. res.set_chunked_content_provider(
  17137. "text/event-stream", [](size_t offset, DataSink &sink) {
  17138. if (offset == 0) {
  17139. std::string event = "data: hello\n\n";
  17140. sink.write(event.data(), event.size());
  17141. }
  17142. return false; // Close connection after sending
  17143. });
  17144. });
  17145. Client client("localhost", get_port());
  17146. sse::SSEClient sse(client, "/reconnect-test");
  17147. sse.on_message([&message_count](const sse::SSEMessage &) {
  17148. message_count.fetch_add(1);
  17149. });
  17150. sse.set_reconnect_interval(100);
  17151. sse.set_max_reconnect_attempts(3);
  17152. sse.start_async();
  17153. // Wait long enough for multiple reconnects
  17154. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17155. sse.stop();
  17156. // Should have connected multiple times (initial + reconnects)
  17157. EXPECT_GE(connection_count.load(), 2);
  17158. // Should have received messages from multiple connections
  17159. EXPECT_GE(message_count.load(), 2);
  17160. }
  17161. // Test: Last-Event-ID sent on reconnect
  17162. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17163. std::atomic<int> connection_count{0};
  17164. std::vector<std::string> received_last_event_ids;
  17165. std::mutex id_mutex;
  17166. // Endpoint that checks Last-Event-ID header and sends event with ID
  17167. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17168. int conn = connection_count.fetch_add(1);
  17169. // Capture the Last-Event-ID header from each connection
  17170. {
  17171. std::lock_guard<std::mutex> lock(id_mutex);
  17172. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17173. }
  17174. res.set_chunked_content_provider(
  17175. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17176. if (offset == 0) {
  17177. std::string event =
  17178. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17179. sink.write(event.data(), event.size());
  17180. }
  17181. return false;
  17182. });
  17183. });
  17184. Client client("localhost", get_port());
  17185. sse::SSEClient sse(client, "/reconnect-with-id");
  17186. sse.set_reconnect_interval(100);
  17187. sse.set_max_reconnect_attempts(3);
  17188. sse.start_async();
  17189. // Wait for at least 2 connections
  17190. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17191. sse.stop();
  17192. // Verify behavior
  17193. std::lock_guard<std::mutex> lock(id_mutex);
  17194. EXPECT_GE(received_last_event_ids.size(), 2u);
  17195. // First connection should have no Last-Event-ID
  17196. if (!received_last_event_ids.empty()) {
  17197. EXPECT_EQ(received_last_event_ids[0], "");
  17198. }
  17199. // Second connection should have Last-Event-ID from first connection
  17200. if (received_last_event_ids.size() >= 2) {
  17201. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17202. }
  17203. }
  17204. // Test: set_headers updates headers used on reconnect
  17205. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17206. std::vector<std::string> received_tokens;
  17207. std::mutex token_mutex;
  17208. // Endpoint that captures Authorization header
  17209. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17210. {
  17211. std::lock_guard<std::mutex> lock(token_mutex);
  17212. received_tokens.push_back(req.get_header_value("Authorization"));
  17213. }
  17214. res.set_chunked_content_provider(
  17215. "text/event-stream", [](size_t offset, DataSink &sink) {
  17216. if (offset == 0) {
  17217. std::string event = "data: hello\n\n";
  17218. sink.write(event.data(), event.size());
  17219. }
  17220. return false; // Close connection to trigger reconnect
  17221. });
  17222. });
  17223. Client client("localhost", get_port());
  17224. Headers headers = {{"Authorization", "Bearer old-token"}};
  17225. sse::SSEClient sse(client, "/auth-check", headers);
  17226. // Update headers on each successful connection
  17227. sse.on_open(
  17228. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17229. sse.set_reconnect_interval(100);
  17230. sse.set_max_reconnect_attempts(3);
  17231. sse.start_async();
  17232. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17233. sse.stop();
  17234. std::lock_guard<std::mutex> lock(token_mutex);
  17235. ASSERT_GE(received_tokens.size(), 2u);
  17236. // First connection uses original header
  17237. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17238. // Second connection uses updated header from set_headers
  17239. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17240. }
  17241. // Test: 401 allows reconnection (so on_error can refresh headers)
  17242. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17243. std::atomic<int> connection_count{0};
  17244. // Endpoint: returns 401 on first attempt, 200 on second
  17245. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17246. int conn = connection_count.fetch_add(1);
  17247. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17248. res.status = StatusCode::Unauthorized_401;
  17249. res.set_content("Unauthorized", "text/plain");
  17250. return;
  17251. }
  17252. res.set_chunked_content_provider(
  17253. "text/event-stream", [](size_t offset, DataSink &sink) {
  17254. if (offset == 0) {
  17255. std::string event = "data: authenticated\n\n";
  17256. sink.write(event.data(), event.size());
  17257. }
  17258. return false;
  17259. });
  17260. });
  17261. Client client("localhost", get_port());
  17262. Headers headers = {{"Authorization", "Bearer expired"}};
  17263. sse::SSEClient sse(client, "/auth-retry", headers);
  17264. std::atomic<bool> message_received{false};
  17265. // Refresh token on error
  17266. sse.on_error(
  17267. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17268. sse.on_message([&](const sse::SSEMessage &msg) {
  17269. if (msg.data == "authenticated") { message_received.store(true); }
  17270. });
  17271. sse.set_reconnect_interval(100);
  17272. sse.set_max_reconnect_attempts(3);
  17273. sse.start_async();
  17274. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17275. sse.stop();
  17276. // Should have reconnected after 401 and succeeded with new token
  17277. EXPECT_GE(connection_count.load(), 2);
  17278. EXPECT_TRUE(message_received.load());
  17279. }
  17280. TEST(Issue2318Test, EmptyHostString) {
  17281. {
  17282. httplib::Client cli_empty("", PORT);
  17283. auto res = cli_empty.Get("/");
  17284. ASSERT_FALSE(res);
  17285. EXPECT_EQ(httplib::Error::Connection, res.error());
  17286. }
  17287. {
  17288. httplib::Client cli(" ", PORT);
  17289. auto res = cli.Get("/");
  17290. ASSERT_FALSE(res);
  17291. EXPECT_EQ(httplib::Error::Connection, res.error());
  17292. }
  17293. }
  17294. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17295. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17296. Server svr;
  17297. // Set a small payload limit (1KB)
  17298. svr.set_payload_max_length(1024);
  17299. svr.Post("/test", [&](const Request &req, Response &res) {
  17300. res.set_content("Body size: " + std::to_string(req.body.size()),
  17301. "text/plain");
  17302. });
  17303. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17304. auto se = detail::scope_exit([&] {
  17305. svr.stop();
  17306. listen_thread.join();
  17307. });
  17308. svr.wait_until_ready();
  17309. // Create data that compresses well but exceeds limit when decompressed
  17310. // 8KB of repeated null bytes compresses to a very small size
  17311. std::string original_data(8 * 1024, '\0');
  17312. // Compress the data using gzip
  17313. std::string compressed_data;
  17314. detail::gzip_compressor compressor;
  17315. compressor.compress(original_data.data(), original_data.size(), true,
  17316. [&](const char *data, size_t size) {
  17317. compressed_data.append(data, size);
  17318. return true;
  17319. });
  17320. // Verify compression worked (compressed should be much smaller)
  17321. ASSERT_LT(compressed_data.size(), original_data.size());
  17322. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17323. // Send compressed data with Content-Encoding: gzip
  17324. Client cli(HOST, PORT);
  17325. Headers headers = {{"Content-Encoding", "gzip"}};
  17326. auto res =
  17327. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17328. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17330. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17331. }
  17332. #endif
  17333. // ============================================================================
  17334. // OpenSSL-Specific Tests
  17335. // ============================================================================
  17336. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17337. X509 *readCertificate(const std::string &strFileName) {
  17338. std::ifstream inStream(strFileName);
  17339. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17340. std::istreambuf_iterator<char>());
  17341. if (strCertPEM.empty()) return (nullptr);
  17342. BIO *pbCert = BIO_new(BIO_s_mem());
  17343. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17344. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17345. BIO_free(pbCert);
  17346. return (pCert);
  17347. }
  17348. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17349. std::ifstream inStream(strFileName);
  17350. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17351. std::istreambuf_iterator<char>());
  17352. if (strPrivateKeyPEM.empty()) return (nullptr);
  17353. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17354. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17355. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17356. BIO_free(pbPrivKey);
  17357. return (pPrivateKey);
  17358. }
  17359. TEST(BindServerTest, UpdateCerts) {
  17360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17361. int port = svr.bind_to_any_port("0.0.0.0");
  17362. ASSERT_TRUE(svr.is_valid());
  17363. ASSERT_TRUE(port > 0);
  17364. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17365. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17366. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17367. ASSERT_TRUE(cert != nullptr);
  17368. ASSERT_TRUE(ca_cert != nullptr);
  17369. ASSERT_TRUE(key != nullptr);
  17370. X509_STORE *cert_store = X509_STORE_new();
  17371. X509_STORE_add_cert(cert_store, ca_cert);
  17372. // svr.update_certs(cert, key, cert_store); // deprecated
  17373. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17374. CLIENT_CA_CERT_FILE);
  17375. ASSERT_TRUE(svr.is_valid());
  17376. svr.stop();
  17377. X509_STORE_free(cert_store);
  17378. X509_free(cert);
  17379. X509_free(ca_cert);
  17380. EVP_PKEY_free(key);
  17381. }
  17382. // Test that update_certs() updates client CA list correctly
  17383. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17384. // Start with file-based constructor
  17385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17386. ASSERT_TRUE(svr.is_valid());
  17387. // Initially no client CA list should be set
  17388. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17389. ASSERT_TRUE(ssl_ctx != nullptr);
  17390. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17391. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17392. EXPECT_EQ(0, count_before);
  17393. // Now update with client CA (PEM string)
  17394. std::string cert_pem, key_pem, ca_pem;
  17395. read_file(SERVER_CERT_FILE, cert_pem);
  17396. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17397. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17398. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17399. ASSERT_TRUE(svr.is_valid());
  17400. // Now client CA list should be set
  17401. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17402. ASSERT_TRUE(ca_list_after != nullptr);
  17403. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17404. }
  17405. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17406. // Test that the file-path SSLServer constructor properly sets the client CA
  17407. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17409. ASSERT_TRUE(svr.is_valid());
  17410. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17411. ASSERT_TRUE(ssl_ctx != nullptr);
  17412. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17413. ASSERT_TRUE(ca_list != nullptr);
  17414. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17415. }
  17416. #endif
  17417. // ============================================================================
  17418. // MbedTLS-Specific Tests
  17419. // ============================================================================
  17420. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17421. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17422. using namespace httplib::tls;
  17423. // Track if callback was invoked
  17424. bool callback_invoked = false;
  17425. // The callback receives void* ctx which is actually MbedTlsContext*
  17426. // We can access the mbedtls_ssl_config via the context
  17427. auto setup_callback = [&callback_invoked](void *ctx) {
  17428. callback_invoked = true;
  17429. // Cast to MbedTlsContext* to access the ssl config
  17430. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17431. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17432. // Use static variables to hold certificate data (simplified for test)
  17433. static mbedtls_x509_crt own_cert;
  17434. static mbedtls_pk_context own_key;
  17435. static mbedtls_x509_crt ca_chain;
  17436. static bool initialized = false;
  17437. if (!initialized) {
  17438. mbedtls_x509_crt_init(&own_cert);
  17439. mbedtls_pk_init(&own_key);
  17440. mbedtls_x509_crt_init(&ca_chain);
  17441. // Load server certificate
  17442. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17443. return false;
  17444. }
  17445. // Load server private key.
  17446. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17447. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17448. #if MBEDTLS_VERSION_MAJOR == 3
  17449. ,
  17450. mbedtls_ctr_drbg_random, nullptr
  17451. #endif
  17452. ) != 0) {
  17453. return false;
  17454. }
  17455. // Load CA chain for client verification
  17456. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17457. return false;
  17458. }
  17459. initialized = true;
  17460. }
  17461. // Configure the SSL config
  17462. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17463. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17464. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17465. // Set minimum TLS version using mbedTLS native API
  17466. #if MBEDTLS_VERSION_MAJOR >= 3
  17467. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17468. #else
  17469. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17470. MBEDTLS_SSL_MINOR_VERSION_3);
  17471. #endif
  17472. return true;
  17473. };
  17474. SSLServer svr(setup_callback);
  17475. ASSERT_TRUE(svr.is_valid());
  17476. ASSERT_TRUE(callback_invoked);
  17477. svr.Get("/test", [&](const Request &req, Response &res) {
  17478. res.set_content("test", "text/plain");
  17479. auto cert = req.peer_cert();
  17480. ASSERT_TRUE(static_cast<bool>(cert));
  17481. auto common_name = cert.subject_cn();
  17482. EXPECT_EQ("Common Name", common_name);
  17483. });
  17484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17485. auto se = detail::scope_exit([&] {
  17486. svr.stop();
  17487. t.join();
  17488. ASSERT_FALSE(svr.is_running());
  17489. });
  17490. svr.wait_until_ready();
  17491. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17492. cli.enable_server_certificate_verification(false);
  17493. cli.set_connection_timeout(30);
  17494. auto res = cli.Get("/test");
  17495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17496. ASSERT_EQ(StatusCode::OK_200, res->status);
  17497. }
  17498. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17499. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17500. // keep-alive SSL session, which reads through that config in
  17501. // mbedtls_ssl_close_notify.
  17502. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17504. ASSERT_TRUE(svr.is_valid());
  17505. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17506. res.set_content("test", "text/plain");
  17507. });
  17508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17509. auto se = detail::scope_exit([&] {
  17510. svr.stop();
  17511. t.join();
  17512. ASSERT_FALSE(svr.is_running());
  17513. });
  17514. svr.wait_until_ready();
  17515. {
  17516. SSLClient cli(HOST, PORT);
  17517. cli.enable_server_certificate_verification(false);
  17518. cli.set_keep_alive(true);
  17519. auto res = cli.Get("/test");
  17520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17521. ASSERT_EQ(StatusCode::OK_200, res->status);
  17522. // cli is destructed here with the keep-alive SSL session still open.
  17523. }
  17524. }
  17525. #endif
  17526. // WebSocket Tests
  17527. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17528. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17529. // defining the meaning of these bits has been negotiated.
  17530. auto make_frame = [](uint8_t first_byte) {
  17531. std::string frame;
  17532. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17533. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17534. frame += "Hello";
  17535. return frame;
  17536. };
  17537. // RSV1 set (0x40)
  17538. {
  17539. detail::BufferStream strm;
  17540. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17541. ws::Opcode opcode;
  17542. std::string payload;
  17543. bool fin;
  17544. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17545. false, 1024));
  17546. }
  17547. // RSV2 set (0x20)
  17548. {
  17549. detail::BufferStream strm;
  17550. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17551. ws::Opcode opcode;
  17552. std::string payload;
  17553. bool fin;
  17554. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17555. false, 1024));
  17556. }
  17557. // RSV3 set (0x10)
  17558. {
  17559. detail::BufferStream strm;
  17560. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17561. ws::Opcode opcode;
  17562. std::string payload;
  17563. bool fin;
  17564. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17565. false, 1024));
  17566. }
  17567. // No RSV bits set - should succeed
  17568. {
  17569. detail::BufferStream strm;
  17570. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17571. ws::Opcode opcode;
  17572. std::string payload;
  17573. bool fin;
  17574. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17575. false, 1024));
  17576. EXPECT_EQ(ws::Opcode::Text, opcode);
  17577. EXPECT_EQ("Hello", payload);
  17578. EXPECT_TRUE(fin);
  17579. }
  17580. }
  17581. TEST(WebSocketTest, ControlFrameValidation) {
  17582. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17583. // payload length <= 125.
  17584. // Ping with FIN=0 - must be rejected
  17585. {
  17586. detail::BufferStream strm;
  17587. std::string frame;
  17588. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17589. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17590. strm.write(frame.data(), frame.size());
  17591. ws::Opcode opcode;
  17592. std::string payload;
  17593. bool fin;
  17594. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17595. false, 1024));
  17596. }
  17597. // Close with FIN=0 - must be rejected
  17598. {
  17599. detail::BufferStream strm;
  17600. std::string frame;
  17601. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17602. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17603. strm.write(frame.data(), frame.size());
  17604. ws::Opcode opcode;
  17605. std::string payload;
  17606. bool fin;
  17607. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17608. false, 1024));
  17609. }
  17610. // Ping with payload_len=126 (extended length) - must be rejected
  17611. {
  17612. detail::BufferStream strm;
  17613. std::string frame;
  17614. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17615. frame += static_cast<char>(126); // payload_len=126 (>125)
  17616. frame += static_cast<char>(0x00); // extended length high byte
  17617. frame += static_cast<char>(126); // extended length low byte
  17618. frame += std::string(126, 'x');
  17619. strm.write(frame.data(), frame.size());
  17620. ws::Opcode opcode;
  17621. std::string payload;
  17622. bool fin;
  17623. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17624. false, 1024));
  17625. }
  17626. // Ping with FIN=1 and payload_len=125 - should succeed
  17627. {
  17628. detail::BufferStream strm;
  17629. std::string frame;
  17630. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17631. frame += static_cast<char>(125); // payload_len=125
  17632. frame += std::string(125, 'x');
  17633. strm.write(frame.data(), frame.size());
  17634. ws::Opcode opcode;
  17635. std::string payload;
  17636. bool fin;
  17637. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17638. false, 1024));
  17639. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17640. EXPECT_EQ(125u, payload.size());
  17641. EXPECT_TRUE(fin);
  17642. }
  17643. }
  17644. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17645. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17646. // length MUST be 0.
  17647. // MSB set - must be rejected
  17648. {
  17649. detail::BufferStream strm;
  17650. std::string frame;
  17651. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17652. frame += static_cast<char>(127); // 64-bit extended length
  17653. frame += static_cast<char>(0x80); // MSB set (invalid)
  17654. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17655. strm.write(frame.data(), frame.size());
  17656. ws::Opcode opcode;
  17657. std::string payload;
  17658. bool fin;
  17659. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17660. false, 1024));
  17661. }
  17662. // MSB clear - should pass length parsing (will be rejected by max_len,
  17663. // but that's a different check; use a small length to verify)
  17664. {
  17665. detail::BufferStream strm;
  17666. std::string frame;
  17667. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17668. frame += static_cast<char>(127); // 64-bit extended length
  17669. frame += std::string(7, '\0'); // high bytes = 0
  17670. frame += static_cast<char>(0x03); // length = 3
  17671. frame += "abc";
  17672. strm.write(frame.data(), frame.size());
  17673. ws::Opcode opcode;
  17674. std::string payload;
  17675. bool fin;
  17676. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17677. false, 1024));
  17678. EXPECT_EQ(ws::Opcode::Text, opcode);
  17679. EXPECT_EQ("abc", payload);
  17680. }
  17681. }
  17682. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17683. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17684. // Valid UTF-8
  17685. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17686. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17687. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17688. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17689. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17690. // Invalid UTF-8
  17691. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17692. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17693. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17694. EXPECT_FALSE(
  17695. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17696. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17697. }
  17698. TEST(WebSocketTest, ConnectAndDisconnect) {
  17699. Server svr;
  17700. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17701. std::string msg;
  17702. while (ws.read(msg)) {}
  17703. });
  17704. auto port = svr.bind_to_any_port(HOST);
  17705. std::thread t([&]() { svr.listen_after_bind(); });
  17706. svr.wait_until_ready();
  17707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17708. auto res = client.connect();
  17709. ASSERT_TRUE(res);
  17710. EXPECT_EQ(Error::Success, res.error());
  17711. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17712. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17713. EXPECT_TRUE(client.is_open());
  17714. client.close();
  17715. EXPECT_FALSE(client.is_open());
  17716. svr.stop();
  17717. t.join();
  17718. }
  17719. TEST(WebSocketTest, ValidURL) {
  17720. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17721. EXPECT_TRUE(ws1.is_valid());
  17722. ws::WebSocketClient ws2("ws://example.com/path");
  17723. EXPECT_TRUE(ws2.is_valid());
  17724. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17725. EXPECT_TRUE(ws3.is_valid());
  17726. #ifdef CPPHTTPLIB_SSL_ENABLED
  17727. ws::WebSocketClient wss1("wss://example.com/path");
  17728. EXPECT_TRUE(wss1.is_valid());
  17729. ws::WebSocketClient wss2("wss://example.com:443/path");
  17730. EXPECT_TRUE(wss2.is_valid());
  17731. #endif
  17732. }
  17733. TEST(WebSocketTest, InvalidURL) {
  17734. // No scheme
  17735. ws::WebSocketClient ws1("localhost:8080/path");
  17736. EXPECT_FALSE(ws1.is_valid());
  17737. // No path
  17738. ws::WebSocketClient ws2("ws://localhost:8080");
  17739. EXPECT_FALSE(ws2.is_valid());
  17740. // Empty string
  17741. ws::WebSocketClient ws3("");
  17742. EXPECT_FALSE(ws3.is_valid());
  17743. // Missing host
  17744. ws::WebSocketClient ws4("ws://:8080/path");
  17745. EXPECT_FALSE(ws4.is_valid());
  17746. // Port number overflow — should not crash
  17747. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17748. EXPECT_FALSE(ws5.is_valid());
  17749. // Port out of range
  17750. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17751. EXPECT_FALSE(ws6.is_valid());
  17752. }
  17753. TEST(WebSocketTest, UnsupportedScheme) {
  17754. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17755. ws::WebSocketClient ws1("http://localhost:8080/path");
  17756. EXPECT_FALSE(ws1.is_valid());
  17757. ws::WebSocketClient ws2("https://localhost:8080/path");
  17758. EXPECT_FALSE(ws2.is_valid());
  17759. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17760. EXPECT_FALSE(ws3.is_valid());
  17761. #else
  17762. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17763. std::invalid_argument);
  17764. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17765. std::invalid_argument);
  17766. #endif
  17767. }
  17768. TEST(WebSocketTest, ConnectWhenInvalid) {
  17769. ws::WebSocketClient ws("not a valid url");
  17770. EXPECT_FALSE(ws.is_valid());
  17771. auto res = ws.connect();
  17772. EXPECT_FALSE(res);
  17773. EXPECT_EQ(Error::Connection, res.error());
  17774. EXPECT_EQ(-1, res.status());
  17775. }
  17776. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17777. // Grab a port that is free, then close it again so nothing listens there
  17778. Server svr;
  17779. auto port = svr.bind_to_any_port(HOST);
  17780. svr.stop();
  17781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17782. auto res = client.connect();
  17783. ASSERT_FALSE(res);
  17784. EXPECT_EQ(Error::Connection, res.error());
  17785. EXPECT_EQ(-1, res.status());
  17786. }
  17787. TEST(WebSocketTest, DefaultPort) {
  17788. ws::WebSocketClient ws1("ws://example.com/path");
  17789. EXPECT_TRUE(ws1.is_valid());
  17790. // ws:// defaults to port 80 (verified by successful parse)
  17791. #ifdef CPPHTTPLIB_SSL_ENABLED
  17792. ws::WebSocketClient ws2("wss://example.com/path");
  17793. EXPECT_TRUE(ws2.is_valid());
  17794. // wss:// defaults to port 443 (verified by successful parse)
  17795. #endif
  17796. }
  17797. TEST(WebSocketTest, IPv6LiteralAddress) {
  17798. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17799. EXPECT_TRUE(ws1.is_valid());
  17800. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17801. EXPECT_TRUE(ws2.is_valid());
  17802. }
  17803. TEST(WebSocketTest, ComplexPath) {
  17804. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17805. EXPECT_TRUE(ws1.is_valid());
  17806. ws::WebSocketClient ws2("ws://localhost:8080/");
  17807. EXPECT_TRUE(ws2.is_valid());
  17808. }
  17809. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17810. Server svr;
  17811. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17812. std::string msg;
  17813. while (ws.read(msg)) {}
  17814. });
  17815. auto port = svr.bind_to_any_port(HOST);
  17816. std::thread t([&]() { svr.listen_after_bind(); });
  17817. svr.wait_until_ready();
  17818. auto another_host = "example.com";
  17819. auto wrong_ip = "192.0.2.1";
  17820. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17821. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17822. ASSERT_TRUE(client.connect());
  17823. EXPECT_TRUE(client.is_open());
  17824. client.close();
  17825. svr.stop();
  17826. t.join();
  17827. }
  17828. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17829. Server svr;
  17830. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17831. std::string msg;
  17832. while (ws.read(msg)) {}
  17833. });
  17834. auto port = svr.bind_to_any_port(HOST);
  17835. std::thread t([&]() { svr.listen_after_bind(); });
  17836. svr.wait_until_ready();
  17837. auto wrong_ip = "192.0.2.1";
  17838. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17839. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17840. client.set_connection_timeout(1);
  17841. client.set_read_timeout(1);
  17842. client.set_write_timeout(1);
  17843. EXPECT_FALSE(client.connect());
  17844. EXPECT_FALSE(client.is_open());
  17845. svr.stop();
  17846. t.join();
  17847. }
  17848. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17849. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17850. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17851. // (RFC 6761) is only a map key and the Host header value.
  17852. auto host = "target.invalid";
  17853. Server svr;
  17854. std::string received_host;
  17855. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17856. received_host = req.get_header_value("Host");
  17857. std::string msg;
  17858. while (ws.read(msg)) {}
  17859. });
  17860. auto port = svr.bind_to_any_port(HOST);
  17861. std::thread t([&]() { svr.listen_after_bind(); });
  17862. // ASSERT_* below returns from the test body, which would leave t joinable
  17863. // and make ~thread call std::terminate.
  17864. auto se = detail::scope_exit([&] {
  17865. svr.stop();
  17866. if (t.joinable()) { t.join(); }
  17867. });
  17868. svr.wait_until_ready();
  17869. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17870. std::to_string(port) + "/ws");
  17871. client.set_hostname_addr_map({{host, HOST}});
  17872. ASSERT_TRUE(client.connect());
  17873. EXPECT_TRUE(client.is_open());
  17874. client.close();
  17875. svr.stop();
  17876. t.join();
  17877. // The mapping only redirects the connection; the identity stays host_.
  17878. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17879. }
  17880. class WebSocketIntegrationTest : public ::testing::Test {
  17881. protected:
  17882. void SetUp() override {
  17883. server_ = httplib::detail::make_unique<Server>();
  17884. setup_server();
  17885. start_server();
  17886. }
  17887. void TearDown() override {
  17888. server_->stop();
  17889. if (server_thread_.joinable()) { server_thread_.join(); }
  17890. }
  17891. void setup_server() {
  17892. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17893. std::string msg;
  17894. ws::ReadResult ret;
  17895. while ((ret = ws.read(msg))) {
  17896. if (ret == ws::Binary) {
  17897. ws.send(msg.data(), msg.size());
  17898. } else {
  17899. ws.send(msg);
  17900. }
  17901. }
  17902. });
  17903. server_->WebSocket("/ws-echo-string",
  17904. [](const Request &, ws::WebSocket &ws) {
  17905. std::string msg;
  17906. while (ws.read(msg)) {
  17907. ws.send("echo: " + msg);
  17908. }
  17909. });
  17910. server_->WebSocket(
  17911. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17912. // Echo back request metadata
  17913. ws.send("path:" + req.path);
  17914. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17915. std::string msg;
  17916. while (ws.read(msg)) {}
  17917. });
  17918. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17919. std::string msg;
  17920. ws.read(msg); // wait for a message
  17921. ws.close();
  17922. });
  17923. server_->WebSocket("/ws-close-status",
  17924. [](const Request &, ws::WebSocket &ws) {
  17925. std::string msg;
  17926. ws.read(msg); // wait for a message
  17927. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17928. });
  17929. server_->WebSocket(
  17930. "/ws-subprotocol",
  17931. [](const Request &, ws::WebSocket &ws) {
  17932. std::string msg;
  17933. while (ws.read(msg)) {
  17934. ws.send(msg);
  17935. }
  17936. },
  17937. [](const std::vector<std::string> &protocols) -> std::string {
  17938. for (const auto &p : protocols) {
  17939. if (p == "graphql-ws") { return p; }
  17940. }
  17941. return "";
  17942. });
  17943. }
  17944. void start_server() {
  17945. port_ = server_->bind_to_any_port(HOST);
  17946. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17947. server_->wait_until_ready();
  17948. }
  17949. std::unique_ptr<Server> server_;
  17950. std::thread server_thread_;
  17951. int port_ = 0;
  17952. };
  17953. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17954. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17955. "/ws-echo");
  17956. ASSERT_TRUE(client.connect());
  17957. ASSERT_TRUE(client.is_open());
  17958. ASSERT_TRUE(client.send("Hello WebSocket"));
  17959. std::string msg;
  17960. EXPECT_EQ(ws::Text, client.read(msg));
  17961. EXPECT_EQ("Hello WebSocket", msg);
  17962. client.close();
  17963. }
  17964. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17965. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17966. "/ws-echo");
  17967. ASSERT_TRUE(client.connect());
  17968. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17969. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17970. std::string msg;
  17971. EXPECT_EQ(ws::Binary, client.read(msg));
  17972. EXPECT_EQ(binary_data, msg);
  17973. client.close();
  17974. }
  17975. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17976. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17977. "/ws-echo");
  17978. ASSERT_TRUE(client.connect());
  17979. for (int i = 0; i < 10; i++) {
  17980. auto text = "message " + std::to_string(i);
  17981. ASSERT_TRUE(client.send(text));
  17982. std::string msg;
  17983. ASSERT_TRUE(client.read(msg));
  17984. EXPECT_EQ(text, msg);
  17985. }
  17986. client.close();
  17987. }
  17988. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17990. "/ws-close");
  17991. ASSERT_TRUE(client.connect());
  17992. // Send a message to trigger the server to close
  17993. ASSERT_TRUE(client.send("trigger close"));
  17994. // The server will close, so read should return false
  17995. std::string msg;
  17996. EXPECT_FALSE(client.read(msg));
  17997. EXPECT_FALSE(client.is_open());
  17998. }
  17999. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18001. "/ws-echo");
  18002. ASSERT_TRUE(client.connect());
  18003. // 128KB message
  18004. std::string large_data(128 * 1024, 'X');
  18005. ASSERT_TRUE(client.send(large_data));
  18006. std::string msg;
  18007. ASSERT_TRUE(client.read(msg));
  18008. EXPECT_EQ(large_data, msg);
  18009. client.close();
  18010. }
  18011. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18013. "/ws-echo");
  18014. ASSERT_TRUE(client.connect());
  18015. const int num_threads = 4;
  18016. std::vector<std::thread> threads;
  18017. std::atomic<int> send_count{0};
  18018. for (int t = 0; t < num_threads; t++) {
  18019. threads.emplace_back([&client, &send_count, t]() {
  18020. for (int i = 0; i < 5; i++) {
  18021. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18022. if (client.send(text)) { send_count++; }
  18023. }
  18024. });
  18025. }
  18026. for (auto &th : threads) {
  18027. th.join();
  18028. }
  18029. int received = 0;
  18030. std::string msg;
  18031. while (received < send_count.load()) {
  18032. if (!client.read(msg)) { break; }
  18033. received++;
  18034. }
  18035. EXPECT_EQ(send_count.load(), received);
  18036. client.close();
  18037. }
  18038. TEST_F(WebSocketIntegrationTest, ReadString) {
  18039. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18040. "/ws-echo-string");
  18041. ASSERT_TRUE(client.connect());
  18042. ASSERT_TRUE(client.send("hello"));
  18043. std::string msg;
  18044. ASSERT_TRUE(client.read(msg));
  18045. EXPECT_EQ("echo: hello", msg);
  18046. ASSERT_TRUE(client.send("world"));
  18047. ASSERT_TRUE(client.read(msg));
  18048. EXPECT_EQ("echo: world", msg);
  18049. client.close();
  18050. }
  18051. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18052. Headers headers = {{"X-Test-Header", "test-value"}};
  18053. ws::WebSocketClient client(
  18054. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18055. ASSERT_TRUE(client.connect());
  18056. std::string msg;
  18057. ASSERT_TRUE(client.read(msg));
  18058. EXPECT_EQ("path:/ws-request-info", msg);
  18059. ASSERT_TRUE(client.read(msg));
  18060. EXPECT_EQ("header:test-value", msg);
  18061. client.close();
  18062. }
  18063. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18064. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18065. "/ws-echo");
  18066. client.set_read_timeout(1, 0); // 1 second
  18067. ASSERT_TRUE(client.connect());
  18068. // Don't send anything — server echo handler waits for a message,
  18069. // so read() should time out and return false.
  18070. std::string msg;
  18071. EXPECT_FALSE(client.read(msg));
  18072. }
  18073. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18074. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18075. "/ws-echo");
  18076. client.set_read_timeout(5, 0);
  18077. ASSERT_TRUE(client.connect());
  18078. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18079. // The server should reject it and close the connection.
  18080. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18081. client.send(oversized);
  18082. // The server's read() should have failed due to payload limit,
  18083. // so our read() should return false (connection closed).
  18084. std::string msg;
  18085. EXPECT_FALSE(client.read(msg));
  18086. }
  18087. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18089. "/ws-echo");
  18090. client.set_read_timeout(10, 0);
  18091. ASSERT_TRUE(client.connect());
  18092. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18093. // This should succeed.
  18094. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18095. ASSERT_TRUE(client.send(at_limit));
  18096. std::string msg;
  18097. ASSERT_TRUE(client.read(msg));
  18098. EXPECT_EQ(at_limit.size(), msg.size());
  18099. client.close();
  18100. }
  18101. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18103. "/nonexistent");
  18104. auto res = client.connect();
  18105. EXPECT_FALSE(res);
  18106. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18107. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18108. EXPECT_FALSE(client.is_open());
  18109. }
  18110. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18112. "/ws-echo");
  18113. ASSERT_TRUE(client.connect());
  18114. ASSERT_TRUE(client.send(""));
  18115. std::string msg;
  18116. EXPECT_EQ(ws::Text, client.read(msg));
  18117. EXPECT_EQ("", msg);
  18118. client.close();
  18119. }
  18120. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18121. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18122. "/ws-echo");
  18123. // First connection
  18124. ASSERT_TRUE(client.connect());
  18125. ASSERT_TRUE(client.send("first"));
  18126. std::string msg;
  18127. ASSERT_TRUE(client.read(msg));
  18128. EXPECT_EQ("first", msg);
  18129. client.close();
  18130. EXPECT_FALSE(client.is_open());
  18131. // Reconnect using the same client object
  18132. ASSERT_TRUE(client.connect());
  18133. ASSERT_TRUE(client.is_open());
  18134. ASSERT_TRUE(client.send("second"));
  18135. ASSERT_TRUE(client.read(msg));
  18136. EXPECT_EQ("second", msg);
  18137. client.close();
  18138. }
  18139. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18141. "/ws-close-status");
  18142. ASSERT_TRUE(client.connect());
  18143. // Trigger the server to close with GoingAway status
  18144. ASSERT_TRUE(client.send("trigger"));
  18145. // read() should return false after receiving the close frame
  18146. std::string msg;
  18147. EXPECT_FALSE(client.read(msg));
  18148. EXPECT_FALSE(client.is_open());
  18149. }
  18150. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18152. "/ws-echo");
  18153. ASSERT_TRUE(client.connect());
  18154. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18155. EXPECT_FALSE(client.is_open());
  18156. }
  18157. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18158. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18159. ws::WebSocketClient client(
  18160. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18161. ASSERT_TRUE(client.connect());
  18162. // Server should have selected graphql-ws
  18163. EXPECT_EQ("graphql-ws", client.subprotocol());
  18164. client.close();
  18165. }
  18166. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18167. Headers headers;
  18168. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18169. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18170. ws::WebSocketClient client(
  18171. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18172. ASSERT_TRUE(client.connect());
  18173. // The offer on the second field line counts too, so graphql-ws is selected
  18174. EXPECT_EQ("graphql-ws", client.subprotocol());
  18175. client.close();
  18176. }
  18177. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18178. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18179. ws::WebSocketClient client(
  18180. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18181. ASSERT_TRUE(client.connect());
  18182. // Server should not have selected any subprotocol
  18183. EXPECT_TRUE(client.subprotocol().empty());
  18184. client.close();
  18185. }
  18186. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18187. // Connect without requesting any subprotocol
  18188. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18189. "/ws-subprotocol");
  18190. ASSERT_TRUE(client.connect());
  18191. EXPECT_TRUE(client.subprotocol().empty());
  18192. client.close();
  18193. }
  18194. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18196. "/ws-echo");
  18197. client.set_tcp_nodelay(true);
  18198. client.set_connection_timeout(3, 0);
  18199. bool socket_options_called = false;
  18200. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18201. ASSERT_TRUE(client.connect());
  18202. ASSERT_TRUE(client.is_open());
  18203. EXPECT_TRUE(socket_options_called);
  18204. ASSERT_TRUE(client.send("hello"));
  18205. std::string msg;
  18206. auto result = client.read(msg);
  18207. EXPECT_EQ(result, ws::ReadResult::Text);
  18208. EXPECT_EQ(msg, "hello");
  18209. client.close();
  18210. }
  18211. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18212. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18213. "/ws-echo");
  18214. client.set_connection_timeout(std::chrono::seconds(3));
  18215. client.set_write_timeout(std::chrono::seconds(3));
  18216. // A sub-second remainder exercises the seconds/microseconds split.
  18217. client.set_read_timeout(std::chrono::milliseconds(1500));
  18218. ASSERT_TRUE(client.connect());
  18219. auto start = std::chrono::steady_clock::now();
  18220. std::string msg;
  18221. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18222. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18223. std::chrono::steady_clock::now() - start)
  18224. .count();
  18225. // Above 1s so that dropping the microseconds half of the split fails here,
  18226. // and well under the 300s default so that ignoring the setter fails too.
  18227. EXPECT_GE(elapsed, 1400);
  18228. EXPECT_LT(elapsed, 30000);
  18229. }
  18230. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18231. Server svr;
  18232. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18233. if (!req.has_header("Authorization")) {
  18234. res.status = StatusCode::Unauthorized_401;
  18235. res.set_content("Unauthorized", "text/plain");
  18236. return Server::HandlerResponse::Handled;
  18237. }
  18238. return Server::HandlerResponse::Unhandled;
  18239. });
  18240. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18241. std::string msg;
  18242. while (ws.read(msg)) {
  18243. ws.send(msg);
  18244. }
  18245. });
  18246. auto port = svr.bind_to_any_port("localhost");
  18247. std::thread t([&]() { svr.listen_after_bind(); });
  18248. svr.wait_until_ready();
  18249. // Without Authorization header - should be rejected before upgrade
  18250. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18251. EXPECT_FALSE(client1.connect());
  18252. // With Authorization header - should succeed
  18253. Headers headers = {{"Authorization", "Bearer token123"}};
  18254. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18255. headers);
  18256. ASSERT_TRUE(client2.connect());
  18257. ASSERT_TRUE(client2.send("hello"));
  18258. std::string msg;
  18259. ASSERT_TRUE(client2.read(msg));
  18260. EXPECT_EQ("hello", msg);
  18261. client2.close();
  18262. svr.stop();
  18263. t.join();
  18264. }
  18265. TEST(WebSocketTest, QueryStringInHandshake) {
  18266. Server svr;
  18267. std::mutex mtx;
  18268. std::string received_target;
  18269. std::string received_token;
  18270. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18271. {
  18272. std::lock_guard<std::mutex> lock(mtx);
  18273. received_target = req.target;
  18274. if (req.has_param("token")) {
  18275. received_token = req.get_param_value("token");
  18276. }
  18277. }
  18278. std::string msg;
  18279. while (ws.read(msg)) {
  18280. ws.send(msg);
  18281. }
  18282. });
  18283. auto port = svr.bind_to_any_port("localhost");
  18284. std::thread t([&]() { svr.listen_after_bind(); });
  18285. svr.wait_until_ready();
  18286. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18287. "/ws?token=ABC&session=123");
  18288. ASSERT_TRUE(client.connect());
  18289. // Round-trip ensures the handler has run and captured the request.
  18290. ASSERT_TRUE(client.send("hello"));
  18291. std::string msg;
  18292. ASSERT_TRUE(client.read(msg));
  18293. EXPECT_EQ("hello", msg);
  18294. client.close();
  18295. {
  18296. std::lock_guard<std::mutex> lock(mtx);
  18297. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18298. EXPECT_EQ("ABC", received_token);
  18299. }
  18300. svr.stop();
  18301. t.join();
  18302. }
  18303. // Run a handshake against a throwaway server and hand the request the server
  18304. // received back to the caller, so tests can assert on the headers the client
  18305. // actually put on the wire.
  18306. static void capture_websocket_handshake_request(
  18307. const Headers &client_headers,
  18308. std::function<void(const Request &, int port)> verify) {
  18309. Server svr;
  18310. std::mutex mtx;
  18311. Request received;
  18312. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18313. {
  18314. std::lock_guard<std::mutex> lock(mtx);
  18315. received = req;
  18316. }
  18317. std::string msg;
  18318. while (ws.read(msg)) {
  18319. ws.send(msg);
  18320. }
  18321. });
  18322. auto port = svr.bind_to_any_port("localhost");
  18323. std::thread t([&]() { svr.listen_after_bind(); });
  18324. auto se = detail::scope_exit([&] {
  18325. svr.stop();
  18326. t.join();
  18327. });
  18328. svr.wait_until_ready();
  18329. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18330. client_headers);
  18331. ASSERT_TRUE(client.connect());
  18332. ASSERT_TRUE(client.send("hello"));
  18333. std::string msg;
  18334. ASSERT_TRUE(client.read(msg));
  18335. client.close();
  18336. {
  18337. std::lock_guard<std::mutex> lock(mtx);
  18338. verify(received, port);
  18339. }
  18340. }
  18341. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18342. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18343. // Non-default port must be present in the Host header. Default ports
  18344. // (80/443) are omitted; that logic is covered by
  18345. // MakeHostAndPortStringTest.
  18346. EXPECT_EQ("localhost:" + std::to_string(port),
  18347. req.get_header_value("Host"));
  18348. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18349. req.get_header_value("User-Agent"));
  18350. EXPECT_FALSE(req.has_header("Accept"));
  18351. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18352. EXPECT_FALSE(req.has_header("Content-Length"));
  18353. });
  18354. }
  18355. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18356. capture_websocket_handshake_request(
  18357. {{"Host", "example.com"},
  18358. {"User-Agent", "custom-agent"},
  18359. {"X-Custom", "value"}},
  18360. [](const Request &req, int) {
  18361. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18362. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18363. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18364. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18365. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18366. });
  18367. }
  18368. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18369. capture_websocket_handshake_request(
  18370. {{"Upgrade", "bogus"},
  18371. {"Connection", "close"},
  18372. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18373. {"Sec-WebSocket-Version", "8"}},
  18374. [](const Request &req, int) {
  18375. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18376. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18377. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18378. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18379. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18380. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18381. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18382. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18383. req.get_header_value("Sec-WebSocket-Key"));
  18384. });
  18385. }
  18386. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18387. // A header the client refuses to send must abort the handshake before any
  18388. // part of it reaches the wire; a lone request line would otherwise sit in
  18389. // the peer's buffer as a truncated request.
  18390. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18391. ASSERT_NE(INVALID_SOCKET, srv);
  18392. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18393. sockaddr_in addr{};
  18394. addr.sin_family = AF_INET;
  18395. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18396. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18397. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18398. ASSERT_EQ(0, ::listen(srv, 1));
  18399. sockaddr_in bound{};
  18400. socklen_t bound_len = sizeof(bound);
  18401. ASSERT_EQ(
  18402. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18403. auto port = ntohs(bound.sin_port);
  18404. ssize_t received = -1;
  18405. std::thread t([&] {
  18406. // Bound every blocking call so a regression fails the test with a bad
  18407. // value instead of hanging the suite.
  18408. fd_set rfds;
  18409. FD_ZERO(&rfds);
  18410. FD_SET(srv, &rfds);
  18411. timeval tv{5, 0};
  18412. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18413. 0) {
  18414. return;
  18415. }
  18416. sockaddr_in cli_addr{};
  18417. socklen_t cli_len = sizeof(cli_addr);
  18418. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18419. if (cli == INVALID_SOCKET) { return; }
  18420. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18421. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18422. char buf[4096];
  18423. received = ::recv(cli, buf, sizeof(buf), 0);
  18424. });
  18425. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18426. // connect() has already shut the socket down by the time it returns false,
  18427. // so the peer sees EOF without waiting for the client to be destroyed.
  18428. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18429. {{"X-Bad", "a\r\nInjected: 1"}});
  18430. EXPECT_FALSE(client.connect());
  18431. t.join();
  18432. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18433. EXPECT_EQ(0, received);
  18434. }
  18435. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18436. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18437. // contains "upgrade" as a substring is a different token and must not
  18438. // start a WebSocket handshake.
  18439. auto make_request = [](const std::vector<std::string> &connection_values) {
  18440. Request req;
  18441. req.method = "GET";
  18442. req.headers.emplace("Upgrade", "websocket");
  18443. for (const auto &value : connection_values) {
  18444. req.headers.emplace("Connection", value);
  18445. }
  18446. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18447. req.headers.emplace("Sec-WebSocket-Version", "13");
  18448. return req;
  18449. };
  18450. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18451. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18452. EXPECT_TRUE(
  18453. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18454. EXPECT_TRUE(
  18455. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18456. EXPECT_TRUE(
  18457. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18458. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18459. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18460. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18461. EXPECT_FALSE(
  18462. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18463. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18464. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18465. }
  18466. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18467. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18468. // asks recipients to match each protocol-name case-insensitively, and RFC
  18469. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18470. // client naming websocket alongside another protocol, or on a second field
  18471. // line, is offering websocket; a value that merely contains "websocket" as a
  18472. // substring is a different protocol name and is not.
  18473. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18474. Request req;
  18475. req.method = "GET";
  18476. for (const auto &value : upgrade_values) {
  18477. req.headers.emplace("Upgrade", value);
  18478. }
  18479. req.headers.emplace("Connection", "Upgrade");
  18480. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18481. req.headers.emplace("Sec-WebSocket-Version", "13");
  18482. return req;
  18483. };
  18484. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18485. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18486. EXPECT_TRUE(
  18487. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18488. EXPECT_TRUE(
  18489. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18490. EXPECT_TRUE(
  18491. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18492. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18493. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18494. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18495. EXPECT_FALSE(
  18496. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18497. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18498. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18499. }
  18500. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18501. Server svr;
  18502. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18503. auto port = svr.bind_to_any_port("localhost");
  18504. std::thread t([&]() { svr.listen_after_bind(); });
  18505. auto se = detail::scope_exit([&] {
  18506. svr.stop();
  18507. t.join();
  18508. });
  18509. svr.wait_until_ready();
  18510. Headers headers = {{"Upgrade", "websocket"},
  18511. {"Connection", "notupgrade"},
  18512. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18513. {"Sec-WebSocket-Version", "13"}};
  18514. Client cli("localhost", port);
  18515. auto res = cli.Get("/ws", headers);
  18516. // The route exists only as a WebSocket route, so a request that fails the
  18517. // handshake check falls through to ordinary routing.
  18518. ASSERT_TRUE(res);
  18519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18520. }
  18521. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18522. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18523. // Connection value is the only thing left for the client to reject.
  18524. Server svr;
  18525. svr.Get("/ws", [](const Request &req, Response &res) {
  18526. res.status = StatusCode::SwitchingProtocol_101;
  18527. res.set_header("Upgrade", "websocket");
  18528. res.set_header("Connection", "notupgrade");
  18529. res.set_header("Sec-WebSocket-Accept",
  18530. detail::websocket_accept_key(
  18531. req.get_header_value("Sec-WebSocket-Key")));
  18532. });
  18533. auto port = svr.bind_to_any_port("localhost");
  18534. std::thread t([&]() { svr.listen_after_bind(); });
  18535. auto se = detail::scope_exit([&] {
  18536. svr.stop();
  18537. t.join();
  18538. });
  18539. svr.wait_until_ready();
  18540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18541. auto res = client.connect();
  18542. EXPECT_FALSE(res);
  18543. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18544. EXPECT_FALSE(client.is_open());
  18545. }
  18546. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18547. // The socket path doubles as the URL host, so it must not contain '/'.
  18548. const char *shard = getenv("GTEST_SHARD_INDEX");
  18549. const std::string sock_path =
  18550. shard ? std::string("httplib-ws-") + shard + ".sock"
  18551. : std::string("httplib-ws.sock");
  18552. std::remove(sock_path.c_str());
  18553. Server svr;
  18554. std::mutex mtx;
  18555. std::string received_host;
  18556. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18557. {
  18558. std::lock_guard<std::mutex> lock(mtx);
  18559. received_host = req.get_header_value("Host");
  18560. }
  18561. std::string msg;
  18562. while (ws.read(msg)) {
  18563. ws.send(msg);
  18564. }
  18565. });
  18566. svr.set_address_family(AF_UNIX);
  18567. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18568. auto se = detail::scope_exit([&] {
  18569. svr.stop();
  18570. t.join();
  18571. std::remove(sock_path.c_str());
  18572. });
  18573. svr.wait_until_ready();
  18574. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18575. client.set_address_family(AF_UNIX);
  18576. ASSERT_TRUE(client.connect());
  18577. ASSERT_TRUE(client.send("hello"));
  18578. std::string msg;
  18579. ASSERT_TRUE(client.read(msg));
  18580. client.close();
  18581. {
  18582. std::lock_guard<std::mutex> lock(mtx);
  18583. // There is no host:port for a Unix socket, so the same "localhost"
  18584. // placeholder the HTTP client uses is expected.
  18585. EXPECT_EQ("localhost", received_host);
  18586. }
  18587. }
  18588. // Two threads must never parse WebSocket frames from the same stream.
  18589. // close() used to read the peer's Close reply with its own frame read, so it
  18590. // raced a reader thread that was in the middle of a payload: the payload loop
  18591. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18592. // so bytes taken by close() were replaced with bytes from further along the
  18593. // stream. The message kept its length and silently changed content.
  18594. //
  18595. // The raw peer below sends a frame header plus part of the payload, waits for
  18596. // the handler to call close(), and only then sends the rest. Whichever thread
  18597. // would win the race for those bytes, the message must arrive intact, because
  18598. // close() must not touch the stream while read() owns it.
  18599. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18600. #ifndef _WIN32
  18601. signal(SIGPIPE, SIG_IGN);
  18602. #endif
  18603. const size_t payload_len = 120; // fits the 7-bit length field
  18604. const size_t prefix_len = 8;
  18605. const int attempts = 8;
  18606. std::string expected(payload_len, '\0');
  18607. for (size_t i = 0; i < payload_len; i++) {
  18608. expected[i] = static_cast<char>('a' + i % 26);
  18609. }
  18610. std::atomic<bool> peer_stalled{false};
  18611. std::atomic<bool> handler_done{false};
  18612. std::mutex received_mutex;
  18613. std::vector<std::string> received;
  18614. // Bound every wait, so a regression fails the test instead of hanging the
  18615. // suite.
  18616. auto wait_for = [](const std::atomic<bool> &flag) {
  18617. for (int i = 0; i < 500 && !flag; i++) {
  18618. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18619. }
  18620. };
  18621. Server svr;
  18622. svr.set_websocket_ping_interval(0);
  18623. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18624. std::thread reader([&]() {
  18625. std::string msg;
  18626. while (ws.read(msg)) {
  18627. std::lock_guard<std::mutex> guard(received_mutex);
  18628. received.push_back(msg);
  18629. }
  18630. });
  18631. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18632. // inside read_websocket_frame() when close() runs.
  18633. wait_for(peer_stalled);
  18634. ws.close();
  18635. reader.join();
  18636. handler_done = true;
  18637. });
  18638. auto port = svr.bind_to_any_port("127.0.0.1");
  18639. std::thread t([&]() { svr.listen_after_bind(); });
  18640. auto se = detail::scope_exit([&] {
  18641. svr.stop();
  18642. t.join();
  18643. });
  18644. svr.wait_until_ready();
  18645. auto send_bytes = [](socket_t s, const std::string &data) {
  18646. #ifdef _WIN32
  18647. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18648. #else
  18649. auto n = ::send(s, data.data(), data.size(), 0);
  18650. #endif
  18651. return n == static_cast<decltype(n)>(data.size());
  18652. };
  18653. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18654. // Every length used here fits the 7-bit length field.
  18655. auto masked_header = [](uint8_t first_byte, size_t len) {
  18656. std::string h;
  18657. h += static_cast<char>(first_byte);
  18658. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18659. h.append(4, '\0'); // mask key
  18660. return h;
  18661. };
  18662. for (int attempt = 0; attempt < attempts; attempt++) {
  18663. peer_stalled = false;
  18664. handler_done = false;
  18665. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18666. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18667. auto se_sock = detail::scope_exit([&] {
  18668. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18669. });
  18670. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18671. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18672. sockaddr_in addr{};
  18673. addr.sin_family = AF_INET;
  18674. addr.sin_port = htons(static_cast<uint16_t>(port));
  18675. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18676. ASSERT_EQ(
  18677. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18678. << "attempt " << attempt;
  18679. ASSERT_TRUE(send_bytes(sock,
  18680. "GET /ws HTTP/1.1\r\n"
  18681. "Host: 127.0.0.1\r\n"
  18682. "Upgrade: websocket\r\n"
  18683. "Connection: Upgrade\r\n"
  18684. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18685. "Sec-WebSocket-Version: 13\r\n"
  18686. "\r\n"))
  18687. << "attempt " << attempt;
  18688. std::string response;
  18689. while (response.find("\r\n\r\n") == std::string::npos) {
  18690. char buf[512];
  18691. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18692. if (n <= 0) { break; }
  18693. response.append(buf, static_cast<size_t>(n));
  18694. }
  18695. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18696. << "attempt " << attempt;
  18697. // Send the header of a Binary message but only the first prefix_len bytes
  18698. // of its payload, leaving the reader thread stalled inside the payload.
  18699. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18700. expected.substr(0, prefix_len)))
  18701. << "attempt " << attempt;
  18702. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18703. peer_stalled = true;
  18704. // Let close() send its Close frame and park in its own read before the
  18705. // rest of the payload arrives, so both threads are waiting for it.
  18706. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18707. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18708. close_frame += static_cast<char>(0x03); // status 1000
  18709. close_frame += static_cast<char>(0xE8);
  18710. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18711. << "attempt " << attempt;
  18712. // Closing the peer releases the reader thread even on the buggy path,
  18713. // where it waits for bytes another thread already consumed.
  18714. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18715. detail::close_socket(sock);
  18716. sock = INVALID_SOCKET;
  18717. wait_for(handler_done);
  18718. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18719. }
  18720. std::lock_guard<std::mutex> guard(received_mutex);
  18721. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18722. << "a message in flight when close() ran was dropped";
  18723. for (size_t i = 0; i < received.size(); i++) {
  18724. EXPECT_EQ(expected, received[i]) << "message " << i;
  18725. }
  18726. }
  18727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18728. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18729. protected:
  18730. void SetUp() override {
  18731. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18732. SERVER_PRIVATE_KEY_FILE);
  18733. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18734. std::string msg;
  18735. ws::ReadResult ret;
  18736. while ((ret = ws.read(msg))) {
  18737. if (ret == ws::Binary) {
  18738. ws.send(msg.data(), msg.size());
  18739. } else {
  18740. ws.send(msg);
  18741. }
  18742. }
  18743. });
  18744. port_ = server_->bind_to_any_port(HOST);
  18745. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18746. server_->wait_until_ready();
  18747. }
  18748. void TearDown() override {
  18749. server_->stop();
  18750. if (server_thread_.joinable()) { server_thread_.join(); }
  18751. }
  18752. std::unique_ptr<SSLServer> server_;
  18753. std::thread server_thread_;
  18754. int port_ = 0;
  18755. };
  18756. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18757. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18758. "/ws-echo");
  18759. client.enable_server_certificate_verification(false);
  18760. ASSERT_TRUE(client.connect());
  18761. ASSERT_TRUE(client.is_open());
  18762. ASSERT_TRUE(client.send("Hello WSS"));
  18763. std::string msg;
  18764. EXPECT_EQ(ws::Text, client.read(msg));
  18765. EXPECT_EQ("Hello WSS", msg);
  18766. client.close();
  18767. }
  18768. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18769. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18770. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18771. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18772. // client (without calling close() first) is the only path that runs
  18773. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18774. // bug exactly.
  18775. //
  18776. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18777. // when linked against an instrumented libssl; run under Valgrind to catch it
  18778. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18779. // suite (the freed session otherwise stalls on the close handshake) — this test
  18780. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18781. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18782. {
  18783. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18784. "/ws-echo");
  18785. client.enable_server_certificate_verification(false);
  18786. client.set_read_timeout(2, 0);
  18787. client.set_write_timeout(2, 0);
  18788. ASSERT_TRUE(client.connect());
  18789. ASSERT_TRUE(client.is_open());
  18790. ASSERT_TRUE(client.send("still open"));
  18791. // Intentionally do NOT call client.close(): leaving scope runs
  18792. // shutdown_and_close() with the WebSocket still open, which must send the
  18793. // close frame while the TLS session is still alive.
  18794. }
  18795. }
  18796. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18797. // shutdown_and_close() at the start of connect(), reproducing the same
  18798. // use-after-free within the test body rather than at scope exit. The second
  18799. // connect must succeed and echo, proving the close handshake ran over a live
  18800. // session. See the note above about memory-tool requirements.
  18801. TEST_F(WebSocketSSLIntegrationTest,
  18802. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18803. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18804. "/ws-echo");
  18805. client.enable_server_certificate_verification(false);
  18806. client.set_read_timeout(2, 0);
  18807. client.set_write_timeout(2, 0);
  18808. ASSERT_TRUE(client.connect());
  18809. ASSERT_TRUE(client.is_open());
  18810. ASSERT_TRUE(client.send("still open"));
  18811. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18812. // the still-open connection, which must not touch a freed TLS session.
  18813. ASSERT_TRUE(client.connect());
  18814. ASSERT_TRUE(client.is_open());
  18815. ASSERT_TRUE(client.send("after reconnect"));
  18816. std::string msg;
  18817. EXPECT_EQ(ws::Text, client.read(msg));
  18818. EXPECT_EQ("after reconnect", msg);
  18819. client.close();
  18820. }
  18821. #endif
  18822. #ifdef CPPHTTPLIB_SSL_ENABLED
  18823. class WebSocketSSLCATest : public ::testing::Test {
  18824. protected:
  18825. void SetUp() override {
  18826. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18827. SERVER_PRIVATE_KEY_FILE);
  18828. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18829. std::string msg;
  18830. while (ws.read(msg)) {
  18831. ws.send(msg);
  18832. }
  18833. });
  18834. port_ = server_->bind_to_any_port("127.0.0.1");
  18835. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18836. server_->wait_until_ready();
  18837. }
  18838. void TearDown() override {
  18839. server_->stop();
  18840. if (server_thread_.joinable()) { server_thread_.join(); }
  18841. }
  18842. std::string url() const {
  18843. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18844. }
  18845. std::unique_ptr<SSLServer> server_;
  18846. std::thread server_thread_;
  18847. int port_ = 0;
  18848. };
  18849. // A custom CA loaded as PEM verifies the server with full certificate
  18850. // verification enabled
  18851. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18852. ws::WebSocketClient client(url());
  18853. std::string cert;
  18854. read_file(SERVER_CERT2_FILE, cert);
  18855. client.load_ca_cert_store(cert.c_str(), cert.size());
  18856. ASSERT_TRUE(client.connect());
  18857. ASSERT_TRUE(client.send("hello"));
  18858. std::string msg;
  18859. EXPECT_EQ(ws::Text, client.read(msg));
  18860. EXPECT_EQ("hello", msg);
  18861. client.close();
  18862. }
  18863. // A custom CA that does not cover the server must fail verification (the
  18864. // custom CA is exclusive; system certs are not loaded alongside it)
  18865. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18866. ws::WebSocketClient client(url());
  18867. std::string cert;
  18868. read_file(CLIENT_CA_CERT_FILE, cert);
  18869. client.load_ca_cert_store(cert.c_str(), cert.size());
  18870. auto res = client.connect();
  18871. ASSERT_FALSE(res);
  18872. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18873. EXPECT_EQ(-1, res.status());
  18874. EXPECT_NE(0u, res.ssl_backend_error());
  18875. }
  18876. // The same CA as a file path rather than PEM in memory
  18877. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18878. ws::WebSocketClient client(url());
  18879. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18880. ASSERT_TRUE(client.connect());
  18881. ASSERT_TRUE(client.send("hello"));
  18882. std::string msg;
  18883. EXPECT_EQ(ws::Text, client.read(msg));
  18884. EXPECT_EQ("hello", msg);
  18885. client.close();
  18886. }
  18887. // ...and a CA file that does not cover the server still fails, so it is the
  18888. // path above that decides the outcome
  18889. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18890. ws::WebSocketClient client(url());
  18891. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18892. ASSERT_FALSE(client.connect());
  18893. }
  18894. // Regression test: reconnecting with a native custom CA store used to reuse
  18895. // a store handle the previous TLS context had already freed (use-after-free
  18896. // under the OpenSSL backend). The context now lives as long as the client.
  18897. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18898. ws::WebSocketClient client(url());
  18899. std::string cert;
  18900. read_file(SERVER_CERT2_FILE, cert);
  18901. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18902. ASSERT_TRUE(client.connect());
  18903. client.close();
  18904. ASSERT_TRUE(client.connect());
  18905. ASSERT_TRUE(client.send("again"));
  18906. std::string msg;
  18907. EXPECT_EQ(ws::Text, client.read(msg));
  18908. EXPECT_EQ("again", msg);
  18909. client.close();
  18910. }
  18911. // Regression test: a certificate with a trusted chain but no identity match
  18912. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18913. // verification entirely for IP hosts, so this connection succeeded there.
  18914. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18915. // chain verification while the identity check must still fail.
  18916. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18918. ASSERT_TRUE(svr.is_valid());
  18919. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18920. std::string msg;
  18921. while (ws.read(msg)) {
  18922. ws.send(msg);
  18923. }
  18924. });
  18925. auto port = svr.bind_to_any_port("127.0.0.1");
  18926. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18927. auto se = detail::scope_exit([&] {
  18928. svr.stop();
  18929. t.join();
  18930. });
  18931. svr.wait_until_ready();
  18932. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18933. "/echo");
  18934. std::string cert;
  18935. read_file(SERVER_CERT_FILE, cert);
  18936. client.load_ca_cert_store(cert.c_str(), cert.size());
  18937. ASSERT_FALSE(client.connect());
  18938. }
  18939. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18940. // SNI, so nothing binds the host name to the TLS session. These bind the
  18941. // server to "localhost" instead, the only shape that exercises the SNI and
  18942. // hostname-verification path with certificate verification left enabled.
  18943. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18944. protected:
  18945. void Start(const char *cert_file) {
  18946. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18947. SERVER_PRIVATE_KEY_FILE);
  18948. ASSERT_TRUE(server_->is_valid());
  18949. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18950. std::string msg;
  18951. while (ws.read(msg)) {
  18952. ws.send(msg);
  18953. }
  18954. });
  18955. port_ = server_->bind_to_any_port("localhost");
  18956. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18957. server_->wait_until_ready();
  18958. }
  18959. void TearDown() override {
  18960. if (server_) { server_->stop(); }
  18961. if (server_thread_.joinable()) { server_thread_.join(); }
  18962. }
  18963. std::string url() const {
  18964. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18965. }
  18966. std::unique_ptr<SSLServer> server_;
  18967. std::thread server_thread_;
  18968. int port_ = 0;
  18969. };
  18970. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18971. // out and the connection is usable
  18972. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18973. Start(SERVER_CERT2_FILE);
  18974. ws::WebSocketClient client(url());
  18975. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18976. ASSERT_TRUE(client.connect());
  18977. ASSERT_TRUE(client.send("hello"));
  18978. std::string msg;
  18979. EXPECT_EQ(ws::Text, client.read(msg));
  18980. EXPECT_EQ("hello", msg);
  18981. client.close();
  18982. }
  18983. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18984. // while the identity check must still reject "localhost"
  18985. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18986. Start(SERVER_CERT_FILE);
  18987. ws::WebSocketClient client(url());
  18988. client.set_ca_cert_path(SERVER_CERT_FILE);
  18989. auto res = client.connect();
  18990. ASSERT_FALSE(res);
  18991. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18992. EXPECT_EQ(-1, res.status());
  18993. }
  18994. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18995. // disabled: the chain is still checked, only the identity check is skipped
  18996. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18997. Start(SERVER_CERT_FILE);
  18998. ws::WebSocketClient client(url());
  18999. client.set_ca_cert_path(SERVER_CERT_FILE);
  19000. client.enable_server_hostname_verification(false);
  19001. ASSERT_TRUE(client.connect());
  19002. ASSERT_TRUE(client.send("hello"));
  19003. std::string msg;
  19004. EXPECT_EQ(ws::Text, client.read(msg));
  19005. EXPECT_EQ("hello", msg);
  19006. client.close();
  19007. }
  19008. // A CA that did not sign the server certificate fails the chain, even though
  19009. // the name would match
  19010. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19011. Start(SERVER_CERT2_FILE);
  19012. ws::WebSocketClient client(url());
  19013. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19014. ASSERT_FALSE(client.connect());
  19015. }
  19016. // With verification disabled, neither the chain nor the name is checked
  19017. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19018. Start(SERVER_CERT_FILE);
  19019. ws::WebSocketClient client(url());
  19020. client.enable_server_certificate_verification(false);
  19021. ASSERT_TRUE(client.connect());
  19022. ASSERT_TRUE(client.send("hello"));
  19023. std::string msg;
  19024. EXPECT_EQ(ws::Text, client.read(msg));
  19025. EXPECT_EQ("hello", msg);
  19026. client.close();
  19027. }
  19028. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19029. protected:
  19030. void SetUp() override {
  19031. server_ = httplib::detail::make_unique<SSLServer>(
  19032. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19033. ASSERT_TRUE(server_->is_valid());
  19034. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19035. std::string msg;
  19036. while (ws.read(msg)) {
  19037. ws.send(msg);
  19038. }
  19039. });
  19040. port_ = server_->bind_to_any_port("localhost");
  19041. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19042. server_->wait_until_ready();
  19043. }
  19044. void TearDown() override {
  19045. server_->stop();
  19046. if (server_thread_.joinable()) { server_thread_.join(); }
  19047. }
  19048. std::string url() const {
  19049. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19050. }
  19051. void ConnectWithClientCert(const std::string &client_cert_file,
  19052. const std::string &client_private_key_file,
  19053. const char *private_key_password) {
  19054. std::string cert_pem, key_pem;
  19055. read_file(client_cert_file, cert_pem);
  19056. read_file(client_private_key_file, key_pem);
  19057. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19058. key_pem.c_str(), key_pem.size(),
  19059. private_key_password};
  19060. ws::WebSocketClient client(url(), pem);
  19061. ASSERT_TRUE(client.is_valid());
  19062. client.enable_server_certificate_verification(false);
  19063. ASSERT_TRUE(client.connect());
  19064. ASSERT_TRUE(client.send("hello"));
  19065. std::string msg;
  19066. EXPECT_EQ(ws::Text, client.read(msg));
  19067. EXPECT_EQ("hello", msg);
  19068. client.close();
  19069. }
  19070. std::unique_ptr<SSLServer> server_;
  19071. std::thread server_thread_;
  19072. int port_ = 0;
  19073. };
  19074. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19075. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19076. }
  19077. // Control for the tests above: the fixture's server really does require a
  19078. // client certificate, so it is the PEM the constructor installed that decides
  19079. // the outcome.
  19080. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19081. ws::WebSocketClient client(url());
  19082. ASSERT_TRUE(client.is_valid());
  19083. client.enable_server_certificate_verification(false);
  19084. EXPECT_FALSE(client.connect());
  19085. }
  19086. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19087. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19088. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19089. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19090. }
  19091. #endif
  19092. #if !defined(_WIN32)
  19093. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19094. auto secret_dir = std::string("./symlink_test_secret");
  19095. auto served_dir = std::string("./symlink_test_served");
  19096. auto secret_file = secret_dir + "/secret.txt";
  19097. auto symlink_path = served_dir + "/escape";
  19098. // Setup: create directories and files
  19099. mkdir(secret_dir.c_str(), 0755);
  19100. mkdir(served_dir.c_str(), 0755);
  19101. {
  19102. std::ofstream ofs(secret_file);
  19103. ofs << "SECRET_DATA";
  19104. }
  19105. // Create symlink using absolute path so it resolves correctly
  19106. #ifdef PATH_MAX
  19107. char abs_secret[PATH_MAX];
  19108. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19109. #else
  19110. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19111. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19112. ASSERT_NE(nullptr, abs_secret);
  19113. #endif
  19114. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19115. auto se = detail::scope_exit([&] {
  19116. unlink(symlink_path.c_str());
  19117. unlink(secret_file.c_str());
  19118. rmdir(served_dir.c_str());
  19119. rmdir(secret_dir.c_str());
  19120. });
  19121. Server svr;
  19122. svr.set_mount_point("/", served_dir);
  19123. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19124. auto se2 = detail::scope_exit([&] {
  19125. svr.stop();
  19126. listen_thread.join();
  19127. });
  19128. svr.wait_until_ready();
  19129. Client cli("localhost", PORT);
  19130. // Symlink pointing outside base dir should be blocked
  19131. auto res = cli.Get("/escape/secret.txt");
  19132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19133. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19134. }
  19135. #endif
  19136. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19137. // A GET request with Content-Length to a static file handler must have its
  19138. // body drained before the keep-alive connection is reused. Otherwise the
  19139. // unread body bytes are interpreted as the next HTTP request.
  19140. //
  19141. // The body is sent AFTER receiving the first response (as in the original
  19142. // PoC) so that the stream_line_reader cannot buffer it together with the
  19143. // headers of the first request.
  19144. Server svr;
  19145. svr.set_mount_point("/", "./www");
  19146. std::atomic<int> smuggled_count(0);
  19147. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19148. smuggled_count++;
  19149. res.set_content("oops", "text/plain");
  19150. });
  19151. auto port = svr.bind_to_any_port("localhost");
  19152. thread t = thread([&] { svr.listen_after_bind(); });
  19153. auto se = detail::scope_exit([&] {
  19154. svr.stop();
  19155. t.join();
  19156. });
  19157. svr.wait_until_ready();
  19158. auto error = Error::Success;
  19159. auto sock = detail::create_client_socket(
  19160. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19161. /*connection_timeout_sec=*/2, 0,
  19162. /*read_timeout_sec=*/2, 0,
  19163. /*write_timeout_sec=*/2, 0, std::string(), error);
  19164. ASSERT_NE(INVALID_SOCKET, sock);
  19165. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19166. // The "smuggled" request will be sent as the body of the outer GET
  19167. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19168. "Host: localhost\r\n"
  19169. "Connection: close\r\n"
  19170. "\r\n";
  19171. // Step 1: Send only the outer request headers (no body yet)
  19172. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19173. "Host: localhost\r\n"
  19174. "Content-Length: " +
  19175. std::to_string(smuggled.size()) +
  19176. "\r\n"
  19177. "\r\n";
  19178. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19179. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19180. // Step 2: Read the first response (server serves file without reading body)
  19181. std::string first_response;
  19182. char buf[4096];
  19183. for (;;) {
  19184. auto n = recv(sock, buf, sizeof(buf), 0);
  19185. if (n <= 0) break;
  19186. first_response.append(buf, static_cast<size_t>(n));
  19187. // Stop once we have a complete response (headers + body)
  19188. auto hdr_end = first_response.find("\r\n\r\n");
  19189. if (hdr_end != std::string::npos) {
  19190. // Check for Content-Length to know when the body is complete
  19191. auto cl_pos = first_response.find("Content-Length:");
  19192. if (cl_pos != std::string::npos) {
  19193. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19194. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19195. auto cl = std::stoul(
  19196. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19197. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19198. } else {
  19199. break; // No Content-Length, assume headers-only response
  19200. }
  19201. }
  19202. }
  19203. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19204. // Step 3: Now send the body, which looks like a new HTTP request.
  19205. // On a vulnerable server the keep-alive loop reads this as a second request.
  19206. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19207. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19208. // Step 4: Try to read a second response (should NOT exist after fix)
  19209. std::string second_response;
  19210. for (;;) {
  19211. auto n = recv(sock, buf, sizeof(buf), 0);
  19212. if (n <= 0) break;
  19213. second_response.append(buf, static_cast<size_t>(n));
  19214. }
  19215. // The smuggled request must NOT have been processed
  19216. EXPECT_EQ(0, smuggled_count.load());
  19217. }
  19218. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19219. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19220. // must be rejected with 400 Bad Request.
  19221. Server svr;
  19222. svr.Post("/test", [&](const Request &, Response &res) {
  19223. res.set_content("ok", "text/plain");
  19224. });
  19225. thread t = thread([&] { svr.listen(HOST, PORT); });
  19226. auto se = detail::scope_exit([&] {
  19227. svr.stop();
  19228. t.join();
  19229. ASSERT_FALSE(svr.is_running());
  19230. });
  19231. svr.wait_until_ready();
  19232. // Exact "chunked"
  19233. {
  19234. auto req = "POST /test HTTP/1.1\r\n"
  19235. "Host: localhost\r\n"
  19236. "Content-Length: 5\r\n"
  19237. "Transfer-Encoding: chunked\r\n"
  19238. "Connection: close\r\n"
  19239. "\r\n"
  19240. "hello";
  19241. std::string response;
  19242. ASSERT_TRUE(send_request(1, req, &response));
  19243. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19244. response.substr(0, response.find("\r\n")));
  19245. }
  19246. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19247. {
  19248. auto req = "POST /test HTTP/1.1\r\n"
  19249. "Host: localhost\r\n"
  19250. "Content-Length: 5\r\n"
  19251. "Transfer-Encoding: gzip, chunked\r\n"
  19252. "Connection: close\r\n"
  19253. "\r\n"
  19254. "hello";
  19255. std::string response;
  19256. ASSERT_TRUE(send_request(1, req, &response));
  19257. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19258. response.substr(0, response.find("\r\n")));
  19259. }
  19260. }
  19261. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19262. Server svr;
  19263. svr.Post("/test", [&](const Request &, Response &res) {
  19264. res.set_content("ok", "text/plain");
  19265. });
  19266. thread t = thread([&] { svr.listen(HOST, PORT); });
  19267. auto se = detail::scope_exit([&] {
  19268. svr.stop();
  19269. t.join();
  19270. ASSERT_FALSE(svr.is_running());
  19271. });
  19272. svr.wait_until_ready();
  19273. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19274. // length cannot be determined, so the server must answer 400 and close
  19275. // rather than treat the request as bodyless and leave the body in the
  19276. // socket for the next request to pick up.
  19277. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19278. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19279. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19280. std::string response;
  19281. ASSERT_TRUE(send_request(1, req, &response));
  19282. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19283. response.substr(0, response.find("\r\n")))
  19284. << transfer_encoding;
  19285. }
  19286. // RFC 9110 5.3: the codings may also be split across several
  19287. // Transfer-Encoding lines, which combine in the order they were received.
  19288. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19289. // just like the single-line "chunked, gzip" above.
  19290. {
  19291. auto req = "POST /test HTTP/1.1\r\n"
  19292. "Host: localhost\r\n"
  19293. "Transfer-Encoding: chunked\r\n"
  19294. "Transfer-Encoding: gzip\r\n"
  19295. "\r\n"
  19296. "0\r\n\r\n";
  19297. std::string response;
  19298. ASSERT_TRUE(send_request(1, req, &response));
  19299. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19300. response.substr(0, response.find("\r\n")));
  19301. }
  19302. // A sequence ending in chunked stays valid.
  19303. auto req = "POST /test HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "Transfer-Encoding: gzip, chunked\r\n"
  19306. "Connection: close\r\n"
  19307. "\r\n"
  19308. "0\r\n\r\n";
  19309. std::string response;
  19310. ASSERT_TRUE(send_request(1, req, &response));
  19311. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19312. // ...including when it is spread over several lines.
  19313. auto split_req = "POST /test HTTP/1.1\r\n"
  19314. "Host: localhost\r\n"
  19315. "Transfer-Encoding: gzip\r\n"
  19316. "Transfer-Encoding: chunked\r\n"
  19317. "Connection: close\r\n"
  19318. "\r\n"
  19319. "0\r\n\r\n";
  19320. std::string split_response;
  19321. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19322. EXPECT_EQ("HTTP/1.1 200 OK",
  19323. split_response.substr(0, split_response.find("\r\n")));
  19324. }
  19325. // Regression for issue #2450: a DELETE without Content-Length on a
  19326. // keep-alive connection must not let the post-response drain consume the
  19327. // next request's bytes.
  19328. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19329. Server svr;
  19330. std::atomic<int> delete_count(0);
  19331. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19332. delete_count++;
  19333. res.status = StatusCode::NoContent_204;
  19334. });
  19335. auto port = svr.bind_to_any_port(HOST);
  19336. thread t = thread([&] { svr.listen_after_bind(); });
  19337. auto se = detail::scope_exit([&] {
  19338. svr.stop();
  19339. t.join();
  19340. });
  19341. svr.wait_until_ready();
  19342. auto error = Error::Success;
  19343. auto sock = detail::create_client_socket(
  19344. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19345. /*connection_timeout_sec=*/2, 0,
  19346. /*read_timeout_sec=*/2, 0,
  19347. /*write_timeout_sec=*/2, 0, std::string(), error);
  19348. ASSERT_NE(INVALID_SOCKET, sock);
  19349. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19350. auto send_request_and_read_response = [&](const std::string &req,
  19351. std::string &out) -> bool {
  19352. auto sent = send(sock, req.data(), req.size(), 0);
  19353. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19354. char buf[4096];
  19355. for (;;) {
  19356. auto n = recv(sock, buf, sizeof(buf), 0);
  19357. if (n <= 0) { return !out.empty(); }
  19358. out.append(buf, static_cast<size_t>(n));
  19359. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19360. }
  19361. };
  19362. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19363. "Host: localhost\r\n"
  19364. "\r\n";
  19365. std::string resp1;
  19366. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19367. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19368. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19369. "Host: localhost\r\n"
  19370. "Connection: close\r\n"
  19371. "\r\n";
  19372. std::string resp2;
  19373. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19374. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19375. EXPECT_EQ(2, delete_count.load());
  19376. }
  19377. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19378. Server svr;
  19379. svr.Post("/ingest", [&](const Request &, Response &res,
  19380. const ContentReader &content_reader) {
  19381. auto consumed = content_reader([](const char *, size_t) { return false; });
  19382. EXPECT_FALSE(consumed);
  19383. res.status = StatusCode::Conflict_409;
  19384. res.set_header("Connection", "close");
  19385. });
  19386. auto port = svr.bind_to_any_port(HOST);
  19387. thread t = thread([&] { svr.listen_after_bind(); });
  19388. auto se = detail::scope_exit([&] {
  19389. svr.stop();
  19390. t.join();
  19391. });
  19392. svr.wait_until_ready();
  19393. auto error = Error::Success;
  19394. auto sock = detail::create_client_socket(
  19395. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19396. /*connection_timeout_sec=*/2, 0,
  19397. /*read_timeout_sec=*/1, 0,
  19398. /*write_timeout_sec=*/2, 0, std::string(), error);
  19399. ASSERT_NE(INVALID_SOCKET, sock);
  19400. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19401. std::string request = "POST /ingest HTTP/1.1\r\n"
  19402. "Host: localhost\r\n"
  19403. "Transfer-Encoding: chunked\r\n"
  19404. "\r\n"
  19405. "4\r\n"
  19406. "data\r\n";
  19407. auto sent = send(sock, request.data(), request.size(), 0);
  19408. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19409. std::string response;
  19410. ssize_t received = 0;
  19411. do {
  19412. char buf[4096];
  19413. received = recv(sock, buf, sizeof(buf), 0);
  19414. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19415. } while (received > 0);
  19416. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19417. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19418. EXPECT_EQ(0, received);
  19419. }
  19420. namespace no_proxy_test {
  19421. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19422. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19423. // calling listen().
  19424. class ScopedServer {
  19425. public:
  19426. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19427. ~ScopedServer() {
  19428. svr_.stop();
  19429. if (th_.joinable()) { th_.join(); }
  19430. }
  19431. Server &svr() { return svr_; }
  19432. int port() const { return port_; }
  19433. void listen() {
  19434. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19435. svr_.wait_until_ready();
  19436. }
  19437. private:
  19438. Server svr_;
  19439. std::thread th_;
  19440. int port_ = 0;
  19441. };
  19442. class ProxyAndTargetServers {
  19443. public:
  19444. ProxyAndTargetServers() {
  19445. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19446. proxy_hits_++;
  19447. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19448. res.set_content("via-proxy", "text/plain");
  19449. });
  19450. target_.Get(".*", [this](const Request &req, Response &res) {
  19451. target_hits_++;
  19452. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19453. res.set_content("direct", "text/plain");
  19454. });
  19455. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19456. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19457. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19458. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19459. proxy_mock_.wait_until_ready();
  19460. target_.wait_until_ready();
  19461. }
  19462. ~ProxyAndTargetServers() {
  19463. proxy_mock_.stop();
  19464. target_.stop();
  19465. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19466. if (target_thread_.joinable()) { target_thread_.join(); }
  19467. }
  19468. Server &proxy_mock() { return proxy_mock_; }
  19469. Server &target() { return target_; }
  19470. int proxy_port() const { return proxy_port_; }
  19471. int target_port() const { return target_port_; }
  19472. int proxy_hits() const { return proxy_hits_.load(); }
  19473. int target_hits() const { return target_hits_.load(); }
  19474. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19475. void reset_counters() {
  19476. proxy_hits_ = 0;
  19477. target_hits_ = 0;
  19478. last_had_proxy_authz_ = false;
  19479. }
  19480. private:
  19481. Server proxy_mock_;
  19482. Server target_;
  19483. std::thread proxy_thread_;
  19484. std::thread target_thread_;
  19485. int proxy_port_ = 0;
  19486. int target_port_ = 0;
  19487. std::atomic<int> proxy_hits_{0};
  19488. std::atomic<int> target_hits_{0};
  19489. std::atomic<bool> last_had_proxy_authz_{false};
  19490. };
  19491. inline std::unique_ptr<Client> make_client(const std::string &host,
  19492. ProxyAndTargetServers &s) {
  19493. auto cli = detail::make_unique<Client>(host, s.target_port());
  19494. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19495. cli->set_proxy("127.0.0.1", s.proxy_port());
  19496. return cli;
  19497. }
  19498. } // namespace no_proxy_test
  19499. using no_proxy_test::make_client;
  19500. using no_proxy_test::ProxyAndTargetServers;
  19501. TEST(NoProxyTest, ExactHostnameBypasses) {
  19502. ProxyAndTargetServers s;
  19503. auto cli = make_client("example.com", s);
  19504. cli->set_no_proxy({"example.com"});
  19505. auto res = cli->Get("/");
  19506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19507. EXPECT_EQ(0, s.proxy_hits());
  19508. EXPECT_EQ(1, s.target_hits());
  19509. }
  19510. TEST(NoProxyTest, SubdomainBypasses) {
  19511. ProxyAndTargetServers s;
  19512. auto cli = make_client("foo.example.com", s);
  19513. cli->set_no_proxy({"example.com"});
  19514. auto res = cli->Get("/");
  19515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19516. EXPECT_EQ(0, s.proxy_hits());
  19517. EXPECT_EQ(1, s.target_hits());
  19518. }
  19519. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19520. // Regression guard: "evilexample.com" must not be considered a subdomain
  19521. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19522. // check would let traffic bypass the proxy and leak credentials direct
  19523. // to the attacker host.
  19524. ProxyAndTargetServers s;
  19525. auto cli = make_client("evilexample.com", s);
  19526. cli->set_no_proxy({"example.com"});
  19527. auto res = cli->Get("/");
  19528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19529. EXPECT_GE(s.proxy_hits(), 1);
  19530. EXPECT_EQ(0, s.target_hits());
  19531. }
  19532. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19533. ProxyAndTargetServers s;
  19534. auto cli = make_client("example.com.evil.com", s);
  19535. cli->set_no_proxy({"example.com"});
  19536. auto res = cli->Get("/");
  19537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19538. EXPECT_GE(s.proxy_hits(), 1);
  19539. EXPECT_EQ(0, s.target_hits());
  19540. }
  19541. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19542. ProxyAndTargetServers s;
  19543. auto cli = make_client("example.com", s);
  19544. cli->set_no_proxy({".example.com"});
  19545. auto res = cli->Get("/");
  19546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19547. EXPECT_EQ(0, s.proxy_hits());
  19548. EXPECT_EQ(1, s.target_hits());
  19549. }
  19550. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19551. ProxyAndTargetServers s;
  19552. auto cli = make_client("Example.COM", s);
  19553. cli->set_no_proxy({"EXAMPLE.com"});
  19554. auto res = cli->Get("/");
  19555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19556. EXPECT_EQ(0, s.proxy_hits());
  19557. EXPECT_EQ(1, s.target_hits());
  19558. }
  19559. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19560. ProxyAndTargetServers s;
  19561. auto cli = make_client("example.com.", s);
  19562. cli->set_no_proxy({"example.com"});
  19563. auto res = cli->Get("/");
  19564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19565. EXPECT_EQ(0, s.proxy_hits());
  19566. EXPECT_EQ(1, s.target_hits());
  19567. }
  19568. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19569. // Trailing dots must be normalized on BOTH sides — host and entry.
  19570. // An implementation that only strips the host-side trailing dot would
  19571. // fail to match host "example.com" against entry "example.com." because
  19572. // a literal substring search would compare 11 chars against 12.
  19573. ProxyAndTargetServers s;
  19574. auto cli = make_client("example.com", s);
  19575. cli->set_no_proxy({"example.com."});
  19576. auto res = cli->Get("/");
  19577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19578. EXPECT_EQ(0, s.proxy_hits());
  19579. EXPECT_EQ(1, s.target_hits());
  19580. }
  19581. TEST(NoProxyTest, WildcardBypassesEverything) {
  19582. ProxyAndTargetServers s;
  19583. auto cli = make_client("anything.invalid.test", s);
  19584. cli->set_no_proxy({"*"});
  19585. auto res = cli->Get("/");
  19586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19587. EXPECT_EQ(0, s.proxy_hits());
  19588. EXPECT_EQ(1, s.target_hits());
  19589. }
  19590. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19591. ProxyAndTargetServers s;
  19592. Client cli("127.0.0.1", s.target_port());
  19593. cli.set_proxy("127.0.0.1", s.proxy_port());
  19594. cli.set_no_proxy({"127.0.0.1"});
  19595. auto res = cli.Get("/");
  19596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19597. EXPECT_EQ(0, s.proxy_hits());
  19598. EXPECT_EQ(1, s.target_hits());
  19599. }
  19600. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19601. ProxyAndTargetServers s;
  19602. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19603. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19604. cli.set_proxy("127.0.0.1", s.proxy_port());
  19605. cli.set_no_proxy({"::1"});
  19606. auto res = cli.Get("/");
  19607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19608. EXPECT_EQ(0, s.proxy_hits());
  19609. EXPECT_EQ(1, s.target_hits());
  19610. }
  19611. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19612. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19613. // must still be recognized as IPv6 for CIDR matching. Implementations
  19614. // that detect IPv6 only when the host begins with '[' would parse the
  19615. // host as a hostname and miss the match.
  19616. ProxyAndTargetServers s;
  19617. Client cli("fe80::1", s.target_port());
  19618. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19619. cli.set_proxy("127.0.0.1", s.proxy_port());
  19620. cli.set_no_proxy({"fe80::/10"});
  19621. auto res = cli.Get("/");
  19622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19623. EXPECT_EQ(0, s.proxy_hits());
  19624. EXPECT_EQ(1, s.target_hits());
  19625. }
  19626. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19627. ProxyAndTargetServers s;
  19628. Client cli("::1", s.target_port());
  19629. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19630. cli.set_proxy("127.0.0.1", s.proxy_port());
  19631. cli.set_no_proxy({"[::1]"});
  19632. auto res = cli.Get("/");
  19633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19634. EXPECT_EQ(0, s.proxy_hits());
  19635. EXPECT_EQ(1, s.target_hits());
  19636. }
  19637. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19638. ProxyAndTargetServers s;
  19639. Client cli("fe80::1", s.target_port());
  19640. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19641. cli.set_proxy("127.0.0.1", s.proxy_port());
  19642. cli.set_no_proxy({"[fe80::]/10"});
  19643. auto res = cli.Get("/");
  19644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19645. EXPECT_EQ(0, s.proxy_hits());
  19646. EXPECT_EQ(1, s.target_hits());
  19647. }
  19648. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19649. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19650. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19651. // tricks via address-family conversion.
  19652. ProxyAndTargetServers s;
  19653. Client cli("::ffff:127.0.0.1", s.target_port());
  19654. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19655. cli.set_proxy("127.0.0.1", s.proxy_port());
  19656. cli.set_no_proxy({"127.0.0.1"});
  19657. auto res = cli.Get("/");
  19658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19659. EXPECT_GE(s.proxy_hits(), 1);
  19660. EXPECT_EQ(0, s.target_hits());
  19661. }
  19662. TEST(NoProxyTest, IPv4CidrMatch) {
  19663. ProxyAndTargetServers s;
  19664. Client cli("127.0.0.1", s.target_port());
  19665. cli.set_proxy("127.0.0.1", s.proxy_port());
  19666. cli.set_no_proxy({"127.0.0.0/8"});
  19667. auto res = cli.Get("/");
  19668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19669. EXPECT_EQ(0, s.proxy_hits());
  19670. EXPECT_EQ(1, s.target_hits());
  19671. }
  19672. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19673. ProxyAndTargetServers s;
  19674. Client cli("127.0.0.1", s.target_port());
  19675. cli.set_proxy("127.0.0.1", s.proxy_port());
  19676. cli.set_no_proxy({"10.0.0.0/8"});
  19677. auto res = cli.Get("/");
  19678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19679. EXPECT_GE(s.proxy_hits(), 1);
  19680. EXPECT_EQ(0, s.target_hits());
  19681. }
  19682. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19683. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19684. // IPv4 target matches.
  19685. ProxyAndTargetServers s;
  19686. Client cli("127.0.0.1", s.target_port());
  19687. cli.set_proxy("127.0.0.1", s.proxy_port());
  19688. cli.set_no_proxy({"0.0.0.0/0"});
  19689. auto res = cli.Get("/");
  19690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19691. EXPECT_EQ(0, s.proxy_hits());
  19692. EXPECT_EQ(1, s.target_hits());
  19693. }
  19694. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19695. ProxyAndTargetServers s;
  19696. Client cli("127.0.0.1", s.target_port());
  19697. cli.set_proxy("127.0.0.1", s.proxy_port());
  19698. cli.set_no_proxy({"127.0.0.1"});
  19699. auto res = cli.Get("/");
  19700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19701. EXPECT_EQ(0, s.proxy_hits());
  19702. EXPECT_EQ(1, s.target_hits());
  19703. }
  19704. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19705. ProxyAndTargetServers s;
  19706. Client cli("127.0.0.1", s.target_port());
  19707. cli.set_proxy("127.0.0.1", s.proxy_port());
  19708. cli.set_no_proxy({"127.0.0.0/33"});
  19709. auto res = cli.Get("/");
  19710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19711. EXPECT_GE(s.proxy_hits(), 1);
  19712. EXPECT_EQ(0, s.target_hits());
  19713. }
  19714. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19715. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19716. ProxyAndTargetServers s;
  19717. Client cli("127.0.0.1", s.target_port());
  19718. cli.set_proxy("127.0.0.1", s.proxy_port());
  19719. cli.set_no_proxy({"127.0.0.1/"});
  19720. auto res = cli.Get("/");
  19721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19722. EXPECT_GE(s.proxy_hits(), 1);
  19723. EXPECT_EQ(0, s.target_hits());
  19724. }
  19725. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19726. ProxyAndTargetServers s;
  19727. auto cli = make_client("internal.corp", s);
  19728. cli->set_proxy_basic_auth("u", "p");
  19729. cli->set_no_proxy({"internal.corp"});
  19730. auto res = cli->Get("/");
  19731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19732. EXPECT_EQ(1, s.target_hits());
  19733. EXPECT_EQ(0, s.proxy_hits());
  19734. EXPECT_FALSE(s.last_had_proxy_authz())
  19735. << "Proxy-Authorization must not be sent direct to the target";
  19736. }
  19737. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19738. ProxyAndTargetServers s;
  19739. auto cli = make_client("public.example", s);
  19740. cli->set_proxy_basic_auth("u", "p");
  19741. cli->set_no_proxy({"internal.corp"}); // does not match
  19742. auto res = cli->Get("/");
  19743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19744. EXPECT_GE(s.proxy_hits(), 1);
  19745. EXPECT_TRUE(s.last_had_proxy_authz());
  19746. }
  19747. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19748. ProxyAndTargetServers s;
  19749. auto cli = make_client("anything.test", s);
  19750. auto res = cli->Get("/");
  19751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19752. EXPECT_GE(s.proxy_hits(), 1);
  19753. EXPECT_EQ(0, s.target_hits());
  19754. }
  19755. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19756. ProxyAndTargetServers s;
  19757. auto cli = make_client("example.com", s);
  19758. cli->set_no_proxy({"example.com:8080"});
  19759. auto res = cli->Get("/");
  19760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19761. EXPECT_GE(s.proxy_hits(), 1);
  19762. EXPECT_EQ(0, s.target_hits());
  19763. }
  19764. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19765. ProxyAndTargetServers s;
  19766. auto cli = make_client("anything.test", s);
  19767. cli->set_no_proxy({"", " ", "\t"});
  19768. auto res = cli->Get("/");
  19769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19770. EXPECT_GE(s.proxy_hits(), 1);
  19771. EXPECT_EQ(0, s.target_hits());
  19772. }
  19773. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19774. // An entry with leading/trailing whitespace must still match — env-style
  19775. // values are commonly pasted with stray spaces and an implementation
  19776. // that feeds the raw token directly to inet_pton would fail to match
  19777. // valid CIDRs because of the spaces.
  19778. ProxyAndTargetServers s;
  19779. Client cli("127.0.0.1", s.target_port());
  19780. cli.set_proxy("127.0.0.1", s.proxy_port());
  19781. cli.set_no_proxy({" 127.0.0.0/8 "});
  19782. auto res = cli.Get("/");
  19783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19784. EXPECT_EQ(0, s.proxy_hits());
  19785. EXPECT_EQ(1, s.target_hits());
  19786. }
  19787. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19788. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19789. // go direct and must NOT carry Proxy-Authorization.
  19790. std::atomic<int> proxy_hits{0};
  19791. std::atomic<int> target_hits{0};
  19792. std::atomic<bool> target_saw_authz{false};
  19793. no_proxy_test::ScopedServer proxy_mock, target;
  19794. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19795. proxy_hits++;
  19796. res.status = 302;
  19797. res.set_header("Location", "http://127.0.0.1:" +
  19798. std::to_string(target.port()) + "/landed");
  19799. });
  19800. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19801. target_hits++;
  19802. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19803. res.set_content("direct", "text/plain");
  19804. });
  19805. proxy_mock.listen();
  19806. target.listen();
  19807. Client cli("public.example", target.port());
  19808. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19809. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19810. cli.set_proxy_basic_auth("u", "p");
  19811. cli.set_no_proxy({"127.0.0.1"});
  19812. cli.set_follow_location(true);
  19813. auto res = cli.Get("/redir");
  19814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19815. EXPECT_GE(proxy_hits.load(), 1);
  19816. EXPECT_GE(target_hits.load(), 1);
  19817. EXPECT_FALSE(target_saw_authz.load());
  19818. }
  19819. #ifdef CPPHTTPLIB_SSL_ENABLED
  19820. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19821. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19822. // proxy creds would be sent to the (possibly hostile) origin.
  19823. std::atomic<int> target_hits{0};
  19824. std::atomic<bool> target_saw_proxy_authz{false};
  19825. no_proxy_test::ScopedServer target;
  19826. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19827. target_hits++;
  19828. if (req.has_header("Proxy-Authorization")) {
  19829. target_saw_proxy_authz = true;
  19830. }
  19831. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19832. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19833. "nonce=\"abc\", algorithm=MD5");
  19834. });
  19835. target.listen();
  19836. // The proxy address is set to the target's port: the bypass MUST kick in;
  19837. // if it doesn't, the test still routes "via proxy" to the same server and
  19838. // the Proxy-Authorization assertion below catches the leak.
  19839. Client cli("evil.example", target.port());
  19840. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19841. cli.set_proxy("127.0.0.1", target.port());
  19842. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19843. cli.set_no_proxy({"evil.example"});
  19844. auto res = cli.Get("/x");
  19845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19846. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19847. EXPECT_EQ(1, target_hits.load());
  19848. EXPECT_FALSE(target_saw_proxy_authz.load());
  19849. }
  19850. #endif
  19851. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19852. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19853. std::atomic<int> proxy_hits{0};
  19854. std::atomic<int> bypass_hits{0};
  19855. std::atomic<bool> proxy_saw_c_url{false};
  19856. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19857. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19858. proxy_hits++;
  19859. if (req.path.find("/start") != std::string::npos) {
  19860. res.status = 302;
  19861. res.set_header("Location", "http://127.0.0.1:" +
  19862. std::to_string(bypass_server.port()) +
  19863. "/middle");
  19864. return;
  19865. }
  19866. if (req.path.find("/end") != std::string::npos) {
  19867. proxy_saw_c_url = true;
  19868. res.set_content("c-via-proxy", "text/plain");
  19869. return;
  19870. }
  19871. res.set_content("unexpected", "text/plain");
  19872. });
  19873. // public.example's "advertised" port is arbitrary (the request never lands
  19874. // there — it goes through the proxy), but use a dynamic value to stay
  19875. // friendly with sharded parallel runs.
  19876. int public_port = bypass_server.port();
  19877. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19878. bypass_hits++;
  19879. res.status = 302;
  19880. res.set_header("Location", "http://public.example:" +
  19881. std::to_string(public_port) + "/end");
  19882. });
  19883. proxy_mock.listen();
  19884. bypass_server.listen();
  19885. Client cli("public.example", public_port);
  19886. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19887. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19888. cli.set_no_proxy({"127.0.0.1"});
  19889. cli.set_follow_location(true);
  19890. auto res = cli.Get("/start");
  19891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19892. EXPECT_EQ(StatusCode::OK_200, res->status);
  19893. EXPECT_EQ("c-via-proxy", res->body);
  19894. EXPECT_GE(proxy_hits.load(), 2);
  19895. EXPECT_GE(bypass_hits.load(), 1);
  19896. EXPECT_TRUE(proxy_saw_c_url.load());
  19897. }
  19898. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19899. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19900. // request reconnects to the correct endpoint.
  19901. std::atomic<int> proxy_hits{0};
  19902. std::atomic<int> target_hits{0};
  19903. no_proxy_test::ScopedServer proxy_mock, target;
  19904. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19905. proxy_hits++;
  19906. res.set_content("via-proxy", "text/plain");
  19907. });
  19908. target.svr().Get(".*", [&](const Request &, Response &res) {
  19909. target_hits++;
  19910. res.set_content("direct", "text/plain");
  19911. });
  19912. proxy_mock.listen();
  19913. target.listen();
  19914. Client cli("public.example", target.port());
  19915. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19916. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19917. cli.set_keep_alive(true);
  19918. auto res1 = cli.Get("/a");
  19919. ASSERT_TRUE(res1);
  19920. EXPECT_EQ("via-proxy", res1->body);
  19921. EXPECT_EQ(1, proxy_hits.load());
  19922. EXPECT_EQ(0, target_hits.load());
  19923. cli.set_no_proxy({"public.example"});
  19924. auto res2 = cli.Get("/b");
  19925. ASSERT_TRUE(res2);
  19926. EXPECT_EQ("direct", res2->body);
  19927. EXPECT_EQ(1, proxy_hits.load());
  19928. EXPECT_EQ(1, target_hits.load());
  19929. }
  19930. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19931. namespace proxy_tunnel_test {
  19932. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19933. class ScopedSSLServer {
  19934. public:
  19935. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19936. port_ = svr_.bind_to_any_port("127.0.0.1");
  19937. }
  19938. ~ScopedSSLServer() {
  19939. svr_.stop();
  19940. if (th_.joinable()) { th_.join(); }
  19941. }
  19942. SSLServer &svr() { return svr_; }
  19943. int port() const { return port_; }
  19944. void listen() {
  19945. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19946. svr_.wait_until_ready();
  19947. }
  19948. private:
  19949. SSLServer svr_;
  19950. std::thread th_;
  19951. int port_ = 0;
  19952. };
  19953. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19954. class ScopedConnectProxy {
  19955. public:
  19956. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19957. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19958. if (listen_fd_ < 0) { return; }
  19959. int yes = 1;
  19960. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19961. sockaddr_in a{};
  19962. a.sin_family = AF_INET;
  19963. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19964. a.sin_port = 0;
  19965. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19966. return;
  19967. }
  19968. socklen_t alen = sizeof(a);
  19969. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19970. 0) {
  19971. return;
  19972. }
  19973. port_ = ntohs(a.sin_port);
  19974. if (::listen(listen_fd_, 1) != 0) { return; }
  19975. th_ = std::thread([this] { run(); });
  19976. }
  19977. ~ScopedConnectProxy() {
  19978. stop_ = true;
  19979. if (listen_fd_ >= 0) {
  19980. ::shutdown(listen_fd_, SHUT_RDWR);
  19981. ::close(listen_fd_);
  19982. }
  19983. if (th_.joinable()) { th_.join(); }
  19984. }
  19985. int port() const { return port_; }
  19986. int connect_hits() const { return connect_hits_.load(); }
  19987. private:
  19988. void run() {
  19989. while (!stop_.load()) {
  19990. fd_set rfds;
  19991. FD_ZERO(&rfds);
  19992. FD_SET(listen_fd_, &rfds);
  19993. timeval tv{0, 100 * 1000};
  19994. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19995. if (sel <= 0) { continue; }
  19996. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19997. if (client_fd < 0) { continue; }
  19998. std::string req;
  19999. char buf[2048];
  20000. while (req.find("\r\n\r\n") == std::string::npos) {
  20001. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20002. if (n <= 0) { break; }
  20003. req.append(buf, static_cast<size_t>(n));
  20004. }
  20005. if (req.compare(0, 7, "CONNECT") != 0) {
  20006. ::close(client_fd);
  20007. continue;
  20008. }
  20009. connect_hits_++;
  20010. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20011. ::send(client_fd, ok, std::strlen(ok), 0);
  20012. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20013. sockaddr_in o{};
  20014. o.sin_family = AF_INET;
  20015. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20016. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20017. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20018. 0) {
  20019. ::close(client_fd);
  20020. ::close(origin_fd);
  20021. continue;
  20022. }
  20023. auto forward = [](int from, int to) {
  20024. char b[8192];
  20025. for (;;) {
  20026. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20027. if (n <= 0) { break; }
  20028. ssize_t off = 0;
  20029. while (off < n) {
  20030. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20031. if (s <= 0) {
  20032. off = n;
  20033. break;
  20034. }
  20035. off += s;
  20036. }
  20037. }
  20038. ::shutdown(to, SHUT_WR);
  20039. };
  20040. std::thread t1([&] { forward(client_fd, origin_fd); });
  20041. std::thread t2([&] { forward(origin_fd, client_fd); });
  20042. t1.join();
  20043. t2.join();
  20044. ::close(client_fd);
  20045. ::close(origin_fd);
  20046. }
  20047. }
  20048. int forward_port_ = -1;
  20049. int listen_fd_ = -1;
  20050. int port_ = 0;
  20051. std::thread th_;
  20052. std::atomic<bool> stop_{false};
  20053. std::atomic<int> connect_hits_{0};
  20054. };
  20055. } // namespace proxy_tunnel_test
  20056. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20057. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20058. // retry; otherwise proxy creds would be sent to the origin.
  20059. std::atomic<int> origin_hits{0};
  20060. std::atomic<bool> origin_saw_proxy_authz{false};
  20061. proxy_tunnel_test::ScopedSSLServer origin;
  20062. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20063. origin_hits++;
  20064. if (req.has_header("Proxy-Authorization")) {
  20065. origin_saw_proxy_authz = true;
  20066. }
  20067. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20068. res.set_header("Proxy-Authenticate",
  20069. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20070. "algorithm=MD5");
  20071. });
  20072. origin.listen();
  20073. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20074. ASSERT_NE(0, proxy.port());
  20075. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20076. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20077. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20078. // and answer with its own status, making this test flaky.
  20079. SSLClient cli("127.0.0.1", origin.port());
  20080. cli.enable_server_certificate_verification(false);
  20081. cli.set_proxy("127.0.0.1", proxy.port());
  20082. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20083. auto res = cli.Get("/x");
  20084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20085. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20086. EXPECT_EQ(1, origin_hits.load());
  20087. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20088. EXPECT_EQ(1, proxy.connect_hits());
  20089. }
  20090. #endif