test.cc 809 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. EXPECT_TRUE(ranges.empty());
  1701. }
  1702. }
  1703. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1704. Request req;
  1705. req.set_header("Accept-Encoding", "gzip");
  1706. Response res;
  1707. res.set_header("Content-Type", "text/plain");
  1708. auto ret = detail::encoding_type(req, res);
  1709. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1710. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1711. #else
  1712. EXPECT_TRUE(ret == detail::EncodingType::None);
  1713. #endif
  1714. }
  1715. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1716. Request req;
  1717. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1718. Response res;
  1719. res.set_header("Content-Type", "text/plain");
  1720. auto ret = detail::encoding_type(req, res);
  1721. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1722. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1723. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1726. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1727. #else
  1728. EXPECT_TRUE(ret == detail::EncodingType::None);
  1729. #endif
  1730. }
  1731. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1732. Request req;
  1733. req.set_header("Accept-Encoding",
  1734. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1749. // All supported encodings rejected with q=0 should return None
  1750. Request req;
  1751. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. EXPECT_TRUE(ret == detail::EncodingType::None);
  1756. }
  1757. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1758. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1759. Request req;
  1760. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1761. Response res;
  1762. res.set_header("Content-Type", "text/plain");
  1763. auto ret = detail::encoding_type(req, res);
  1764. EXPECT_TRUE(ret == detail::EncodingType::None);
  1765. }
  1766. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1767. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1776. // RFC 7231: Accept-Encoding values are case-insensitive
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1783. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1784. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1785. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1786. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1793. // q value should determine priority, not hardcoded order
  1794. Request req;
  1795. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1796. Response res;
  1797. res.set_header("Content-Type", "text/plain");
  1798. auto ret = detail::encoding_type(req, res);
  1799. // gzip has highest q=1.0, so it should be selected even though
  1800. // br and zstd are also supported
  1801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1803. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1804. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1805. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1806. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1807. #else
  1808. EXPECT_TRUE(ret == detail::EncodingType::None);
  1809. #endif
  1810. }
  1811. TEST(BufferStreamTest, read) {
  1812. detail::BufferStream strm1;
  1813. Stream &strm = strm1;
  1814. EXPECT_EQ(5, strm.write("hello"));
  1815. char buf[512];
  1816. EXPECT_EQ(2, strm.read(buf, 2));
  1817. EXPECT_EQ('h', buf[0]);
  1818. EXPECT_EQ('e', buf[1]);
  1819. EXPECT_EQ(2, strm.read(buf, 2));
  1820. EXPECT_EQ('l', buf[0]);
  1821. EXPECT_EQ('l', buf[1]);
  1822. EXPECT_EQ(1, strm.read(buf, 1));
  1823. EXPECT_EQ('o', buf[0]);
  1824. EXPECT_EQ(0, strm.read(buf, 1));
  1825. }
  1826. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1827. auto host = "www.httpwatch.com";
  1828. auto ip = hosted_at(host);
  1829. EXPECT_EQ("23.96.13.243", ip);
  1830. std::vector<std::string> addrs;
  1831. hosted_at(host, addrs);
  1832. EXPECT_EQ(1u, addrs.size());
  1833. }
  1834. #if 0 // It depends on each test environment...
  1835. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1836. auto host = "www.youtube.com";
  1837. std::vector<std::string> addrs;
  1838. hosted_at(host, addrs);
  1839. EXPECT_EQ(20u, addrs.size());
  1840. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1841. EXPECT_TRUE(it != addrs.end());
  1842. }
  1843. #endif
  1844. class ChunkedEncodingTest : public ::testing::Test {
  1845. protected:
  1846. ChunkedEncodingTest()
  1847. : cli_(HOST, PORT)
  1848. #ifdef CPPHTTPLIB_SSL_ENABLED
  1849. ,
  1850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1851. #endif
  1852. {
  1853. cli_.set_connection_timeout(2);
  1854. #ifdef CPPHTTPLIB_SSL_ENABLED
  1855. cli_.enable_server_certificate_verification(false);
  1856. #endif
  1857. }
  1858. virtual void SetUp() {
  1859. read_file("./image.jpg", image_data_);
  1860. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1861. res.set_content("Hello World!", "text/plain");
  1862. });
  1863. svr_.Get(
  1864. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1865. res.set_chunked_content_provider(
  1866. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1867. size_t remaining = image_data_.size() - offset;
  1868. if (remaining == 0) {
  1869. sink.done();
  1870. } else {
  1871. constexpr size_t CHUNK_SIZE = 1024;
  1872. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1873. sink.write(&image_data_[offset], send_size);
  1874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1875. }
  1876. return true;
  1877. });
  1878. });
  1879. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1880. svr_.wait_until_ready();
  1881. }
  1882. virtual void TearDown() {
  1883. svr_.stop();
  1884. if (!request_threads_.empty()) {
  1885. std::this_thread::sleep_for(std::chrono::seconds(1));
  1886. for (auto &t : request_threads_) {
  1887. t.join();
  1888. }
  1889. }
  1890. t_.join();
  1891. }
  1892. #ifdef CPPHTTPLIB_SSL_ENABLED
  1893. SSLClient cli_;
  1894. SSLServer svr_;
  1895. #else
  1896. Client cli_;
  1897. Server svr_;
  1898. #endif
  1899. thread t_;
  1900. std::vector<thread> request_threads_;
  1901. std::string image_data_;
  1902. };
  1903. TEST_F(ChunkedEncodingTest, NormalGet) {
  1904. auto res = cli_.Get("/chunked");
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. std::string out;
  1907. read_file("./image.jpg", out);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ(out, res->body);
  1910. }
  1911. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1912. std::string body;
  1913. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1914. body.append(data, data_length);
  1915. return true;
  1916. });
  1917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1918. std::string out;
  1919. read_file("./image.jpg", out);
  1920. EXPECT_EQ(StatusCode::OK_200, res->status);
  1921. EXPECT_EQ(out, body);
  1922. }
  1923. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1924. std::string body;
  1925. auto res = cli_.Get(
  1926. "/chunked",
  1927. [&](const Response &response) {
  1928. EXPECT_EQ(StatusCode::OK_200, response.status);
  1929. return true;
  1930. },
  1931. [&](const char *data, size_t data_length) {
  1932. body.append(data, data_length);
  1933. return true;
  1934. });
  1935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1936. std::string out;
  1937. read_file("./image.jpg", out);
  1938. EXPECT_EQ(StatusCode::OK_200, res->status);
  1939. EXPECT_EQ(out, body);
  1940. }
  1941. TEST(RangeTest, FromHTTPBin_Online) {
  1942. auto host = "httpbingo.org";
  1943. auto path = std::string{"/range/32"};
  1944. #ifdef CPPHTTPLIB_SSL_ENABLED
  1945. auto port = 443;
  1946. SSLClient cli(host, port);
  1947. #else
  1948. auto port = 80;
  1949. Client cli(host, port);
  1950. #endif
  1951. cli.set_connection_timeout(5);
  1952. {
  1953. auto res = cli.Get(path);
  1954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1955. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1956. EXPECT_EQ(StatusCode::OK_200, res->status);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, -1}})};
  1960. auto res = cli.Get(path, headers);
  1961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1962. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1964. }
  1965. {
  1966. Headers headers = {make_range_header({{1, 10}})};
  1967. auto res = cli.Get(path, headers);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("bcdefghijk", res->body);
  1970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1971. }
  1972. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1973. // entire resource, while the original httpbin returned 200. Both are
  1974. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1975. {
  1976. Headers headers = {make_range_header({{0, 31}})};
  1977. auto res = cli.Get(path, headers);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1981. res->status == StatusCode::PartialContent_206);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{0, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1989. res->status == StatusCode::PartialContent_206);
  1990. }
  1991. // go-httpbin returns 206 with clamped range for over-range requests,
  1992. // while the original httpbin returned 416. Both behaviors are observed
  1993. // in real servers, so we only verify the request succeeds.
  1994. {
  1995. Headers headers = {make_range_header({{0, 32}})};
  1996. auto res = cli.Get(path, headers);
  1997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1998. }
  1999. }
  2000. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2001. auto host = "unresolvableaddress.local";
  2002. auto path = std::string{"/"};
  2003. #ifdef CPPHTTPLIB_SSL_ENABLED
  2004. auto port = 443;
  2005. SSLClient cli(host, port);
  2006. #else
  2007. auto port = 80;
  2008. Client cli(host, port);
  2009. #endif
  2010. cli.set_connection_timeout(1);
  2011. {
  2012. auto res = cli.Get(path);
  2013. ASSERT_FALSE(res);
  2014. }
  2015. std::this_thread::sleep_for(std::chrono::seconds(8));
  2016. }
  2017. #if defined(__linux__) && defined(__GLIBC__) && \
  2018. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2019. // Forward declaration: in split builds split.py strips `inline` and moves the
  2020. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2021. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2022. // against the symbol in both header-only and split builds.
  2023. namespace httplib {
  2024. namespace detail {
  2025. int getaddrinfo_with_timeout(const char *node, const char *service,
  2026. const struct addrinfo *hints,
  2027. struct addrinfo **res, time_t timeout_sec);
  2028. } // namespace detail
  2029. } // namespace httplib
  2030. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2031. //
  2032. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2033. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2034. // gai_suspend() call hits the connection timeout the function calls
  2035. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2036. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2037. // still alive and still references the now-destroyed stack frame.
  2038. //
  2039. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2040. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2041. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2042. // and runs them in a container.
  2043. namespace {
  2044. bool should_run_issue_2431_tests() {
  2045. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2046. return v && *v && std::string(v) != "0";
  2047. }
  2048. std::string unique_unresolvable_host(int n) {
  2049. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2050. // glibc still asks the configured nameserver — which is exactly the path
  2051. // we want to exercise. A unique label per call avoids the resolver cache.
  2052. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2053. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2054. std::to_string(n) + ".invalid";
  2055. }
  2056. } // namespace
  2057. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2058. if (!should_run_issue_2431_tests()) {
  2059. GTEST_SKIP()
  2060. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2061. }
  2062. for (int i = 0; i < 8; ++i) {
  2063. struct addrinfo hints;
  2064. memset(&hints, 0, sizeof(hints));
  2065. hints.ai_family = AF_UNSPEC;
  2066. hints.ai_socktype = SOCK_STREAM;
  2067. auto host = unique_unresolvable_host(i);
  2068. struct addrinfo *result = nullptr;
  2069. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2070. &result, /*timeout_sec=*/1);
  2071. if (rc == 0 && result) { freeaddrinfo(result); }
  2072. }
  2073. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2074. // stack region they still believe holds their gaicb.
  2075. std::this_thread::sleep_for(std::chrono::seconds(3));
  2076. }
  2077. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2078. if (!should_run_issue_2431_tests()) {
  2079. GTEST_SKIP()
  2080. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2081. }
  2082. std::atomic<bool> stop{false};
  2083. std::vector<std::thread> threads;
  2084. for (int t = 0; t < 8; ++t) {
  2085. threads.emplace_back([t, &stop] {
  2086. int i = 0;
  2087. while (!stop.load(std::memory_order_relaxed)) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(t * 100000 + i++);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. });
  2099. }
  2100. std::this_thread::sleep_for(std::chrono::seconds(8));
  2101. stop.store(true, std::memory_order_relaxed);
  2102. for (auto &th : threads) {
  2103. th.join();
  2104. }
  2105. std::this_thread::sleep_for(std::chrono::seconds(3));
  2106. }
  2107. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2108. if (!should_run_issue_2431_tests()) {
  2109. GTEST_SKIP()
  2110. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2111. }
  2112. std::atomic<bool> stop{false};
  2113. std::vector<std::thread> threads;
  2114. for (int t = 0; t < 8; ++t) {
  2115. threads.emplace_back([t, &stop] {
  2116. int i = 0;
  2117. while (!stop.load(std::memory_order_relaxed)) {
  2118. auto host = unique_unresolvable_host(t * 100000 + i++);
  2119. Client cli(host, 80);
  2120. cli.set_connection_timeout(1, 0);
  2121. cli.set_read_timeout(1, 0);
  2122. cli.set_write_timeout(1, 0);
  2123. (void)cli.Get("/");
  2124. }
  2125. });
  2126. }
  2127. std::this_thread::sleep_for(std::chrono::seconds(8));
  2128. stop.store(true, std::memory_order_relaxed);
  2129. for (auto &th : threads) {
  2130. th.join();
  2131. }
  2132. std::this_thread::sleep_for(std::chrono::seconds(3));
  2133. }
  2134. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2135. TEST(ConnectionErrorTest, InvalidHost) {
  2136. auto host = "-abcde.com";
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. auto port = 443;
  2139. SSLClient cli(host, port);
  2140. #else
  2141. auto port = 80;
  2142. Client cli(host, port);
  2143. #endif
  2144. cli.set_connection_timeout(std::chrono::seconds(2));
  2145. auto res = cli.Get("/");
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Connection, res.error());
  2148. }
  2149. TEST(ConnectionErrorTest, InvalidHost2) {
  2150. auto host = "httpcan.org/";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. SSLClient cli(host);
  2153. #else
  2154. Client cli(host);
  2155. #endif
  2156. cli.set_connection_timeout(std::chrono::seconds(2));
  2157. auto res = cli.Get("/");
  2158. ASSERT_TRUE(!res);
  2159. EXPECT_EQ(Error::Connection, res.error());
  2160. }
  2161. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2162. auto host = "httpcan.org/";
  2163. #ifdef CPPHTTPLIB_SSL_ENABLED
  2164. SSLClient cli(host);
  2165. #else
  2166. Client cli(host);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. stringstream s;
  2172. s << "error code: " << res.error();
  2173. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidPort) {
  2176. auto host = "localhost";
  2177. auto port = 44380;
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. SSLClient cli(host, port);
  2180. #else
  2181. Client cli(host, port);
  2182. #endif
  2183. cli.set_connection_timeout(std::chrono::seconds(2));
  2184. auto res = cli.Get("/");
  2185. ASSERT_TRUE(!res);
  2186. EXPECT_TRUE(Error::Connection == res.error() ||
  2187. Error::ConnectionTimeout == res.error());
  2188. }
  2189. TEST(ConnectionErrorTest, Timeout_Online) {
  2190. auto host = "google.com";
  2191. #ifdef CPPHTTPLIB_SSL_ENABLED
  2192. auto port = 44380;
  2193. SSLClient cli(host, port);
  2194. #else
  2195. auto port = 8080;
  2196. Client cli(host, port);
  2197. #endif
  2198. cli.set_connection_timeout(std::chrono::seconds(2));
  2199. // only probe one address type so that the error reason
  2200. // correlates to the timed-out IPv4, not the unsupported
  2201. // IPv6 connection attempt
  2202. cli.set_address_family(AF_INET);
  2203. auto res = cli.Get("/");
  2204. ASSERT_TRUE(!res);
  2205. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2206. }
  2207. TEST(CancelTest, NoCancel_Online) {
  2208. auto host = "httpbingo.org";
  2209. auto path = std::string{"/range/32"};
  2210. #ifdef CPPHTTPLIB_SSL_ENABLED
  2211. auto port = 443;
  2212. SSLClient cli(host, port);
  2213. #else
  2214. auto port = 80;
  2215. Client cli(host, port);
  2216. #endif
  2217. cli.set_connection_timeout(std::chrono::seconds(5));
  2218. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::OK_200, res->status);
  2222. }
  2223. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2224. // Use /bytes with a large payload so that the DownloadProgress callback
  2225. // (which only fires for Content-Length responses) is invoked before the
  2226. // entire body is received, giving cancellation a chance to fire.
  2227. auto host = "httpbingo.org";
  2228. auto path = std::string{"/bytes/524288"};
  2229. #ifdef CPPHTTPLIB_SSL_ENABLED
  2230. auto port = 443;
  2231. SSLClient cli(host, port);
  2232. #else
  2233. auto port = 80;
  2234. Client cli(host, port);
  2235. #endif
  2236. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2237. cli.set_connection_timeout(std::chrono::seconds(5));
  2238. ASSERT_TRUE(!res);
  2239. EXPECT_EQ(Error::Canceled, res.error());
  2240. }
  2241. TEST(CancelTest, WithCancelLargePayload_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/bytes/524288"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. auto port = 443;
  2246. SSLClient cli(host, port);
  2247. #else
  2248. auto port = 80;
  2249. Client cli(host, port);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. uint32_t count = 0;
  2253. auto res =
  2254. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2255. ASSERT_TRUE(!res);
  2256. EXPECT_EQ(Error::Canceled, res.error());
  2257. }
  2258. TEST(CancelTest, NoCancelPost) {
  2259. Server svr;
  2260. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2261. res.set_content("Hello World!", "text/plain");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. Client cli(HOST, PORT);
  2271. cli.set_connection_timeout(std::chrono::seconds(5));
  2272. auto res =
  2273. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2274. "application/json", [](uint64_t, uint64_t) { return true; });
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("Hello World!", res->body);
  2277. EXPECT_EQ(StatusCode::OK_200, res->status);
  2278. }
  2279. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2280. Server svr;
  2281. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2282. res.set_content("Hello World!", "text/plain");
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. Client cli(HOST, PORT);
  2292. cli.set_connection_timeout(std::chrono::seconds(5));
  2293. auto res =
  2294. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2295. "application/json", [](uint64_t, uint64_t) { return false; });
  2296. ASSERT_TRUE(!res);
  2297. EXPECT_EQ(Error::Canceled, res.error());
  2298. }
  2299. TEST(CancelTest, WithCancelLargePayloadPost) {
  2300. Server svr;
  2301. svr.set_payload_max_length(200 * 1024 * 1024);
  2302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2303. res.set_content(LARGE_DATA, "text/plain");
  2304. });
  2305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2306. auto se = detail::scope_exit([&] {
  2307. svr.stop();
  2308. thread.join();
  2309. ASSERT_FALSE(svr.is_running());
  2310. });
  2311. svr.wait_until_ready();
  2312. Client cli(HOST, PORT);
  2313. cli.set_payload_max_length(200 * 1024 * 1024);
  2314. cli.set_connection_timeout(std::chrono::seconds(5));
  2315. auto res =
  2316. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2317. "application/json", [](uint64_t, uint64_t) { return false; });
  2318. ASSERT_TRUE(!res);
  2319. EXPECT_EQ(Error::Canceled, res.error());
  2320. }
  2321. TEST(CancelTest, NoCancelPut) {
  2322. Server svr;
  2323. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. auto res =
  2336. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2337. "application/json", [](uint64_t, uint64_t) { return true; });
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ("Hello World!", res->body);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. }
  2342. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2343. Server svr;
  2344. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return false; });
  2359. ASSERT_TRUE(!res);
  2360. EXPECT_EQ(Error::Canceled, res.error());
  2361. }
  2362. TEST(CancelTest, WithCancelLargePayloadPut) {
  2363. Server svr;
  2364. svr.set_payload_max_length(200 * 1024 * 1024);
  2365. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content(LARGE_DATA, "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_payload_max_length(200 * 1024 * 1024);
  2377. cli.set_connection_timeout(std::chrono::seconds(5));
  2378. auto res =
  2379. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2380. "application/json", [](uint64_t, uint64_t) { return false; });
  2381. ASSERT_TRUE(!res);
  2382. EXPECT_EQ(Error::Canceled, res.error());
  2383. }
  2384. TEST(CancelTest, NoCancelPatch) {
  2385. Server svr;
  2386. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return true; });
  2401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2402. EXPECT_EQ("Hello World!", res->body);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. }
  2405. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2406. Server svr;
  2407. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return false; });
  2422. ASSERT_TRUE(!res);
  2423. EXPECT_EQ(Error::Canceled, res.error());
  2424. }
  2425. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2426. Server svr;
  2427. svr.set_payload_max_length(200 * 1024 * 1024);
  2428. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content(LARGE_DATA, "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_payload_max_length(200 * 1024 * 1024);
  2440. cli.set_connection_timeout(std::chrono::seconds(5));
  2441. auto res =
  2442. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2443. "application/json", [](uint64_t, uint64_t) { return false; });
  2444. ASSERT_TRUE(!res);
  2445. EXPECT_EQ(Error::Canceled, res.error());
  2446. }
  2447. TEST(CancelTest, NoCancelDelete) {
  2448. Server svr;
  2449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return true; });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ("Hello World!", res->body);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. }
  2468. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2469. Server svr;
  2470. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return false; });
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Canceled, res.error());
  2487. }
  2488. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2489. Server svr;
  2490. svr.set_payload_max_length(200 * 1024 * 1024);
  2491. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content(LARGE_DATA, "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_payload_max_length(200 * 1024 * 1024);
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. auto res =
  2505. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2506. "application/json", [](uint64_t, uint64_t) { return false; });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. static std::string remove_whitespace(const std::string &input) {
  2511. std::string output;
  2512. output.reserve(input.size());
  2513. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2514. [](unsigned char c) { return !std::isspace(c); });
  2515. return output;
  2516. }
  2517. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2518. auto host = "httpbingo.org";
  2519. auto path = std::string{"/basic-auth/hello/world"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2531. }
  2532. {
  2533. auto res = cli.Get(
  2534. path, Headers{make_basic_authentication_header("hello", "world")});
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. auto body = remove_whitespace(res->body);
  2537. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2538. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. }
  2541. {
  2542. cli.set_basic_auth("hello", "world");
  2543. auto res = cli.Get(path);
  2544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2545. auto body = remove_whitespace(res->body);
  2546. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2547. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2548. EXPECT_EQ(StatusCode::OK_200, res->status);
  2549. }
  2550. {
  2551. cli.set_basic_auth("hello", "bad");
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. cli.set_basic_auth("bad", "world");
  2558. auto res = cli.Get(path);
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2561. }
  2562. }
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2565. auto host = "httpbingo.org";
  2566. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2567. auto paths = std::vector<std::string>{
  2568. "/digest-auth/auth/hello/world/MD5",
  2569. "/digest-auth/auth/hello/world/SHA-256",
  2570. };
  2571. auto port = 443;
  2572. SSLClient cli(host, port);
  2573. {
  2574. auto res = cli.Get(unauth_path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2577. }
  2578. {
  2579. cli.set_digest_auth("hello", "world");
  2580. for (const auto &path : paths) {
  2581. auto res = cli.Get(path.c_str());
  2582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2583. auto body = remove_whitespace(res->body);
  2584. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2585. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2586. EXPECT_EQ(StatusCode::OK_200, res->status);
  2587. }
  2588. cli.set_digest_auth("hello", "bad");
  2589. for (const auto &path : paths) {
  2590. auto res = cli.Get(path.c_str());
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2593. }
  2594. }
  2595. }
  2596. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2597. // comma-separated list of challenges, and each challenge may itself carry a
  2598. // comma-separated auth-param list, so a server can legally offer Basic
  2599. // before Digest, either as two field lines or packed into one. Runs one 401
  2600. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2601. // value() joins them in receipt order) and checks that the retry carries a
  2602. // well-formed Digest Authorization header naming expected_realm.
  2603. static void
  2604. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2605. const std::string &expected_realm) {
  2606. std::atomic<int> hits{0};
  2607. Server svr;
  2608. svr.Get("/x", [&](const Request &req, Response &res) {
  2609. if (++hits == 1) {
  2610. res.status = StatusCode::Unauthorized_401;
  2611. for (const auto &challenge : challenges) {
  2612. res.set_header("WWW-Authenticate", challenge);
  2613. }
  2614. } else {
  2615. auto authorization = req.get_header_value("Authorization");
  2616. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2617. EXPECT_NE(std::string::npos,
  2618. authorization.find("realm=\"" + expected_realm + "\""));
  2619. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2620. res.set_content("ok", "text/plain");
  2621. }
  2622. });
  2623. auto port = svr.bind_to_any_port(HOST);
  2624. std::thread t([&]() { svr.listen_after_bind(); });
  2625. auto se = detail::scope_exit([&] {
  2626. svr.stop();
  2627. t.join();
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, port);
  2631. cli.set_digest_auth("hello", "world");
  2632. auto res = cli.Get("/x");
  2633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2634. EXPECT_EQ(2, hits.load());
  2635. }
  2636. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2637. static const char *kDigestChallenge =
  2638. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2639. "algorithm=MD5";
  2640. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2641. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2642. "testrealm");
  2643. }
  2644. // Same challenge list with the schemes in the opposite order, to make sure
  2645. // the fix above didn't just special-case "Basic first".
  2646. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2647. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2648. "testrealm");
  2649. }
  2650. // A comma inside a quoted auth-param value must not be mistaken for the
  2651. // separator between two challenges (or two auth-params).
  2652. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2653. run_digest_challenge_list_test(
  2654. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2655. "algorithm=MD5"},
  2656. "test,realm");
  2657. }
  2658. #endif
  2659. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2660. auto host = "google.com";
  2661. auto another_host = "example.com";
  2662. auto wrong_ip = "0.0.0.0";
  2663. #ifdef CPPHTTPLIB_SSL_ENABLED
  2664. SSLClient cli(host);
  2665. #else
  2666. Client cli(host);
  2667. #endif
  2668. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2669. auto res = cli.Get("/");
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2672. }
  2673. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2674. auto host = "google.com";
  2675. auto wrong_ip = "0.0.0.0";
  2676. #ifdef CPPHTTPLIB_SSL_ENABLED
  2677. SSLClient cli(host);
  2678. #else
  2679. Client cli(host);
  2680. #endif
  2681. cli.set_hostname_addr_map({{host, wrong_ip}});
  2682. auto res = cli.Get("/");
  2683. ASSERT_TRUE(!res);
  2684. EXPECT_EQ(Error::Connection, res.error());
  2685. }
  2686. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2687. // A mapped value that is not an IP literal must be resolved. "localhost"
  2688. // resolves from the hosts file, so this test needs no external DNS.
  2689. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2690. auto host = "target.invalid";
  2691. Server svr;
  2692. std::string received_host;
  2693. svr.Get("/hi", [&](const Request &req, Response &res) {
  2694. received_host = req.get_header_value("Host");
  2695. res.set_content("Hello World!", "text/plain");
  2696. });
  2697. auto port = svr.bind_to_any_port(HOST);
  2698. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2699. auto se = detail::scope_exit([&] {
  2700. svr.stop();
  2701. thread.join();
  2702. ASSERT_FALSE(svr.is_running());
  2703. });
  2704. svr.wait_until_ready();
  2705. Client cli(host, port);
  2706. cli.set_hostname_addr_map({{host, HOST}});
  2707. auto res = cli.Get("/hi");
  2708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2709. EXPECT_EQ(StatusCode::OK_200, res->status);
  2710. // The mapping only redirects the connection; the identity stays host_.
  2711. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2712. }
  2713. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2714. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2715. auto host = "target.invalid";
  2716. Server svr;
  2717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2718. res.set_content("Hello World!", "text/plain");
  2719. });
  2720. auto port = svr.bind_to_any_port("127.0.0.1");
  2721. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(host, port);
  2729. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2730. auto res = cli.Get("/hi");
  2731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2735. // An empty mapped value must leave host_ as the connection target. Without
  2736. // that guard the empty value would become the host argument, getaddrinfo
  2737. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2738. // loopback - silently connecting somewhere the caller never asked for.
  2739. // The server listens on loopback, so such a fallback would succeed and is
  2740. // therefore observable as a failure of this test.
  2741. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2742. Server svr;
  2743. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2744. res.set_content("Hello World!", "text/plain");
  2745. });
  2746. auto port = svr.bind_to_any_port(HOST);
  2747. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(blackhole, port);
  2755. cli.set_hostname_addr_map({{blackhole, ""}});
  2756. cli.set_connection_timeout(1);
  2757. auto res = cli.Get("/hi");
  2758. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2759. }
  2760. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2761. auto host = "httpbingo.org";
  2762. auto path = std::string{"/absolute-redirect/3"};
  2763. #ifdef CPPHTTPLIB_SSL_ENABLED
  2764. SSLClient cli(host);
  2765. #else
  2766. Client cli(host);
  2767. #endif
  2768. cli.set_follow_location(true);
  2769. auto res = cli.Get(path);
  2770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2771. EXPECT_EQ(StatusCode::OK_200, res->status);
  2772. }
  2773. TEST(RedirectTest, Redirect_Online) {
  2774. auto host = "httpbingo.org";
  2775. auto path = std::string{"/redirect/3"};
  2776. #ifdef CPPHTTPLIB_SSL_ENABLED
  2777. SSLClient cli(host);
  2778. #else
  2779. Client cli(host);
  2780. #endif
  2781. cli.set_follow_location(true);
  2782. auto res = cli.Get(path);
  2783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2784. EXPECT_EQ(StatusCode::OK_200, res->status);
  2785. }
  2786. TEST(RelativeRedirectTest, Redirect_Online) {
  2787. auto host = "httpbingo.org";
  2788. auto path = std::string{"/relative-redirect/3"};
  2789. #ifdef CPPHTTPLIB_SSL_ENABLED
  2790. SSLClient cli(host);
  2791. #else
  2792. Client cli(host);
  2793. #endif
  2794. cli.set_follow_location(true);
  2795. auto res = cli.Get(path);
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. }
  2799. TEST(TooManyRedirectTest, Redirect_Online) {
  2800. auto host = "httpbingo.org";
  2801. auto path = std::string{"/redirect/21"};
  2802. #ifdef CPPHTTPLIB_SSL_ENABLED
  2803. SSLClient cli(host);
  2804. #else
  2805. Client cli(host);
  2806. #endif
  2807. cli.set_follow_location(true);
  2808. auto res = cli.Get(path);
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2811. }
  2812. #ifdef CPPHTTPLIB_SSL_ENABLED
  2813. TEST(YahooRedirectTest, Redirect_Online) {
  2814. Client cli("yahoo.com");
  2815. auto res = cli.Get("/");
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2818. cli.set_follow_location(true);
  2819. res = cli.Get("/");
  2820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2821. EXPECT_EQ(StatusCode::OK_200, res->status);
  2822. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2823. }
  2824. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2825. #define REDIR_HOST "httpbingo.org"
  2826. #define REDIR_PATH "/redirect-to"
  2827. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2828. SSLClient cli(REDIR_HOST);
  2829. cli.set_follow_location(true);
  2830. auto res =
  2831. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2833. EXPECT_EQ(StatusCode::OK_200, res->status);
  2834. }
  2835. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2836. SSLClient cli(REDIR_HOST);
  2837. cli.set_follow_location(true);
  2838. Params params;
  2839. params.emplace("url", "http://example.com");
  2840. params.emplace("status_code", "302");
  2841. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::OK_200, res->status);
  2844. }
  2845. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2846. SSLClient cli(REDIR_HOST);
  2847. cli.set_follow_location(true);
  2848. Params params;
  2849. params.emplace("url", "http://example.com");
  2850. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ(StatusCode::OK_200, res->status);
  2853. }
  2854. TEST(UrlWithSpace, Redirect_Online) {
  2855. SSLClient cli("edge.forgecdn.net");
  2856. cli.set_follow_location(true);
  2857. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::OK_200, res->status);
  2860. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2861. }
  2862. #endif
  2863. #if !defined(_WIN32) && !defined(_WIN64)
  2864. TEST(ReceiveSignals, Signal) {
  2865. auto setupSignalHandlers = []() {
  2866. struct sigaction act;
  2867. sigemptyset(&act.sa_mask);
  2868. act.sa_flags = SA_SIGINFO;
  2869. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2870. switch (sig) {
  2871. case SIGINT:
  2872. default: break;
  2873. }
  2874. };
  2875. ::sigaction(SIGINT, &act, nullptr);
  2876. };
  2877. Server svr;
  2878. int port = 0;
  2879. auto thread = std::thread([&]() {
  2880. setupSignalHandlers();
  2881. port = svr.bind_to_any_port(HOST);
  2882. svr.listen_after_bind();
  2883. });
  2884. auto se = detail::scope_exit([&] {
  2885. svr.stop();
  2886. thread.join();
  2887. ASSERT_FALSE(svr.is_running());
  2888. });
  2889. svr.wait_until_ready();
  2890. ASSERT_TRUE(svr.is_running());
  2891. pthread_kill(thread.native_handle(), SIGINT);
  2892. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2893. ASSERT_TRUE(svr.is_running());
  2894. }
  2895. #endif
  2896. TEST(RedirectToDifferentPort, Redirect) {
  2897. Server svr1;
  2898. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2899. res.set_content("Hello World!", "text/plain");
  2900. });
  2901. int svr1_port = 0;
  2902. auto thread1 = std::thread([&]() {
  2903. svr1_port = svr1.bind_to_any_port(HOST);
  2904. svr1.listen_after_bind();
  2905. });
  2906. Server svr2;
  2907. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2908. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2909. });
  2910. int svr2_port = 0;
  2911. auto thread2 = std::thread([&]() {
  2912. svr2_port = svr2.bind_to_any_port(HOST);
  2913. svr2.listen_after_bind();
  2914. });
  2915. auto se = detail::scope_exit([&] {
  2916. svr2.stop();
  2917. thread2.join();
  2918. svr1.stop();
  2919. thread1.join();
  2920. ASSERT_FALSE(svr2.is_running());
  2921. ASSERT_FALSE(svr1.is_running());
  2922. });
  2923. svr1.wait_until_ready();
  2924. svr2.wait_until_ready();
  2925. Client cli("localhost", svr2_port);
  2926. cli.set_follow_location(true);
  2927. auto res = cli.Get("/2");
  2928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2929. EXPECT_EQ(StatusCode::OK_200, res->status);
  2930. EXPECT_EQ("Hello World!", res->body);
  2931. }
  2932. static void
  2933. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2934. Server svr1;
  2935. std::string captured_authorization;
  2936. svr1.Get("/target", [&](const Request &req, Response &res) {
  2937. captured_authorization = req.get_header_value("Authorization");
  2938. res.set_content("OK", "text/plain");
  2939. });
  2940. int svr1_port = 0;
  2941. auto thread1 = std::thread([&]() {
  2942. svr1_port = svr1.bind_to_any_port(HOST);
  2943. svr1.listen_after_bind();
  2944. });
  2945. Server svr2;
  2946. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2947. res.set_redirect(
  2948. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2949. });
  2950. int svr2_port = 0;
  2951. auto thread2 = std::thread([&]() {
  2952. svr2_port = svr2.bind_to_any_port(HOST);
  2953. svr2.listen_after_bind();
  2954. });
  2955. auto se = detail::scope_exit([&] {
  2956. svr2.stop();
  2957. thread2.join();
  2958. svr1.stop();
  2959. thread1.join();
  2960. ASSERT_FALSE(svr2.is_running());
  2961. ASSERT_FALSE(svr1.is_running());
  2962. });
  2963. svr1.wait_until_ready();
  2964. svr2.wait_until_ready();
  2965. Client cli("localhost", svr2_port);
  2966. cli.set_follow_location(true);
  2967. set_auth(cli);
  2968. auto res = cli.Get("/redir");
  2969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2970. EXPECT_EQ(StatusCode::OK_200, res->status);
  2971. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2972. EXPECT_TRUE(captured_authorization.empty());
  2973. }
  2974. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2975. TestDoNotForwardCredentialsOnRedirect(
  2976. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2977. }
  2978. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2979. TestDoNotForwardCredentialsOnRedirect(
  2980. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2981. }
  2982. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2983. Server svr1;
  2984. std::string captured_cookie;
  2985. bool target_hit = false;
  2986. svr1.Get("/target", [&](const Request &req, Response &res) {
  2987. captured_cookie = req.get_header_value("Cookie");
  2988. target_hit = true;
  2989. res.set_content("OK", "text/plain");
  2990. });
  2991. int svr1_port = 0;
  2992. auto thread1 = std::thread([&]() {
  2993. svr1_port = svr1.bind_to_any_port(HOST);
  2994. svr1.listen_after_bind();
  2995. });
  2996. Server svr2;
  2997. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2998. res.set_redirect(
  2999. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3000. });
  3001. int svr2_port = 0;
  3002. auto thread2 = std::thread([&]() {
  3003. svr2_port = svr2.bind_to_any_port(HOST);
  3004. svr2.listen_after_bind();
  3005. });
  3006. auto se = detail::scope_exit([&] {
  3007. svr2.stop();
  3008. thread2.join();
  3009. svr1.stop();
  3010. thread1.join();
  3011. ASSERT_FALSE(svr2.is_running());
  3012. ASSERT_FALSE(svr1.is_running());
  3013. });
  3014. svr1.wait_until_ready();
  3015. svr2.wait_until_ready();
  3016. Client cli("localhost", svr2_port);
  3017. cli.set_follow_location(true);
  3018. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3019. auto res = cli.Get("/redir", headers);
  3020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3021. EXPECT_EQ(StatusCode::OK_200, res->status);
  3022. EXPECT_TRUE(target_hit);
  3023. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3024. EXPECT_TRUE(captured_cookie.empty());
  3025. }
  3026. TEST(RedirectToSamePort, ForwardCookie) {
  3027. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3028. // header so that ordinary session flows keep working.
  3029. Server svr;
  3030. std::string captured_cookie;
  3031. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3032. res.set_redirect("/target", 302);
  3033. });
  3034. svr.Get("/target", [&](const Request &req, Response &res) {
  3035. captured_cookie = req.get_header_value("Cookie");
  3036. res.set_content("OK", "text/plain");
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. thread.join();
  3043. ASSERT_FALSE(svr.is_running());
  3044. });
  3045. svr.wait_until_ready();
  3046. Client cli(HOST, port);
  3047. cli.set_follow_location(true);
  3048. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3049. auto res = cli.Get("/redir", headers);
  3050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3053. }
  3054. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3055. Server svr;
  3056. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3057. // Port number that overflows int — should not crash
  3058. res.set_redirect("http://localhost:99999999999999999999/target");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. thread.join();
  3065. ASSERT_FALSE(svr.is_running());
  3066. });
  3067. svr.wait_until_ready();
  3068. Client cli(HOST, port);
  3069. cli.set_follow_location(true);
  3070. auto res = cli.Get("/redir");
  3071. // Should fail gracefully, not crash (no valid response due to bad port)
  3072. EXPECT_FALSE(res);
  3073. }
  3074. TEST(RedirectFromPageWithContent, Redirect) {
  3075. Server svr;
  3076. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3077. res.set_content("___", "text/plain");
  3078. res.set_redirect("/2");
  3079. });
  3080. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3081. res.set_content("Hello World!", "text/plain");
  3082. });
  3083. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. th.join();
  3087. ASSERT_FALSE(svr.is_running());
  3088. });
  3089. svr.wait_until_ready();
  3090. {
  3091. Client cli("localhost", PORT);
  3092. cli.set_follow_location(true);
  3093. std::string body;
  3094. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3095. body.append(data, data_length);
  3096. return true;
  3097. });
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. EXPECT_EQ("Hello World!", body);
  3101. }
  3102. {
  3103. Client cli("localhost", PORT);
  3104. std::string body;
  3105. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3106. body.append(data, data_length);
  3107. return true;
  3108. });
  3109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3110. EXPECT_EQ(StatusCode::Found_302, res->status);
  3111. EXPECT_EQ("___", body);
  3112. }
  3113. }
  3114. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3115. Server svr;
  3116. auto port_str = std::to_string(PORT);
  3117. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3118. auto expected_host = "[::1]:" + port_str;
  3119. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("___", "text/plain");
  3121. // res.set_redirect("/2");
  3122. res.set_redirect(redirect_url);
  3123. });
  3124. svr.Get("/2", [&](const Request &req, Response &res) {
  3125. auto host_header = req.headers.find("Host");
  3126. ASSERT_TRUE(host_header != req.headers.end());
  3127. EXPECT_EQ(expected_host, host_header->second);
  3128. res.set_content("Hello World!", "text/plain");
  3129. });
  3130. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3131. auto se = detail::scope_exit([&] {
  3132. svr.stop();
  3133. th.join();
  3134. ASSERT_FALSE(svr.is_running());
  3135. });
  3136. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3137. // actually starts anything, so the condition !svr.is_running() will
  3138. // always remain true, and the loop never stops.
  3139. // This basically counts how many milliseconds have passed since the
  3140. // call to svr.listen(), and if after 5 seconds nothing started yet
  3141. // aborts the test.
  3142. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3143. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3144. ASSERT_LT(milliseconds, 5000U);
  3145. }
  3146. {
  3147. Client cli("::1", PORT);
  3148. cli.set_follow_location(true);
  3149. std::string body;
  3150. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3151. body.append(data, data_length);
  3152. return true;
  3153. });
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("Hello World!", body);
  3157. }
  3158. {
  3159. Client cli("::1", PORT);
  3160. std::string body;
  3161. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3162. body.append(data, data_length);
  3163. return true;
  3164. });
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::Found_302, res->status);
  3167. EXPECT_EQ("___", body);
  3168. }
  3169. }
  3170. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3171. Server svr;
  3172. svr.Get("/foo", [](const Request &req, Response &res) {
  3173. auto a = req.params.find("a");
  3174. if (a != req.params.end()) {
  3175. res.set_content((*a).second, "text/plain");
  3176. res.status = StatusCode::OK_200;
  3177. } else {
  3178. res.status = StatusCode::BadRequest_400;
  3179. }
  3180. });
  3181. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3182. auto se = detail::scope_exit([&] {
  3183. svr.stop();
  3184. thread.join();
  3185. ASSERT_FALSE(svr.is_running());
  3186. });
  3187. svr.wait_until_ready();
  3188. {
  3189. Client cli(HOST, PORT);
  3190. cli.set_path_encode(false);
  3191. auto res = cli.Get("/foo?a=explicitly+encoded");
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. // This expects it back with a space, as the `+` won't have been
  3195. // url-encoded, and server-side the params get decoded turning `+`
  3196. // into spaces.
  3197. EXPECT_EQ("explicitly encoded", res->body);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3201. // When path encoding is disabled the client must transmit the supplied
  3202. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3203. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3204. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3205. // than a space (0x20). Assert on the raw wire target to catch this.
  3206. Server svr;
  3207. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3208. svr.Get("/foo", [&](const Request &req, Response &res) {
  3209. EXPECT_EQ(expected_target, req.target);
  3210. res.status = StatusCode::OK_200;
  3211. });
  3212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3213. auto se = detail::scope_exit([&] {
  3214. svr.stop();
  3215. thread.join();
  3216. ASSERT_FALSE(svr.is_running());
  3217. });
  3218. svr.wait_until_ready();
  3219. {
  3220. Client cli(HOST, PORT);
  3221. cli.set_path_encode(false);
  3222. auto res = cli.Get(expected_target.c_str());
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::OK_200, res->status);
  3225. }
  3226. }
  3227. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3228. // `open_stream()` used to skip the path encoding that the buffered send
  3229. // path applies, so the same `path` produced different bytes in the request
  3230. // line depending on which API was used. Assert the two agree.
  3231. Server svr;
  3232. std::string target;
  3233. svr.Get(".*", [&](const Request &req, Response &res) {
  3234. target = req.target;
  3235. res.status = StatusCode::OK_200;
  3236. });
  3237. auto port = svr.bind_to_any_port(HOST);
  3238. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3239. auto se = detail::scope_exit([&] {
  3240. svr.stop();
  3241. thread.join();
  3242. ASSERT_FALSE(svr.is_running());
  3243. });
  3244. svr.wait_until_ready();
  3245. struct {
  3246. const char *path;
  3247. const char *expected;
  3248. } cases[] = {
  3249. {"/a b?x=1", "/a%20b?x=1"},
  3250. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3251. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3252. };
  3253. for (const auto &c : cases) {
  3254. Client cli(HOST, port);
  3255. target.clear();
  3256. auto res = cli.Get(c.path);
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3259. auto buffered_target = target;
  3260. target.clear();
  3261. auto handle = cli.open_stream("GET", c.path);
  3262. EXPECT_TRUE(handle.is_valid())
  3263. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3264. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3265. }
  3266. }
  3267. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3268. // The `set_path_encode(false)` contract — transmit the supplied target
  3269. // verbatim — must hold for the streaming API too.
  3270. Server svr;
  3271. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3272. std::string target;
  3273. svr.Get("/foo", [&](const Request &req, Response &res) {
  3274. target = req.target;
  3275. res.status = StatusCode::OK_200;
  3276. });
  3277. auto port = svr.bind_to_any_port(HOST);
  3278. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3279. auto se = detail::scope_exit([&] {
  3280. svr.stop();
  3281. thread.join();
  3282. ASSERT_FALSE(svr.is_running());
  3283. });
  3284. svr.wait_until_ready();
  3285. {
  3286. Client cli(HOST, port);
  3287. cli.set_path_encode(false);
  3288. auto handle = cli.open_stream("GET", expected_target);
  3289. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3290. EXPECT_EQ(expected_target, target);
  3291. }
  3292. }
  3293. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3294. // With path encoding enabled a CR/LF in the target is percent-encoded
  3295. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3296. // write_request_line still backstops `set_path_encode(false)`, which is
  3297. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3298. Server svr;
  3299. // Captured before routing: the decoded path contains a newline, which a
  3300. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3301. std::string target;
  3302. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3303. target = req.target;
  3304. res.status = StatusCode::OK_200;
  3305. return Server::HandlerResponse::Handled;
  3306. });
  3307. auto port = svr.bind_to_any_port(HOST);
  3308. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3309. auto se = detail::scope_exit([&] {
  3310. svr.stop();
  3311. thread.join();
  3312. ASSERT_FALSE(svr.is_running());
  3313. });
  3314. svr.wait_until_ready();
  3315. {
  3316. Client cli(HOST, port);
  3317. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3318. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3319. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3320. }
  3321. }
  3322. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3323. // Nothing may reach the wire: a raw CR/LF target would split the request
  3324. // line and inject headers.
  3325. Server svr;
  3326. // Pre-routing so that "not called" means nothing reached the server at all,
  3327. // rather than merely failing to match a handler pattern.
  3328. auto handler_called = false;
  3329. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3330. handler_called = true;
  3331. res.status = StatusCode::OK_200;
  3332. return Server::HandlerResponse::Handled;
  3333. });
  3334. auto port = svr.bind_to_any_port(HOST);
  3335. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3336. auto se = detail::scope_exit([&] {
  3337. svr.stop();
  3338. thread.join();
  3339. ASSERT_FALSE(svr.is_running());
  3340. });
  3341. svr.wait_until_ready();
  3342. {
  3343. Client cli(HOST, port);
  3344. cli.set_path_encode(false);
  3345. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3346. EXPECT_FALSE(handle.is_valid());
  3347. EXPECT_EQ(Error::Write, handle.error);
  3348. EXPECT_FALSE(handler_called);
  3349. }
  3350. }
  3351. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3352. // Which of the two branches runs is decided by whether the query component
  3353. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3354. // an empty query and must still fall back to building one from
  3355. // `req.params`, while a non-empty query must win over `req.params`.
  3356. Server svr;
  3357. std::string target;
  3358. svr.Get("/foo", [&](const Request &req, Response &res) {
  3359. target = req.target;
  3360. res.status = StatusCode::OK_200;
  3361. });
  3362. auto port = svr.bind_to_any_port(HOST);
  3363. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3364. auto se = detail::scope_exit([&] {
  3365. svr.stop();
  3366. thread.join();
  3367. ASSERT_FALSE(svr.is_running());
  3368. });
  3369. svr.wait_until_ready();
  3370. {
  3371. // Trailing `?` -> empty query component -> `req.params` is used.
  3372. Client cli(HOST, port);
  3373. Request req;
  3374. req.method = "GET";
  3375. req.path = "/foo?";
  3376. req.params.emplace("a", "1");
  3377. target.clear();
  3378. auto res = cli.send(req);
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ("/foo?a=1", target);
  3381. }
  3382. {
  3383. // Non-empty query in `req.path` -> `req.params` is not appended.
  3384. Client cli(HOST, port);
  3385. Request req;
  3386. req.method = "GET";
  3387. req.path = "/foo?b=2";
  3388. req.params.emplace("a", "1");
  3389. target.clear();
  3390. auto res = cli.send(req);
  3391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3392. EXPECT_EQ("/foo?b=2", target);
  3393. }
  3394. }
  3395. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3396. Server svr;
  3397. svr.Get("/", [](const Request &req, Response &) {
  3398. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3399. });
  3400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3401. auto se = detail::scope_exit([&] {
  3402. svr.stop();
  3403. thread.join();
  3404. ASSERT_FALSE(svr.is_running());
  3405. });
  3406. svr.wait_until_ready();
  3407. {
  3408. Client cli(HOST, PORT);
  3409. cli.set_path_encode(false);
  3410. auto res = cli.Get("/?something=%0A");
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. }
  3414. }
  3415. TEST(BindServerTest, BindDualStack) {
  3416. Server svr;
  3417. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3418. res.set_content("Hello World!", "text/plain");
  3419. });
  3420. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3421. auto se = detail::scope_exit([&] {
  3422. svr.stop();
  3423. thread.join();
  3424. ASSERT_FALSE(svr.is_running());
  3425. });
  3426. svr.wait_until_ready();
  3427. {
  3428. Client cli("127.0.0.1", PORT);
  3429. auto res = cli.Get("/1");
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("Hello World!", res->body);
  3433. }
  3434. {
  3435. Client cli("::1", PORT);
  3436. auto res = cli.Get("/1");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::OK_200, res->status);
  3439. EXPECT_EQ("Hello World!", res->body);
  3440. }
  3441. }
  3442. TEST(BindServerTest, BindAndListenSeparately) {
  3443. Server svr;
  3444. int port = svr.bind_to_any_port("0.0.0.0");
  3445. ASSERT_TRUE(svr.is_valid());
  3446. ASSERT_TRUE(port > 0);
  3447. svr.stop();
  3448. }
  3449. // Reports whether anything is still listening on a loopback port. A plain
  3450. // connect() is used instead of a Client request because a socket left bound by
  3451. // mistake accepts the connection into its backlog and never answers, which
  3452. // would hang the test instead of failing it.
  3453. static bool is_loopback_port_accepting(int port) {
  3454. sockaddr_in addr{};
  3455. addr.sin_family = AF_INET;
  3456. addr.sin_port = htons(static_cast<uint16_t>(port));
  3457. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3458. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3459. EXPECT_NE(sock, INVALID_SOCKET);
  3460. if (sock == INVALID_SOCKET) { return false; }
  3461. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3462. static_cast<socklen_t>(sizeof(addr)));
  3463. detail::close_socket(sock);
  3464. return ret == 0;
  3465. }
  3466. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3467. Server svr;
  3468. auto port = svr.bind_to_any_port("127.0.0.1");
  3469. ASSERT_TRUE(port > 0);
  3470. svr.stop();
  3471. // bind_to_any_port() already called listen(2), so until stop() closed the
  3472. // descriptor the port kept accepting connections into the backlog. ASSERT
  3473. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3474. // below blocks forever in the accept loop.
  3475. ASSERT_FALSE(is_loopback_port_accepting(port));
  3476. // Nothing is left to accept on, so listen_after_bind() must report failure
  3477. // instead of returning success without ever serving.
  3478. EXPECT_FALSE(svr.listen_after_bind());
  3479. // The failed listen marks the server decommissioned, so a waiter returns
  3480. // instead of spinning forever.
  3481. svr.wait_until_ready();
  3482. }
  3483. #ifdef CPPHTTPLIB_SSL_ENABLED
  3484. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3486. CLIENT_CA_CERT_DIR);
  3487. int port = svr.bind_to_any_port("0.0.0.0");
  3488. ASSERT_TRUE(svr.is_valid());
  3489. ASSERT_TRUE(port > 0);
  3490. svr.stop();
  3491. }
  3492. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3493. // or a rejected CustomRoute() registration would not stop the server binding.
  3494. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3496. CLIENT_CA_CERT_DIR);
  3497. ASSERT_TRUE(svr.is_valid());
  3498. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3499. EXPECT_FALSE(svr.is_valid());
  3500. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3501. }
  3502. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3503. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3504. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3505. int port = svr.bind_to_any_port("0.0.0.0");
  3506. ASSERT_TRUE(svr.is_valid());
  3507. ASSERT_TRUE(port > 0);
  3508. svr.stop();
  3509. }
  3510. TEST(BindServerTest, UpdateCertsPem) {
  3511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3512. int port = svr.bind_to_any_port("0.0.0.0");
  3513. ASSERT_TRUE(svr.is_valid());
  3514. ASSERT_TRUE(port > 0);
  3515. // Read PEM files
  3516. std::string cert_pem, key_pem, ca_pem;
  3517. read_file(SERVER_CERT_FILE, cert_pem);
  3518. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3519. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3520. // Update server certificates using PEM API
  3521. ASSERT_TRUE(
  3522. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3523. ASSERT_TRUE(svr.is_valid());
  3524. svr.stop();
  3525. }
  3526. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3527. // Start server with client CA (enables client auth)
  3528. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3529. ASSERT_TRUE(svr.is_valid());
  3530. bool handler_called = false;
  3531. svr.Get("/test", [&](const Request &req, Response &res) {
  3532. handler_called = true;
  3533. // Verify client certificate is present
  3534. auto cert = req.peer_cert();
  3535. EXPECT_TRUE(static_cast<bool>(cert));
  3536. res.set_content("ok", "text/plain");
  3537. });
  3538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. t.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. // Read PEM files
  3546. std::string cert_pem, key_pem, ca_pem;
  3547. read_file(SERVER_CERT_FILE, cert_pem);
  3548. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3549. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3550. // Update server certificates and client CA using PEM API while server running
  3551. ASSERT_TRUE(
  3552. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3553. // Connect with client certificate
  3554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3555. cli.enable_server_certificate_verification(false);
  3556. cli.set_connection_timeout(30);
  3557. auto res = cli.Get("/test");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_TRUE(handler_called);
  3561. EXPECT_EQ("ok", res->body);
  3562. }
  3563. #endif
  3564. TEST(ErrorHandlerTest, ContentLength) {
  3565. Server svr;
  3566. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3567. res.status = StatusCode::OK_200;
  3568. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3569. "text/html"); // <= Content-Length still 13
  3570. });
  3571. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!\n", "text/plain");
  3573. res.status = 524;
  3574. });
  3575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3576. auto se = detail::scope_exit([&] {
  3577. svr.stop();
  3578. thread.join();
  3579. ASSERT_FALSE(svr.is_running());
  3580. });
  3581. svr.wait_until_ready();
  3582. {
  3583. Client cli(HOST, PORT);
  3584. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::OK_200, res->status);
  3587. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3588. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3589. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3590. }
  3591. }
  3592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3593. TEST(ExceptionTest, WithoutExceptionHandler) {
  3594. Server svr;
  3595. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3596. throw std::runtime_error("exception...");
  3597. });
  3598. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3599. throw std::runtime_error("exception\r\n...");
  3600. });
  3601. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3602. auto se = detail::scope_exit([&] {
  3603. svr.stop();
  3604. listen_thread.join();
  3605. ASSERT_FALSE(svr.is_running());
  3606. });
  3607. svr.wait_until_ready();
  3608. Client cli("localhost", PORT);
  3609. {
  3610. auto res = cli.Get("/exception");
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3613. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3614. }
  3615. {
  3616. auto res = cli.Get("/unknown");
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3619. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3620. }
  3621. }
  3622. TEST(ExceptionTest, WithExceptionHandler) {
  3623. Server svr;
  3624. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3625. std::exception_ptr ep) {
  3626. EXPECT_FALSE(ep == nullptr);
  3627. try {
  3628. std::rethrow_exception(ep);
  3629. } catch (std::exception &e) {
  3630. EXPECT_EQ("abc", std::string(e.what()));
  3631. } catch (...) {}
  3632. res.status = StatusCode::InternalServerError_500;
  3633. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3634. "text/html"); // <= Content-Length still 13 at this point
  3635. });
  3636. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3637. res.set_content("Hello World!\n", "text/plain");
  3638. throw std::runtime_error("abc");
  3639. });
  3640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3641. auto se = detail::scope_exit([&] {
  3642. svr.stop();
  3643. thread.join();
  3644. ASSERT_FALSE(svr.is_running());
  3645. });
  3646. svr.wait_until_ready();
  3647. for (size_t i = 0; i < 10; i++) {
  3648. Client cli(HOST, PORT);
  3649. for (size_t j = 0; j < 100; j++) {
  3650. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3652. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3653. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3654. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3655. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3656. }
  3657. cli.set_keep_alive(true);
  3658. for (size_t j = 0; j < 100; j++) {
  3659. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3661. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3663. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3664. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3665. }
  3666. }
  3667. }
  3668. TEST(ExceptionTest, AndErrorHandler) {
  3669. Server svr;
  3670. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3671. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3672. });
  3673. svr.set_exception_handler(
  3674. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3675. EXPECT_FALSE(ep == nullptr);
  3676. try {
  3677. std::rethrow_exception(ep);
  3678. } catch (std::exception &e) {
  3679. res.set_content(e.what(), "text/html");
  3680. } catch (...) {}
  3681. res.status = StatusCode::InternalServerError_500;
  3682. });
  3683. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3684. throw std::runtime_error("EXCEPTION");
  3685. });
  3686. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3687. res.set_content("ERROR", "text/html");
  3688. res.status = StatusCode::InternalServerError_500;
  3689. });
  3690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3691. auto se = detail::scope_exit([&] {
  3692. svr.stop();
  3693. thread.join();
  3694. ASSERT_FALSE(svr.is_running());
  3695. });
  3696. svr.wait_until_ready();
  3697. Client cli(HOST, PORT);
  3698. {
  3699. auto res = cli.Get("/exception");
  3700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3701. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3702. EXPECT_EQ("EXCEPTION", res->body);
  3703. }
  3704. {
  3705. auto res = cli.Get("/error");
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3708. EXPECT_EQ("ERROR", res->body);
  3709. }
  3710. {
  3711. auto res = cli.Get("/invalid");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3714. EXPECT_EQ("NOT_FOUND", res->body);
  3715. }
  3716. }
  3717. #endif
  3718. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3719. // process_request() wraps only routing() in a try/catch, so an exception from
  3720. // any other user callback used to unwind into the task queue - which does not
  3721. // catch - and terminate the process. Each test below runs the server on a
  3722. // single worker thread: a guard that catches the exception but still loses the
  3723. // thread would otherwise be hidden by a spare worker serving the follow-up
  3724. // request. Note that a regression here aborts the whole test binary rather
  3725. // than failing one test.
  3726. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3727. Server svr;
  3728. svr.new_task_queue = [] { return new ThreadPool(1); };
  3729. std::atomic<int> reported{0};
  3730. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3731. if (err == Error::UserCallbackException) { reported++; }
  3732. });
  3733. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3734. res.set_content_provider(
  3735. 1024, "text/plain",
  3736. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3737. sink.write("hello", 5);
  3738. throw std::runtime_error("from the content provider");
  3739. });
  3740. });
  3741. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3742. res.set_content("ok", "text/plain");
  3743. });
  3744. auto port = svr.bind_to_any_port(HOST);
  3745. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3746. auto se = detail::scope_exit([&] {
  3747. svr.stop();
  3748. listen_thread.join();
  3749. ASSERT_FALSE(svr.is_running());
  3750. });
  3751. svr.wait_until_ready();
  3752. {
  3753. Client cli(HOST, port);
  3754. cli.set_read_timeout(5, 0);
  3755. EXPECT_FALSE(cli.Get("/throw"));
  3756. }
  3757. EXPECT_TRUE(svr.is_running());
  3758. EXPECT_EQ(1, reported.load());
  3759. // A request on a fresh connection is still served.
  3760. {
  3761. Client cli(HOST, port);
  3762. auto res = cli.Get("/ok");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. EXPECT_EQ("ok", res->body);
  3766. }
  3767. }
  3768. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3769. Server svr;
  3770. svr.new_task_queue = [] { return new ThreadPool(1); };
  3771. std::atomic<bool> should_throw{true};
  3772. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3773. res.set_content("hi", "text/plain");
  3774. });
  3775. svr.set_post_routing_handler(
  3776. [&](const Request & /*req*/, Response & /*res*/) {
  3777. if (should_throw) {
  3778. throw std::runtime_error("from the post-routing handler");
  3779. }
  3780. });
  3781. auto port = svr.bind_to_any_port(HOST);
  3782. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3783. auto se = detail::scope_exit([&] {
  3784. svr.stop();
  3785. listen_thread.join();
  3786. ASSERT_FALSE(svr.is_running());
  3787. });
  3788. svr.wait_until_ready();
  3789. {
  3790. Client cli(HOST, port);
  3791. cli.set_read_timeout(5, 0);
  3792. EXPECT_FALSE(cli.Get("/hi"));
  3793. }
  3794. EXPECT_TRUE(svr.is_running());
  3795. should_throw = false;
  3796. {
  3797. Client cli(HOST, port);
  3798. auto res = cli.Get("/hi");
  3799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3800. EXPECT_EQ(StatusCode::OK_200, res->status);
  3801. EXPECT_EQ("hi", res->body);
  3802. }
  3803. }
  3804. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3805. // The guard reports the caught exception through the error logger, which is
  3806. // a user callback too. A logger that throws has to be contained as well, or
  3807. // the process would terminate from inside the catch.
  3808. Server svr;
  3809. svr.new_task_queue = [] { return new ThreadPool(1); };
  3810. std::atomic<int> reported{0};
  3811. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3812. if (err == Error::UserCallbackException) {
  3813. reported++;
  3814. throw std::runtime_error("from the error logger");
  3815. }
  3816. });
  3817. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3818. res.set_content_provider(
  3819. 1024, "text/plain",
  3820. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3821. sink.write("hello", 5);
  3822. throw std::runtime_error("from the content provider");
  3823. });
  3824. });
  3825. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3826. res.set_content("ok", "text/plain");
  3827. });
  3828. auto port = svr.bind_to_any_port(HOST);
  3829. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3830. auto se = detail::scope_exit([&] {
  3831. svr.stop();
  3832. listen_thread.join();
  3833. ASSERT_FALSE(svr.is_running());
  3834. });
  3835. svr.wait_until_ready();
  3836. {
  3837. Client cli(HOST, port);
  3838. cli.set_read_timeout(5, 0);
  3839. EXPECT_FALSE(cli.Get("/throw"));
  3840. }
  3841. EXPECT_TRUE(svr.is_running());
  3842. EXPECT_EQ(1, reported.load());
  3843. {
  3844. Client cli(HOST, port);
  3845. auto res = cli.Get("/ok");
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("ok", res->body);
  3849. }
  3850. }
  3851. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3852. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3853. // so the exception unwinds through the ws::WebSocket object on its way to
  3854. // the guard. None of the HTTP cases above cross that.
  3855. Server svr;
  3856. svr.new_task_queue = [] { return new ThreadPool(1); };
  3857. std::atomic<int> reported{0};
  3858. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3859. if (err == Error::UserCallbackException) { reported++; }
  3860. });
  3861. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3862. throw std::runtime_error("from the WebSocket handler");
  3863. });
  3864. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3865. res.set_content("ok", "text/plain");
  3866. });
  3867. auto port = svr.bind_to_any_port(HOST);
  3868. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3869. auto se = detail::scope_exit([&] {
  3870. svr.stop();
  3871. listen_thread.join();
  3872. ASSERT_FALSE(svr.is_running());
  3873. });
  3874. svr.wait_until_ready();
  3875. {
  3876. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3877. "/ws");
  3878. auto res = client.connect();
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. // The server dropped the connection instead of dying.
  3881. std::string msg;
  3882. EXPECT_FALSE(client.read(msg));
  3883. client.close();
  3884. }
  3885. EXPECT_TRUE(svr.is_running());
  3886. EXPECT_EQ(1, reported.load());
  3887. {
  3888. Client cli(HOST, port);
  3889. auto res = cli.Get("/ok");
  3890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3891. EXPECT_EQ(StatusCode::OK_200, res->status);
  3892. EXPECT_EQ("ok", res->body);
  3893. }
  3894. }
  3895. #ifdef CPPHTTPLIB_SSL_ENABLED
  3896. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3897. // SSLServer::process_and_close_socket() is a separate overload with its own
  3898. // guard, so it is exercised on its own.
  3899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3900. ASSERT_TRUE(svr.is_valid());
  3901. svr.new_task_queue = [] { return new ThreadPool(1); };
  3902. std::atomic<int> reported{0};
  3903. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3904. if (err == Error::UserCallbackException) { reported++; }
  3905. });
  3906. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3907. res.set_content_provider(
  3908. 1024, "text/plain",
  3909. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3910. sink.write("hello", 5);
  3911. throw std::runtime_error("from the content provider");
  3912. });
  3913. });
  3914. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3915. res.set_content("ok", "text/plain");
  3916. });
  3917. auto port = svr.bind_to_any_port(HOST);
  3918. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3919. auto se = detail::scope_exit([&] {
  3920. svr.stop();
  3921. listen_thread.join();
  3922. ASSERT_FALSE(svr.is_running());
  3923. });
  3924. svr.wait_until_ready();
  3925. {
  3926. SSLClient cli(HOST, port);
  3927. cli.enable_server_certificate_verification(false);
  3928. cli.set_read_timeout(5, 0);
  3929. EXPECT_FALSE(cli.Get("/throw"));
  3930. }
  3931. EXPECT_TRUE(svr.is_running());
  3932. EXPECT_EQ(1, reported.load());
  3933. {
  3934. SSLClient cli(HOST, port);
  3935. cli.enable_server_certificate_verification(false);
  3936. auto res = cli.Get("/ok");
  3937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("ok", res->body);
  3940. }
  3941. }
  3942. #endif
  3943. #endif
  3944. TEST(NoContentTest, ContentLength) {
  3945. Server svr;
  3946. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3947. res.status = StatusCode::NoContent_204;
  3948. });
  3949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. thread.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. {
  3957. Client cli(HOST, PORT);
  3958. auto res = cli.Get("/hi");
  3959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3960. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3961. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3962. }
  3963. }
  3964. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3965. #ifdef CPPHTTPLIB_SSL_ENABLED
  3966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3967. ASSERT_TRUE(svr.is_valid());
  3968. #else
  3969. Server svr;
  3970. #endif
  3971. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3972. if (req.path == "/routing_handler") {
  3973. res.set_header("PRE_ROUTING", "on");
  3974. res.set_content("Routing Handler", "text/plain");
  3975. return httplib::Server::HandlerResponse::Handled;
  3976. }
  3977. return httplib::Server::HandlerResponse::Unhandled;
  3978. });
  3979. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3980. res.set_content("Error", "text/html");
  3981. });
  3982. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3983. if (req.path == "/routing_handler") {
  3984. res.set_header("POST_ROUTING", "on");
  3985. }
  3986. });
  3987. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3988. res.set_content("Hello World!\n", "text/plain");
  3989. });
  3990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3991. auto se = detail::scope_exit([&] {
  3992. svr.stop();
  3993. thread.join();
  3994. ASSERT_FALSE(svr.is_running());
  3995. });
  3996. svr.wait_until_ready();
  3997. {
  3998. #ifdef CPPHTTPLIB_SSL_ENABLED
  3999. SSLClient cli(HOST, PORT);
  4000. cli.enable_server_certificate_verification(false);
  4001. #else
  4002. Client cli(HOST, PORT);
  4003. #endif
  4004. auto res = cli.Get("/routing_handler");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::OK_200, res->status);
  4007. EXPECT_EQ("Routing Handler", res->body);
  4008. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4009. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4010. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4011. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4012. }
  4013. {
  4014. #ifdef CPPHTTPLIB_SSL_ENABLED
  4015. SSLClient cli(HOST, PORT);
  4016. cli.enable_server_certificate_verification(false);
  4017. #else
  4018. Client cli(HOST, PORT);
  4019. #endif
  4020. auto res = cli.Get("/hi");
  4021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4022. EXPECT_EQ(StatusCode::OK_200, res->status);
  4023. EXPECT_EQ("Hello World!\n", res->body);
  4024. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4025. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4026. }
  4027. {
  4028. #ifdef CPPHTTPLIB_SSL_ENABLED
  4029. SSLClient cli(HOST, PORT);
  4030. cli.enable_server_certificate_verification(false);
  4031. #else
  4032. Client cli(HOST, PORT);
  4033. #endif
  4034. auto res = cli.Get("/aaa");
  4035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4037. EXPECT_EQ("Error", res->body);
  4038. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4039. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4040. }
  4041. }
  4042. TEST(RequestHandlerTest, PreRequestHandler) {
  4043. auto route_path = "/user/:user";
  4044. Server svr;
  4045. svr.Get("/hi", [](const Request &, Response &res) {
  4046. res.set_content("hi", "text/plain");
  4047. });
  4048. svr.Get(route_path, [](const Request &req, Response &res) {
  4049. res.set_content(req.path_params.at("user"), "text/plain");
  4050. });
  4051. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4052. if (req.matched_route == route_path) {
  4053. auto user = req.path_params.at("user");
  4054. if (user != "john") {
  4055. res.status = StatusCode::Forbidden_403;
  4056. res.set_content("error", "text/html");
  4057. return Server::HandlerResponse::Handled;
  4058. }
  4059. }
  4060. return Server::HandlerResponse::Unhandled;
  4061. });
  4062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4063. auto se = detail::scope_exit([&] {
  4064. svr.stop();
  4065. thread.join();
  4066. ASSERT_FALSE(svr.is_running());
  4067. });
  4068. svr.wait_until_ready();
  4069. Client cli(HOST, PORT);
  4070. {
  4071. auto res = cli.Get("/hi");
  4072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. EXPECT_EQ("hi", res->body);
  4075. }
  4076. {
  4077. auto res = cli.Get("/user/john");
  4078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4079. EXPECT_EQ(StatusCode::OK_200, res->status);
  4080. EXPECT_EQ("john", res->body);
  4081. }
  4082. {
  4083. auto res = cli.Get("/user/invalid-user");
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4086. EXPECT_EQ("error", res->body);
  4087. }
  4088. }
  4089. // The pre-request handler must run before the request body is read, so a
  4090. // rejected request never forces the server to buffer a (potentially large)
  4091. // body. Here the posted body is larger than the payload limit: if the body
  4092. // were read first the server would answer 413, but because the pre-request
  4093. // handler runs first it answers 403 and the body is never read.
  4094. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4095. Server svr;
  4096. svr.set_payload_max_length(8);
  4097. auto handler_ran = false;
  4098. svr.Post("/reject", [&](const Request &req, Response &res) {
  4099. handler_ran = true;
  4100. res.set_content(req.body, "text/plain");
  4101. });
  4102. svr.Post("/accept", [](const Request &req, Response &res) {
  4103. res.set_content(req.body, "text/plain");
  4104. });
  4105. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4106. if (req.matched_route == "/reject") {
  4107. res.status = StatusCode::Forbidden_403;
  4108. res.set_content("denied", "text/plain");
  4109. return Server::HandlerResponse::Handled;
  4110. }
  4111. return Server::HandlerResponse::Unhandled;
  4112. });
  4113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. thread.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. Client cli(HOST, PORT);
  4121. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4122. // rejects with 403 before the body is read, so 413 is never reached.
  4123. {
  4124. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4126. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4127. EXPECT_EQ("denied", res->body);
  4128. EXPECT_FALSE(handler_ran);
  4129. }
  4130. // An approved route still reads the body and enforces the payload limit.
  4131. {
  4132. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4134. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4135. }
  4136. }
  4137. TEST(UserDataTest, BasicOperations) {
  4138. httplib::UserData ud;
  4139. // Initially empty
  4140. EXPECT_FALSE(ud.has("key"));
  4141. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4142. // set and get
  4143. ud.set("key", 42);
  4144. EXPECT_TRUE(ud.has("key"));
  4145. auto *p = ud.get<int>("key");
  4146. ASSERT_NE(nullptr, p);
  4147. EXPECT_EQ(42, *p);
  4148. // Type mismatch → nullptr
  4149. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4150. // Overwrite with different type
  4151. ud.set("key", std::string("hello"));
  4152. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4153. auto *s = ud.get<std::string>("key");
  4154. ASSERT_NE(nullptr, s);
  4155. EXPECT_EQ("hello", *s);
  4156. // erase
  4157. ud.erase("key");
  4158. EXPECT_FALSE(ud.has("key"));
  4159. // clear
  4160. ud.set("a", 1);
  4161. ud.set("b", 2);
  4162. ud.clear();
  4163. EXPECT_FALSE(ud.has("a"));
  4164. EXPECT_FALSE(ud.has("b"));
  4165. }
  4166. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4167. struct AuthCtx {
  4168. std::string user_id;
  4169. };
  4170. Server svr;
  4171. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4172. res.user_data.set("auth", AuthCtx{"alice"});
  4173. return Server::HandlerResponse::Unhandled;
  4174. });
  4175. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4176. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4177. ASSERT_NE(nullptr, ctx);
  4178. res.set_content("Hello " + ctx->user_id, "text/plain");
  4179. });
  4180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4181. auto se = detail::scope_exit([&] {
  4182. svr.stop();
  4183. thread.join();
  4184. ASSERT_FALSE(svr.is_running());
  4185. });
  4186. svr.wait_until_ready();
  4187. Client cli(HOST, PORT);
  4188. auto res = cli.Get("/me");
  4189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4190. EXPECT_EQ(StatusCode::OK_200, res->status);
  4191. EXPECT_EQ("Hello alice", res->body);
  4192. }
  4193. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4194. struct RoleCtx {
  4195. std::string role;
  4196. };
  4197. Server svr;
  4198. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4199. res.user_data.set("role", RoleCtx{"admin"});
  4200. return Server::HandlerResponse::Unhandled;
  4201. });
  4202. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4203. auto *ctx = res.user_data.get<RoleCtx>("role");
  4204. ASSERT_NE(nullptr, ctx);
  4205. res.set_content(ctx->role, "text/plain");
  4206. });
  4207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4208. auto se = detail::scope_exit([&] {
  4209. svr.stop();
  4210. thread.join();
  4211. ASSERT_FALSE(svr.is_running());
  4212. });
  4213. svr.wait_until_ready();
  4214. Client cli(HOST, PORT);
  4215. auto res = cli.Get("/role");
  4216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4217. EXPECT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ("admin", res->body);
  4219. }
  4220. TEST(InvalidFormatTest, StatusCode) {
  4221. Server svr;
  4222. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4223. res.set_content("Hello World!\n", "text/plain");
  4224. res.status = 9999; // Status should be a three-digit code...
  4225. });
  4226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. {
  4234. Client cli(HOST, PORT);
  4235. auto res = cli.Get("/hi");
  4236. ASSERT_FALSE(res);
  4237. }
  4238. }
  4239. TEST(URLFragmentTest, WithFragment) {
  4240. Server svr;
  4241. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4242. EXPECT_TRUE(req.target == "/hi");
  4243. });
  4244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4245. auto se = detail::scope_exit([&] {
  4246. svr.stop();
  4247. thread.join();
  4248. ASSERT_FALSE(svr.is_running());
  4249. });
  4250. svr.wait_until_ready();
  4251. {
  4252. Client cli(HOST, PORT);
  4253. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4254. EXPECT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::OK_200, res->status);
  4256. res = cli.Get("/hi%23key1=val1=key2=val2");
  4257. EXPECT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4259. }
  4260. }
  4261. TEST(HeaderWriter, SetHeaderWriter) {
  4262. Server svr;
  4263. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4264. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4265. return detail::write_headers(strm, hdrs);
  4266. });
  4267. svr.Get("/hi", [](const Request &req, Response &res) {
  4268. auto it = req.headers.find("CustomClientHeader");
  4269. EXPECT_TRUE(it != req.headers.end());
  4270. EXPECT_EQ(it->second, "CustomClientValue");
  4271. res.set_content("Hello World!\n", "text/plain");
  4272. });
  4273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4274. auto se = detail::scope_exit([&] {
  4275. svr.stop();
  4276. thread.join();
  4277. ASSERT_FALSE(svr.is_running());
  4278. });
  4279. svr.wait_until_ready();
  4280. {
  4281. Client cli(HOST, PORT);
  4282. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4283. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4284. return detail::write_headers(strm, hdrs);
  4285. });
  4286. auto res = cli.Get("/hi");
  4287. EXPECT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::OK_200, res->status);
  4289. auto it = res->headers.find("CustomServerHeader");
  4290. EXPECT_TRUE(it != res->headers.end());
  4291. EXPECT_EQ(it->second, "CustomServerValue");
  4292. }
  4293. }
  4294. class ServerTest : public ::testing::Test {
  4295. protected:
  4296. ServerTest()
  4297. : cli_(HOST, PORT)
  4298. #ifdef CPPHTTPLIB_SSL_ENABLED
  4299. ,
  4300. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4301. #endif
  4302. {
  4303. #ifdef CPPHTTPLIB_SSL_ENABLED
  4304. cli_.enable_server_certificate_verification(false);
  4305. #endif
  4306. // Allow LARGE_DATA (100MB) responses
  4307. cli_.set_payload_max_length(200 * 1024 * 1024);
  4308. }
  4309. virtual void SetUp() {
  4310. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4311. svr_.set_payload_max_length(200 * 1024 * 1024);
  4312. svr_.set_mount_point("/", "./www");
  4313. svr_.set_mount_point("/mount", "./www2");
  4314. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4315. svr_.Get("/hi",
  4316. [&](const Request & /*req*/, Response &res) {
  4317. res.set_content("Hello World!", "text/plain");
  4318. })
  4319. .Get("/file_content",
  4320. [&](const Request & /*req*/, Response &res) {
  4321. res.set_file_content("./www/dir/test.html");
  4322. })
  4323. .Get("/file_content_with_content_type",
  4324. [&](const Request & /*req*/, Response &res) {
  4325. res.set_file_content("./www/file", "text/plain");
  4326. })
  4327. .Get("/invalid_file_content",
  4328. [&](const Request & /*req*/, Response &res) {
  4329. res.set_file_content("./www/dir/invalid_file_path");
  4330. })
  4331. .Get("/http_response_splitting",
  4332. [&](const Request & /*req*/, Response &res) {
  4333. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4334. EXPECT_EQ(0U, res.headers.size());
  4335. EXPECT_FALSE(res.has_header("a"));
  4336. res.set_header("a", "1\nSet-Cookie: a=1");
  4337. EXPECT_EQ(0U, res.headers.size());
  4338. EXPECT_FALSE(res.has_header("a"));
  4339. res.set_header("a", "1\rSet-Cookie: a=1");
  4340. EXPECT_EQ(0U, res.headers.size());
  4341. EXPECT_FALSE(res.has_header("a"));
  4342. res.set_header("a\r\nb", "0");
  4343. EXPECT_EQ(0U, res.headers.size());
  4344. EXPECT_FALSE(res.has_header("a"));
  4345. res.set_header("a\rb", "0");
  4346. EXPECT_EQ(0U, res.headers.size());
  4347. EXPECT_FALSE(res.has_header("a"));
  4348. res.set_header("a\nb", "0");
  4349. EXPECT_EQ(0U, res.headers.size());
  4350. EXPECT_FALSE(res.has_header("a"));
  4351. res.set_redirect("1\r\nSet-Cookie: a=1");
  4352. EXPECT_EQ(0U, res.headers.size());
  4353. EXPECT_FALSE(res.has_header("Location"));
  4354. })
  4355. .Get("/slow",
  4356. [&](const Request & /*req*/, Response &res) {
  4357. std::this_thread::sleep_for(std::chrono::seconds(4));
  4358. res.set_content("slow", "text/plain");
  4359. })
  4360. #if 0
  4361. .Post("/slowpost",
  4362. [&](const Request & /*req*/, Response &res) {
  4363. std::this_thread::sleep_for(std::chrono::seconds(2));
  4364. res.set_content("slow", "text/plain");
  4365. })
  4366. #endif
  4367. .Get("/remote_addr",
  4368. [&](const Request &req, Response &res) {
  4369. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4370. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4371. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4372. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4373. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4374. #endif
  4375. res.set_content(req.remote_addr, "text/plain");
  4376. })
  4377. .Get("/local_addr",
  4378. [&](const Request &req, Response &res) {
  4379. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4380. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4381. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4382. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4383. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4384. #endif
  4385. auto local_addr = req.local_addr;
  4386. auto local_port = std::to_string(req.local_port);
  4387. res.set_content(local_addr.append(":").append(local_port),
  4388. "text/plain");
  4389. })
  4390. .Get("/endwith%",
  4391. [&](const Request & /*req*/, Response &res) {
  4392. res.set_content("Hello World!", "text/plain");
  4393. })
  4394. .Get("/a\\+\\+b",
  4395. [&](const Request &req, Response &res) {
  4396. ASSERT_TRUE(req.has_param("a +b"));
  4397. auto val = req.get_param_value("a +b");
  4398. res.set_content(val, "text/plain");
  4399. })
  4400. .Get("/", [&](const Request & /*req*/,
  4401. Response &res) { res.set_redirect("/hi"); })
  4402. .Post("/1",
  4403. [](const Request & /*req*/, Response &res) {
  4404. res.set_redirect("/2", StatusCode::SeeOther_303);
  4405. })
  4406. .Get("/2",
  4407. [](const Request & /*req*/, Response &res) {
  4408. res.set_content("redirected.", "text/plain");
  4409. res.status = StatusCode::OK_200;
  4410. })
  4411. .Post("/person",
  4412. [&](const Request &req, Response &res) {
  4413. if (req.has_param("name") && req.has_param("note")) {
  4414. persons_[req.get_param_value("name")] =
  4415. req.get_param_value("note");
  4416. } else {
  4417. res.status = StatusCode::BadRequest_400;
  4418. }
  4419. })
  4420. .Put("/person",
  4421. [&](const Request &req, Response &res) {
  4422. if (req.has_param("name") && req.has_param("note")) {
  4423. persons_[req.get_param_value("name")] =
  4424. req.get_param_value("note");
  4425. } else {
  4426. res.status = StatusCode::BadRequest_400;
  4427. }
  4428. })
  4429. .Get("/person/(.*)",
  4430. [&](const Request &req, Response &res) {
  4431. string name = req.matches[1];
  4432. if (persons_.find(name) != persons_.end()) {
  4433. auto note = persons_[name];
  4434. res.set_content(note, "text/plain");
  4435. } else {
  4436. res.status = StatusCode::NotFound_404;
  4437. }
  4438. })
  4439. .Delete("/person",
  4440. [&](const Request &req, Response &res) {
  4441. if (req.has_param("name")) {
  4442. string name = req.get_param_value("name");
  4443. if (persons_.find(name) != persons_.end()) {
  4444. persons_.erase(name);
  4445. res.set_content("DELETED", "text/plain");
  4446. } else {
  4447. res.status = StatusCode::NotFound_404;
  4448. }
  4449. } else {
  4450. res.status = StatusCode::BadRequest_400;
  4451. }
  4452. })
  4453. .Post("/x-www-form-urlencoded-json",
  4454. [&](const Request &req, Response &res) {
  4455. auto json = req.get_param_value("json");
  4456. ASSERT_EQ(JSON_DATA, json);
  4457. res.set_content(json, "appliation/json");
  4458. res.status = StatusCode::OK_200;
  4459. })
  4460. .Get("/streamed-chunked",
  4461. [&](const Request & /*req*/, Response &res) {
  4462. res.set_chunked_content_provider(
  4463. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4464. sink.os << "123";
  4465. sink.os << "456";
  4466. sink.os << "789";
  4467. sink.done();
  4468. return true;
  4469. });
  4470. })
  4471. .Get("/streamed-chunked-with-prohibited-trailer",
  4472. [&](const Request & /*req*/, Response &res) {
  4473. auto i = new int(0);
  4474. // Declare both a prohibited trailer (Content-Length) and an
  4475. // allowed one
  4476. res.set_header("Trailer", "Content-Length, X-Allowed");
  4477. res.set_chunked_content_provider(
  4478. "text/plain",
  4479. [i](size_t /*offset*/, DataSink &sink) {
  4480. switch (*i) {
  4481. case 0: sink.os << "123"; break;
  4482. case 1: sink.os << "456"; break;
  4483. case 2: sink.os << "789"; break;
  4484. case 3: {
  4485. sink.done_with_trailer(
  4486. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4487. } break;
  4488. }
  4489. (*i)++;
  4490. return true;
  4491. },
  4492. [i](bool success) {
  4493. EXPECT_TRUE(success);
  4494. delete i;
  4495. });
  4496. })
  4497. .Get("/streamed-chunked2",
  4498. [&](const Request & /*req*/, Response &res) {
  4499. auto i = new int(0);
  4500. res.set_chunked_content_provider(
  4501. "text/plain",
  4502. [i](size_t /*offset*/, DataSink &sink) {
  4503. switch (*i) {
  4504. case 0: sink.os << "123"; break;
  4505. case 1: sink.os << "456"; break;
  4506. case 2: sink.os << "789"; break;
  4507. case 3: sink.done(); break;
  4508. }
  4509. (*i)++;
  4510. return true;
  4511. },
  4512. [i](bool success) {
  4513. EXPECT_TRUE(success);
  4514. delete i;
  4515. });
  4516. })
  4517. .Get("/streamed-chunked-with-trailer",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. auto i = new int(0);
  4520. res.set_header("Trailer", "Dummy1, Dummy2");
  4521. res.set_chunked_content_provider(
  4522. "text/plain",
  4523. [i](size_t /*offset*/, DataSink &sink) {
  4524. switch (*i) {
  4525. case 0: sink.os << "123"; break;
  4526. case 1: sink.os << "456"; break;
  4527. case 2: sink.os << "789"; break;
  4528. case 3: {
  4529. sink.done_with_trailer(
  4530. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4531. } break;
  4532. }
  4533. (*i)++;
  4534. return true;
  4535. },
  4536. [i](bool success) {
  4537. EXPECT_TRUE(success);
  4538. delete i;
  4539. });
  4540. })
  4541. .Get("/streamed",
  4542. [&](const Request & /*req*/, Response &res) {
  4543. res.set_content_provider(
  4544. 6, "text/plain",
  4545. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4546. sink.os << (offset < 3 ? "a" : "b");
  4547. return true;
  4548. });
  4549. })
  4550. .Get("/streamed-without-length",
  4551. [&](const Request & /*req*/, Response &res) {
  4552. auto data = new std::string("abcdefg");
  4553. res.set_content_provider(
  4554. "text/plain",
  4555. [data](size_t offset, DataSink &sink) {
  4556. if (offset < data->size()) {
  4557. sink.os << data->substr(offset);
  4558. }
  4559. sink.done();
  4560. return true;
  4561. },
  4562. [data](bool success) {
  4563. EXPECT_TRUE(success);
  4564. delete data;
  4565. });
  4566. })
  4567. .Get("/streamed-with-range",
  4568. [&](const Request &req, Response &res) {
  4569. auto data = new std::string("abcdefg");
  4570. // An explicit status keeps the server from picking the 206 it
  4571. // would otherwise choose for a ranged request, so the response
  4572. // is not a partial representation.
  4573. auto status = req.get_param_value("status");
  4574. if (status == "200") {
  4575. res.status = StatusCode::OK_200;
  4576. } else if (status == "403") {
  4577. res.status = StatusCode::Forbidden_403;
  4578. }
  4579. res.set_content_provider(
  4580. data->size(), "text/plain",
  4581. [data](size_t offset, size_t length, DataSink &sink) {
  4582. size_t DATA_CHUNK_SIZE = 4;
  4583. const auto &d = *data;
  4584. auto out_len =
  4585. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4586. auto ret =
  4587. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4588. EXPECT_TRUE(ret);
  4589. return true;
  4590. },
  4591. [data, &req](bool success) {
  4592. EXPECT_EQ(success, !req.has_param("error"));
  4593. delete data;
  4594. });
  4595. })
  4596. .Get("/streamed-cancel",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. res.set_content_provider(
  4599. size_t(-1), "text/plain",
  4600. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4601. sink.os << "data_chunk";
  4602. return true;
  4603. });
  4604. })
  4605. .Get("/regex-with-delimiter",
  4606. [&](const Request &req, Response & /*res*/) {
  4607. ASSERT_TRUE(req.has_param("key"));
  4608. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4609. })
  4610. .Get("/with-range",
  4611. [&](const Request & /*req*/, Response &res) {
  4612. res.set_content("abcdefg", "text/plain");
  4613. })
  4614. .Get("/test-start-time",
  4615. [&](const Request &req, Response & /*res*/) {
  4616. EXPECT_NE(req.start_time_,
  4617. std::chrono::steady_clock::time_point::min());
  4618. })
  4619. .Get("/with-range-customized-response",
  4620. [&](const Request & /*req*/, Response &res) {
  4621. res.status = StatusCode::BadRequest_400;
  4622. res.set_content(JSON_DATA, "application/json");
  4623. })
  4624. .Post("/chunked",
  4625. [&](const Request &req, Response & /*res*/) {
  4626. EXPECT_EQ(req.body, "dechunked post body");
  4627. })
  4628. .Post("/large-chunked",
  4629. [&](const Request &req, Response & /*res*/) {
  4630. std::string expected(6 * 30 * 1024u, 'a');
  4631. EXPECT_EQ(req.body, expected);
  4632. })
  4633. .Post("/multipart",
  4634. [&](const Request &req, Response & /*res*/) {
  4635. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4636. req.form.get_field_count("text2") +
  4637. req.form.get_field_count("file3") +
  4638. req.form.get_field_count("file4"));
  4639. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4640. req.form.get_file_count("file2"));
  4641. ASSERT_TRUE(!req.form.has_file("???"));
  4642. ASSERT_TRUE(!req.form.has_field("???"));
  4643. ASSERT_TRUE(req.body.empty());
  4644. {
  4645. const auto &text = req.form.get_field("text1");
  4646. EXPECT_EQ("text default", text);
  4647. }
  4648. {
  4649. const auto &text = req.form.get_field("text2");
  4650. EXPECT_EQ("aωb", text);
  4651. }
  4652. {
  4653. const auto &file = req.form.get_file("file1");
  4654. EXPECT_EQ("hello.txt", file.filename);
  4655. EXPECT_EQ("text/plain", file.content_type);
  4656. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4657. }
  4658. {
  4659. const auto &file = req.form.get_file("file2");
  4660. EXPECT_EQ("world.json", file.filename);
  4661. EXPECT_EQ("application/json", file.content_type);
  4662. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4663. }
  4664. {
  4665. const auto &text = req.form.get_field("file3");
  4666. EXPECT_EQ(0u, text.size());
  4667. }
  4668. {
  4669. const auto &text = req.form.get_field("file4");
  4670. EXPECT_EQ(0u, text.size());
  4671. }
  4672. })
  4673. .Post("/multipart/multi_file_values",
  4674. [&](const Request &req, Response & /*res*/) {
  4675. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4676. req.form.get_field_count("multi_text1"));
  4677. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4678. ASSERT_TRUE(!req.form.has_file("???"));
  4679. ASSERT_TRUE(!req.form.has_field("???"));
  4680. ASSERT_TRUE(req.body.empty());
  4681. {
  4682. const auto &text = req.form.get_field("text");
  4683. EXPECT_EQ("default text", text);
  4684. }
  4685. {
  4686. const auto &text1_values = req.form.get_fields("multi_text1");
  4687. EXPECT_EQ(2u, text1_values.size());
  4688. EXPECT_EQ("aaaaa", text1_values[0]);
  4689. EXPECT_EQ("bbbbb", text1_values[1]);
  4690. }
  4691. {
  4692. const auto &file1_values = req.form.get_files("multi_file1");
  4693. EXPECT_EQ(2u, file1_values.size());
  4694. auto file1 = file1_values[0];
  4695. EXPECT_EQ(file1.filename, "hello.txt");
  4696. EXPECT_EQ(file1.content_type, "text/plain");
  4697. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4698. auto file2 = file1_values[1];
  4699. EXPECT_EQ(file2.filename, "world.json");
  4700. EXPECT_EQ(file2.content_type, "application/json");
  4701. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4702. }
  4703. })
  4704. .Post("/empty",
  4705. [&](const Request &req, Response &res) {
  4706. EXPECT_EQ(req.body, "");
  4707. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4708. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4709. res.set_content("empty", "text/plain");
  4710. })
  4711. .Post("/empty-no-content-type",
  4712. [&](const Request &req, Response &res) {
  4713. EXPECT_EQ(req.body, "");
  4714. EXPECT_FALSE(req.has_header("Content-Type"));
  4715. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4716. res.set_content("empty-no-content-type", "text/plain");
  4717. })
  4718. .Post("/path-only",
  4719. [&](const Request &req, Response &res) {
  4720. EXPECT_EQ(req.body, "");
  4721. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4723. res.set_content("path-only", "text/plain");
  4724. })
  4725. .Post("/path-headers-only",
  4726. [&](const Request &req, Response &res) {
  4727. EXPECT_EQ(req.body, "");
  4728. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4729. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4730. EXPECT_EQ("world", req.get_header_value("hello"));
  4731. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4732. res.set_content("path-headers-only", "text/plain");
  4733. })
  4734. .Post("/post-large",
  4735. [&](const Request &req, Response &res) {
  4736. EXPECT_EQ(req.body, LARGE_DATA);
  4737. res.set_content(req.body, "text/plain");
  4738. })
  4739. .Post("/post-loopback",
  4740. [&](const Request &, Response &res,
  4741. ContentReader const &content_reader) {
  4742. std::string body;
  4743. content_reader([&](const char *data, size_t data_length) {
  4744. body.append(data, data_length);
  4745. return true;
  4746. });
  4747. res.set_content(body, "text/plain");
  4748. })
  4749. .Put("/put-loopback",
  4750. [&](const Request &, Response &res,
  4751. ContentReader const &content_reader) {
  4752. std::string body;
  4753. content_reader([&](const char *data, size_t data_length) {
  4754. body.append(data, data_length);
  4755. return true;
  4756. });
  4757. res.set_content(body, "text/plain");
  4758. })
  4759. .Patch("/patch-loopback",
  4760. [&](const Request &, Response &res,
  4761. ContentReader const &content_reader) {
  4762. std::string body;
  4763. content_reader([&](const char *data, size_t data_length) {
  4764. body.append(data, data_length);
  4765. return true;
  4766. });
  4767. res.set_content(body, "text/plain");
  4768. })
  4769. .Put("/empty-no-content-type",
  4770. [&](const Request &req, Response &res) {
  4771. EXPECT_EQ(req.body, "");
  4772. EXPECT_FALSE(req.has_header("Content-Type"));
  4773. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4774. res.set_content("empty-no-content-type", "text/plain");
  4775. })
  4776. .Put("/put",
  4777. [&](const Request &req, Response &res) {
  4778. EXPECT_EQ(req.body, "PUT");
  4779. res.set_content(req.body, "text/plain");
  4780. })
  4781. .Put("/put-large",
  4782. [&](const Request &req, Response &res) {
  4783. EXPECT_EQ(req.body, LARGE_DATA);
  4784. res.set_content(req.body, "text/plain");
  4785. })
  4786. .Patch("/patch",
  4787. [&](const Request &req, Response &res) {
  4788. EXPECT_EQ(req.body, "PATCH");
  4789. res.set_content(req.body, "text/plain");
  4790. })
  4791. .Delete("/delete",
  4792. [&](const Request & /*req*/, Response &res) {
  4793. res.set_content("DELETE", "text/plain");
  4794. })
  4795. .Delete("/delete-body",
  4796. [&](const Request &req, Response &res) {
  4797. EXPECT_EQ(req.body, "content");
  4798. res.set_content(req.body, "text/plain");
  4799. })
  4800. .Options(R"(\*)",
  4801. [&](const Request & /*req*/, Response &res) {
  4802. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4803. })
  4804. .CustomRoute("PROPFIND", "/dav/:id",
  4805. [&](const Request &req, Response &res) {
  4806. res.set_header("x-body-size",
  4807. std::to_string(req.body.size()));
  4808. res.set_header("x-matched-route", req.matched_route);
  4809. res.set_header("x-dav-id", req.path_params.at("id"));
  4810. res.status = StatusCode::MultiStatus_207;
  4811. res.set_content(req.body, "application/xml");
  4812. })
  4813. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4814. [&](const Request &req, Response &res) {
  4815. res.set_header("x-dav-match", req.matches[1]);
  4816. res.status = StatusCode::MultiStatus_207;
  4817. })
  4818. .CustomRoute("MKCOL", "/dav-mkcol",
  4819. [&](const Request &req, Response &res) {
  4820. EXPECT_TRUE(req.body.empty());
  4821. res.status = StatusCode::Created_201;
  4822. })
  4823. .CustomRoute(
  4824. "REPORT", "/dav-report",
  4825. [&](const Request & /*req*/, Response &res,
  4826. const ContentReader &content_reader) {
  4827. std::string body;
  4828. content_reader([&](const char *data, size_t data_length) {
  4829. body.append(data, data_length);
  4830. return true;
  4831. });
  4832. res.set_header("x-body-size", std::to_string(body.size()));
  4833. res.status = StatusCode::MultiStatus_207;
  4834. res.set_content(body, "application/xml");
  4835. })
  4836. .Get("/request-target",
  4837. [&](const Request &req, Response & /*res*/) {
  4838. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4839. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4840. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4841. })
  4842. .Get("/long-query-value",
  4843. [&](const Request &req, Response & /*res*/) {
  4844. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4845. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4846. })
  4847. .Get("/too-long-query-value",
  4848. [&](const Request &req, Response & /*res*/) {
  4849. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4850. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4851. })
  4852. .Get("/array-param",
  4853. [&](const Request &req, Response & /*res*/) {
  4854. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4855. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4856. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4857. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4858. })
  4859. .Get("/array-param-values",
  4860. [&](const Request &req, Response & /*res*/) {
  4861. auto values = req.get_param_values("array");
  4862. EXPECT_EQ(3u, values.size());
  4863. EXPECT_EQ("value1", values[0]);
  4864. EXPECT_EQ("value2", values[1]);
  4865. EXPECT_EQ("value3", values[2]);
  4866. auto empty = req.get_param_values("nonexistent");
  4867. EXPECT_TRUE(empty.empty());
  4868. })
  4869. .Post("/validate-no-multiple-headers",
  4870. [&](const Request &req, Response & /*res*/) {
  4871. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4872. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4873. })
  4874. .Post("/content_receiver",
  4875. [&](const Request &req, Response &res,
  4876. const ContentReader &content_reader) {
  4877. if (req.is_multipart_form_data()) {
  4878. std::vector<FormData> items;
  4879. content_reader(
  4880. [&](const FormData &file) {
  4881. items.push_back(file);
  4882. return true;
  4883. },
  4884. [&](const char *data, size_t data_length) {
  4885. items.back().content.append(data, data_length);
  4886. return true;
  4887. });
  4888. EXPECT_EQ(5u, items.size());
  4889. {
  4890. const auto &file = get_file_value(items, "text1");
  4891. EXPECT_TRUE(file.filename.empty());
  4892. EXPECT_EQ("text default", file.content);
  4893. }
  4894. {
  4895. const auto &file = get_file_value(items, "text2");
  4896. EXPECT_TRUE(file.filename.empty());
  4897. EXPECT_EQ("aωb", file.content);
  4898. }
  4899. {
  4900. const auto &file = get_file_value(items, "file1");
  4901. EXPECT_EQ("hello.txt", file.filename);
  4902. EXPECT_EQ("text/plain", file.content_type);
  4903. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4904. }
  4905. {
  4906. const auto &file = get_file_value(items, "file2");
  4907. EXPECT_EQ("world.json", file.filename);
  4908. EXPECT_EQ("application/json", file.content_type);
  4909. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4910. }
  4911. {
  4912. const auto &file = get_file_value(items, "file3");
  4913. EXPECT_TRUE(file.filename.empty());
  4914. EXPECT_EQ("application/octet-stream", file.content_type);
  4915. EXPECT_EQ(0u, file.content.size());
  4916. }
  4917. } else {
  4918. std::string body;
  4919. content_reader([&](const char *data, size_t data_length) {
  4920. EXPECT_EQ(7U, data_length);
  4921. body.append(data, data_length);
  4922. return true;
  4923. });
  4924. EXPECT_EQ(body, "content");
  4925. res.set_content(body, "text/plain");
  4926. }
  4927. })
  4928. .Put("/content_receiver",
  4929. [&](const Request & /*req*/, Response &res,
  4930. const ContentReader &content_reader) {
  4931. std::string body;
  4932. content_reader([&](const char *data, size_t data_length) {
  4933. body.append(data, data_length);
  4934. return true;
  4935. });
  4936. EXPECT_EQ(body, "content");
  4937. res.set_content(body, "text/plain");
  4938. })
  4939. .Patch("/content_receiver",
  4940. [&](const Request & /*req*/, Response &res,
  4941. const ContentReader &content_reader) {
  4942. std::string body;
  4943. content_reader([&](const char *data, size_t data_length) {
  4944. body.append(data, data_length);
  4945. return true;
  4946. });
  4947. EXPECT_EQ(body, "content");
  4948. res.set_content(body, "text/plain");
  4949. })
  4950. .Post("/query-string-and-body",
  4951. [&](const Request &req, Response & /*res*/) {
  4952. ASSERT_TRUE(req.has_param("key"));
  4953. EXPECT_EQ(req.get_param_value("key"), "value");
  4954. EXPECT_EQ(req.body, "content");
  4955. })
  4956. .Get("/last-request",
  4957. [&](const Request &req, Response & /*res*/) {
  4958. EXPECT_EQ("close", req.get_header_value("Connection"));
  4959. })
  4960. .Get(R"(/redirect/(\d+))",
  4961. [&](const Request &req, Response &res) {
  4962. auto num = std::stoi(req.matches[1]) + 1;
  4963. std::string url = "/redirect/" + std::to_string(num);
  4964. res.set_redirect(url);
  4965. })
  4966. .Post("/binary",
  4967. [&](const Request &req, Response &res) {
  4968. EXPECT_EQ(4U, req.body.size());
  4969. EXPECT_EQ("application/octet-stream",
  4970. req.get_header_value("Content-Type"));
  4971. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4972. res.set_content(req.body, "application/octet-stream");
  4973. })
  4974. .Put("/binary",
  4975. [&](const Request &req, Response &res) {
  4976. EXPECT_EQ(4U, req.body.size());
  4977. EXPECT_EQ("application/octet-stream",
  4978. req.get_header_value("Content-Type"));
  4979. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4980. res.set_content(req.body, "application/octet-stream");
  4981. })
  4982. .Patch("/binary",
  4983. [&](const Request &req, Response &res) {
  4984. EXPECT_EQ(4U, req.body.size());
  4985. EXPECT_EQ("application/octet-stream",
  4986. req.get_header_value("Content-Type"));
  4987. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4988. res.set_content(req.body, "application/octet-stream");
  4989. })
  4990. .Delete("/binary",
  4991. [&](const Request &req, Response &res) {
  4992. EXPECT_EQ(4U, req.body.size());
  4993. EXPECT_EQ("application/octet-stream",
  4994. req.get_header_value("Content-Type"));
  4995. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4996. res.set_content(req.body, "application/octet-stream");
  4997. })
  4998. .Get("/issue1772",
  4999. [&](const Request & /*req*/, Response &res) {
  5000. res.status = 401;
  5001. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5002. })
  5003. .Delete("/issue609",
  5004. [](const httplib::Request &, httplib::Response &res,
  5005. const httplib::ContentReader &) {
  5006. res.set_content("ok", "text/plain");
  5007. })
  5008. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5009. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5010. .Get("/compress",
  5011. [&](const Request & /*req*/, Response &res) {
  5012. res.set_content(
  5013. "12345678901234567890123456789012345678901234567890123456789"
  5014. "01234567890123456789012345678901234567890",
  5015. "text/plain");
  5016. })
  5017. .Get("/compress-with-charset",
  5018. [&](const Request & /*req*/, Response &res) {
  5019. res.set_content(
  5020. "12345678901234567890123456789012345678901234567890123456789"
  5021. "01234567890123456789012345678901234567890",
  5022. "application/json; charset=utf-8");
  5023. })
  5024. .Get("/nocompress",
  5025. [&](const Request & /*req*/, Response &res) {
  5026. res.set_content(
  5027. "12345678901234567890123456789012345678901234567890123456789"
  5028. "01234567890123456789012345678901234567890",
  5029. "application/octet-stream");
  5030. })
  5031. .Post("/compress-multipart",
  5032. [&](const Request &req, Response & /*res*/) {
  5033. EXPECT_EQ(2u, req.form.fields.size());
  5034. ASSERT_TRUE(!req.form.has_field("???"));
  5035. {
  5036. const auto &text = req.form.get_field("key1");
  5037. EXPECT_EQ("test", text);
  5038. }
  5039. {
  5040. const auto &text = req.form.get_field("key2");
  5041. EXPECT_EQ("--abcdefg123", text);
  5042. }
  5043. })
  5044. #endif
  5045. ;
  5046. persons_["john"] = "programmer";
  5047. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5048. svr_.wait_until_ready();
  5049. }
  5050. virtual void TearDown() {
  5051. svr_.stop();
  5052. if (!request_threads_.empty()) {
  5053. std::this_thread::sleep_for(std::chrono::seconds(1));
  5054. for (auto &t : request_threads_) {
  5055. t.join();
  5056. }
  5057. }
  5058. t_.join();
  5059. }
  5060. map<string, string> persons_;
  5061. #ifdef CPPHTTPLIB_SSL_ENABLED
  5062. SSLClient cli_;
  5063. SSLServer svr_;
  5064. #else
  5065. Client cli_;
  5066. Server svr_;
  5067. #endif
  5068. thread t_;
  5069. std::vector<thread> request_threads_;
  5070. };
  5071. TEST_F(ServerTest, GetMethod200) {
  5072. auto res = cli_.Get("/hi");
  5073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5074. EXPECT_EQ("HTTP/1.1", res->version);
  5075. EXPECT_EQ(StatusCode::OK_200, res->status);
  5076. EXPECT_EQ("OK", res->reason);
  5077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5078. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5079. EXPECT_EQ("Hello World!", res->body);
  5080. }
  5081. TEST_F(ServerTest, GetEmptyFile) {
  5082. auto res = cli_.Get("/empty_file");
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::OK_200, res->status);
  5085. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5086. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5087. EXPECT_EQ("", res->body);
  5088. }
  5089. TEST_F(ServerTest, GetFileContent) {
  5090. auto res = cli_.Get("/file_content");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5094. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5095. EXPECT_EQ("test.html", res->body);
  5096. }
  5097. TEST_F(ServerTest, GetFileContentWithRange) {
  5098. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5101. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5102. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5103. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5104. EXPECT_EQ("est", res->body);
  5105. }
  5106. TEST_F(ServerTest, GetFileContentWithContentType) {
  5107. auto res = cli_.Get("/file_content_with_content_type");
  5108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5111. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5112. EXPECT_EQ("file\n", res->body);
  5113. }
  5114. TEST_F(ServerTest, GetInvalidFileContent) {
  5115. auto res = cli_.Get("/invalid_file_content");
  5116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5118. }
  5119. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5120. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5122. EXPECT_EQ("HTTP/1.1", res->version);
  5123. EXPECT_EQ(StatusCode::OK_200, res->status);
  5124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5125. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5126. EXPECT_EQ("Hello World!", res->body);
  5127. }
  5128. TEST_F(ServerTest, GetMethod302) {
  5129. auto res = cli_.Get("/");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. EXPECT_EQ(StatusCode::Found_302, res->status);
  5132. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5133. }
  5134. TEST_F(ServerTest, GetMethod302Redirect) {
  5135. cli_.set_follow_location(true);
  5136. auto res = cli_.Get("/");
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("Hello World!", res->body);
  5140. EXPECT_EQ("/hi", res->location);
  5141. }
  5142. TEST_F(ServerTest, GetMethod404) {
  5143. auto res = cli_.Get("/invalid");
  5144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5146. }
  5147. TEST_F(ServerTest, HeadMethod200) {
  5148. auto res = cli_.Head("/hi");
  5149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5152. EXPECT_TRUE(res->body.empty());
  5153. }
  5154. TEST_F(ServerTest, HeadMethod200Static) {
  5155. auto res = cli_.Head("/mount/dir/index.html");
  5156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5157. EXPECT_EQ(StatusCode::OK_200, res->status);
  5158. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5159. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5160. EXPECT_TRUE(res->body.empty());
  5161. }
  5162. TEST_F(ServerTest, HeadMethod404) {
  5163. auto res = cli_.Head("/invalid");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5166. EXPECT_TRUE(res->body.empty());
  5167. }
  5168. TEST_F(ServerTest, GetMethodPersonJohn) {
  5169. auto res = cli_.Get("/person/john");
  5170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5173. EXPECT_EQ("programmer", res->body);
  5174. }
  5175. TEST_F(ServerTest, PostMethod1) {
  5176. auto res = cli_.Get("/person/john1");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5179. res = cli_.Post("/person", "name=john1&note=coder",
  5180. "application/x-www-form-urlencoded");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. ASSERT_EQ(StatusCode::OK_200, res->status);
  5183. res = cli_.Get("/person/john1");
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. ASSERT_EQ(StatusCode::OK_200, res->status);
  5186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5187. ASSERT_EQ("coder", res->body);
  5188. }
  5189. TEST_F(ServerTest, PostMethod2) {
  5190. auto res = cli_.Get("/person/john2");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5193. Params params;
  5194. params.emplace("name", "john2");
  5195. params.emplace("note", "coder");
  5196. res = cli_.Post("/person", params);
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. ASSERT_EQ(StatusCode::OK_200, res->status);
  5199. res = cli_.Get("/person/john2");
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. ASSERT_EQ(StatusCode::OK_200, res->status);
  5202. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5203. ASSERT_EQ("coder", res->body);
  5204. }
  5205. TEST_F(ServerTest, PutMethod3) {
  5206. auto res = cli_.Get("/person/john3");
  5207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5208. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5209. Params params;
  5210. params.emplace("name", "john3");
  5211. params.emplace("note", "coder");
  5212. res = cli_.Put("/person", params);
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. ASSERT_EQ(StatusCode::OK_200, res->status);
  5215. res = cli_.Get("/person/john3");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. ASSERT_EQ("coder", res->body);
  5220. }
  5221. TEST_F(ServerTest, DeleteMethod1) {
  5222. auto res = cli_.Get("/person/john4");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. Params params;
  5226. params.emplace("name", "john4");
  5227. params.emplace("note", "coder");
  5228. res = cli_.Post("/person", params);
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. res = cli_.Get("/person/john4");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. ASSERT_EQ(StatusCode::OK_200, res->status);
  5234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. ASSERT_EQ("coder", res->body);
  5236. Params delete_params;
  5237. delete_params.emplace("name", "john4");
  5238. res = cli_.Delete("/person", delete_params);
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. ASSERT_EQ(StatusCode::OK_200, res->status);
  5241. ASSERT_EQ("DELETED", res->body);
  5242. res = cli_.Get("/person/john4");
  5243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5244. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5245. }
  5246. TEST_F(ServerTest, DeleteMethod2) {
  5247. auto res = cli_.Get("/person/john5");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5250. Params params;
  5251. params.emplace("name", "john5");
  5252. params.emplace("note", "developer");
  5253. res = cli_.Post("/person", params);
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. ASSERT_EQ(StatusCode::OK_200, res->status);
  5256. res = cli_.Get("/person/john5");
  5257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5258. ASSERT_EQ(StatusCode::OK_200, res->status);
  5259. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5260. ASSERT_EQ("developer", res->body);
  5261. Params delete_params;
  5262. delete_params.emplace("name", "john5");
  5263. Headers headers;
  5264. headers.emplace("Custom-Header", "test-value");
  5265. res = cli_.Delete("/person", headers, delete_params);
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. ASSERT_EQ(StatusCode::OK_200, res->status);
  5268. ASSERT_EQ("DELETED", res->body);
  5269. res = cli_.Get("/person/john5");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5272. }
  5273. TEST_F(ServerTest, DeleteMethod3) {
  5274. auto res = cli_.Get("/person/john6");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5277. Params params;
  5278. params.emplace("name", "john6");
  5279. params.emplace("note", "tester");
  5280. res = cli_.Post("/person", params);
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. ASSERT_EQ(StatusCode::OK_200, res->status);
  5283. res = cli_.Get("/person/john6");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. ASSERT_EQ(StatusCode::OK_200, res->status);
  5286. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5287. ASSERT_EQ("tester", res->body);
  5288. Params delete_params;
  5289. delete_params.emplace("name", "john6");
  5290. Headers headers;
  5291. headers.emplace("Custom-Header", "test-value");
  5292. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5294. ASSERT_EQ(StatusCode::OK_200, res->status);
  5295. ASSERT_EQ("DELETED", res->body);
  5296. res = cli_.Get("/person/john6");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5299. }
  5300. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5301. Params params;
  5302. params.emplace("json", JSON_DATA);
  5303. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::OK_200, res->status);
  5306. ASSERT_EQ(JSON_DATA, res->body);
  5307. }
  5308. TEST_F(ServerTest, PostEmptyContent) {
  5309. auto res = cli_.Post("/empty", "", "text/plain");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. ASSERT_EQ(StatusCode::OK_200, res->status);
  5312. ASSERT_EQ("empty", res->body);
  5313. }
  5314. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5315. auto res = cli_.Post("/empty-no-content-type");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::OK_200, res->status);
  5318. ASSERT_EQ("empty-no-content-type", res->body);
  5319. }
  5320. TEST_F(ServerTest, PostPathOnly) {
  5321. auto res = cli_.Post("/path-only");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. ASSERT_EQ(StatusCode::OK_200, res->status);
  5324. ASSERT_EQ("path-only", res->body);
  5325. }
  5326. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5327. auto res = cli_.Post("/path-headers-only",
  5328. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::OK_200, res->status);
  5331. ASSERT_EQ("path-headers-only", res->body);
  5332. }
  5333. TEST_F(ServerTest, PostLarge) {
  5334. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. ASSERT_EQ(StatusCode::OK_200, res->status);
  5337. EXPECT_EQ(LARGE_DATA, res->body);
  5338. }
  5339. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5340. auto res = cli_.Put("/empty-no-content-type");
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. ASSERT_EQ(StatusCode::OK_200, res->status);
  5343. ASSERT_EQ("empty-no-content-type", res->body);
  5344. }
  5345. TEST_F(ServerTest, GetMethodDir) {
  5346. auto res = cli_.Get("/dir/");
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. EXPECT_EQ(StatusCode::OK_200, res->status);
  5349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5350. auto body = R"(<html>
  5351. <head>
  5352. </head>
  5353. <body>
  5354. <a href="/dir/test.html">Test</a>
  5355. <a href="/hi">hi</a>
  5356. </body>
  5357. </html>
  5358. )";
  5359. EXPECT_EQ(body, res->body);
  5360. }
  5361. TEST_F(ServerTest, GetMethodDirTest) {
  5362. auto res = cli_.Get("/dir/test.html");
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. EXPECT_EQ(StatusCode::OK_200, res->status);
  5365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5366. EXPECT_EQ("test.html", res->body);
  5367. }
  5368. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5369. auto res = cli_.Get("/dir/../dir/test.html");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::OK_200, res->status);
  5372. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5373. EXPECT_EQ("test.html", res->body);
  5374. }
  5375. TEST_F(ServerTest, GetMethodInvalidPath) {
  5376. auto res = cli_.Get("/dir/../test.html");
  5377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5379. }
  5380. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5381. auto res = cli_.Get("/../www/dir/test.html");
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5384. }
  5385. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5386. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5389. }
  5390. TEST_F(ServerTest, GetMethodDirMountTest) {
  5391. auto res = cli_.Get("/mount/dir/test.html");
  5392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5395. EXPECT_EQ("test.html", res->body);
  5396. }
  5397. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5398. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("test.html", res->body);
  5403. }
  5404. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5405. auto res = cli_.Get("/mount/dir/../test.html");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5408. }
  5409. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5410. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5413. }
  5414. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5415. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5418. }
  5419. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5420. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5423. }
  5424. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5425. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5427. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5428. }
  5429. TEST_F(ServerTest, PostMethod303) {
  5430. auto res = cli_.Post("/1", "body", "text/plain");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5433. EXPECT_EQ("/2", res->get_header_value("Location"));
  5434. }
  5435. TEST_F(ServerTest, PostMethod303Redirect) {
  5436. cli_.set_follow_location(true);
  5437. auto res = cli_.Post("/1", "body", "text/plain");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. EXPECT_EQ("redirected.", res->body);
  5441. EXPECT_EQ("/2", res->location);
  5442. }
  5443. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5444. auto res = cli_.Get("/dir/test.abcde");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5448. EXPECT_EQ("abcde", res->body);
  5449. }
  5450. TEST_F(ServerTest, StaticFileRange) {
  5451. auto res =
  5452. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5455. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5456. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5457. EXPECT_EQ(true, res->has_header("Content-Range"));
  5458. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5459. EXPECT_EQ(std::string("cd"), res->body);
  5460. }
  5461. TEST_F(ServerTest, StaticFileRanges) {
  5462. auto res = cli_.Get("/dir/test.abcde",
  5463. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_TRUE(
  5467. res->get_header_value("Content-Type")
  5468. .find(
  5469. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5470. 0);
  5471. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5472. }
  5473. TEST_F(ServerTest, StaticFileRangeHead) {
  5474. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5477. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5478. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5479. EXPECT_EQ(true, res->has_header("Content-Range"));
  5480. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5481. }
  5482. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5483. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ(true, res->has_header("Content-Range"));
  5489. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5490. res->get_header_value("Content-Range"));
  5491. EXPECT_EQ("LAST\n", res->body);
  5492. }
  5493. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5494. auto res =
  5495. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5498. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5499. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5500. EXPECT_EQ(true, res->has_header("Content-Range"));
  5501. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5502. }
  5503. TEST_F(ServerTest, StaticFileBigFile) {
  5504. auto res = cli_.Get("/dir/1MB.txt");
  5505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5508. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5509. }
  5510. TEST_F(ServerTest, InvalidBaseDirMount) {
  5511. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5512. }
  5513. TEST_F(ServerTest, Binary) {
  5514. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5515. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5516. "application/octet-stream");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. ASSERT_EQ(StatusCode::OK_200, res->status);
  5519. ASSERT_EQ(4U, res->body.size());
  5520. res = cli_.Put("/binary", binary.data(), binary.size(),
  5521. "application/octet-stream");
  5522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5523. ASSERT_EQ(StatusCode::OK_200, res->status);
  5524. ASSERT_EQ(4U, res->body.size());
  5525. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5526. "application/octet-stream");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. ASSERT_EQ(StatusCode::OK_200, res->status);
  5529. ASSERT_EQ(4U, res->body.size());
  5530. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5531. "application/octet-stream");
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. ASSERT_EQ(StatusCode::OK_200, res->status);
  5534. ASSERT_EQ(4U, res->body.size());
  5535. }
  5536. TEST_F(ServerTest, BinaryString) {
  5537. auto binary = std::string("\x00\x01\x02\x03", 4);
  5538. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5540. ASSERT_EQ(StatusCode::OK_200, res->status);
  5541. ASSERT_EQ(4U, res->body.size());
  5542. res = cli_.Put("/binary", binary, "application/octet-stream");
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. ASSERT_EQ(StatusCode::OK_200, res->status);
  5545. ASSERT_EQ(4U, res->body.size());
  5546. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5548. ASSERT_EQ(StatusCode::OK_200, res->status);
  5549. ASSERT_EQ(4U, res->body.size());
  5550. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::OK_200, res->status);
  5553. ASSERT_EQ(4U, res->body.size());
  5554. }
  5555. TEST_F(ServerTest, EmptyRequest) {
  5556. auto res = cli_.Get("");
  5557. ASSERT_TRUE(!res);
  5558. EXPECT_EQ(Error::Connection, res.error());
  5559. }
  5560. TEST_F(ServerTest, LongRequest) {
  5561. std::string request;
  5562. for (size_t i = 0; i < 545; i++) {
  5563. request += "/TooLongRequest";
  5564. }
  5565. request += "OK";
  5566. auto res = cli_.Get(request.c_str());
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, TooLongRequest) {
  5571. std::string request;
  5572. for (size_t i = 0; i < 546; i++) {
  5573. request += "/TooLongRequest";
  5574. }
  5575. request += "_NG";
  5576. auto start = std::chrono::high_resolution_clock::now();
  5577. cli_.set_keep_alive(true);
  5578. auto res = cli_.Get(request.c_str());
  5579. auto end = std::chrono::high_resolution_clock::now();
  5580. auto elapsed =
  5581. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5582. .count();
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5585. EXPECT_LE(elapsed, 1000);
  5586. EXPECT_EQ("close", res->get_header_value("Connection"));
  5587. EXPECT_FALSE(cli_.is_socket_open());
  5588. }
  5589. TEST_F(ServerTest, AlmostTooLongRequest) {
  5590. // test for #2046 - URI length check shouldn't include other content on req
  5591. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5592. // leading /, space, HTTP/1.1)
  5593. std::string request =
  5594. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5595. auto res = cli_.Get(request.c_str());
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5598. }
  5599. TEST_F(ServerTest, LongHeader) {
  5600. Request req;
  5601. req.method = "GET";
  5602. req.path = "/hi";
  5603. std::string host_and_port;
  5604. host_and_port += HOST;
  5605. host_and_port += ":";
  5606. host_and_port += std::to_string(PORT);
  5607. req.headers.emplace("Host", host_and_port.c_str());
  5608. req.headers.emplace("Accept", "*/*");
  5609. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5610. req.headers.emplace(
  5611. "Header-Name",
  5612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5640. "@@@@@@@@@@@@@@@@");
  5641. auto res = std::make_shared<Response>();
  5642. auto error = Error::Success;
  5643. auto ret = cli_.send(req, *res, error);
  5644. ASSERT_TRUE(ret);
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. }
  5647. TEST_F(ServerTest, LongQueryValue) {
  5648. auto start = std::chrono::high_resolution_clock::now();
  5649. cli_.set_keep_alive(true);
  5650. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5651. auto end = std::chrono::high_resolution_clock::now();
  5652. auto elapsed =
  5653. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5654. .count();
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5657. EXPECT_LE(elapsed, 1000);
  5658. EXPECT_EQ("close", res->get_header_value("Connection"));
  5659. EXPECT_FALSE(cli_.is_socket_open());
  5660. }
  5661. TEST_F(ServerTest, TooLongQueryValue) {
  5662. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5663. ASSERT_FALSE(res);
  5664. EXPECT_EQ(Error::Read, res.error());
  5665. }
  5666. TEST_F(ServerTest, TooLongHeader) {
  5667. Request req;
  5668. req.method = "GET";
  5669. req.path = "/hi";
  5670. std::string host_and_port;
  5671. host_and_port += HOST;
  5672. host_and_port += ":";
  5673. host_and_port += std::to_string(PORT);
  5674. req.headers.emplace("Host", host_and_port.c_str());
  5675. req.headers.emplace("Accept", "*/*");
  5676. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5677. req.headers.emplace(
  5678. "Header-Name",
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5707. "@@@@@@@@@@@@@@@@@");
  5708. auto res = std::make_shared<Response>();
  5709. auto error = Error::Success;
  5710. auto ret = cli_.send(req, *res, error);
  5711. ASSERT_TRUE(ret);
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. }
  5714. TEST_F(ServerTest, HeaderCountAtLimit) {
  5715. // Test with headers just under the 100 limit
  5716. httplib::Headers headers;
  5717. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5718. // This should keep us just under the 100 header limit
  5719. for (int i = 0; i < 95; i++) {
  5720. std::string name = "X-Test-Header-" + std::to_string(i);
  5721. std::string value = "value" + std::to_string(i);
  5722. headers.emplace(name, value);
  5723. }
  5724. // This should work fine as we're under the limit
  5725. auto res = cli_.Get("/hi", headers);
  5726. EXPECT_TRUE(res);
  5727. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5728. }
  5729. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5730. // Test with many headers to exceed the 100 limit
  5731. httplib::Headers headers;
  5732. // Add 150 headers to definitely exceed the 100 limit
  5733. for (int i = 0; i < 150; i++) {
  5734. std::string name = "X-Test-Header-" + std::to_string(i);
  5735. std::string value = "value" + std::to_string(i);
  5736. headers.emplace(name, value);
  5737. }
  5738. // This should fail due to exceeding header count limit
  5739. cli_.set_keep_alive(true);
  5740. auto res = cli_.Get("/hi", headers);
  5741. // The server should respond with 400 Bad Request
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5744. EXPECT_EQ("close", res->get_header_value("Connection"));
  5745. EXPECT_FALSE(cli_.is_socket_open());
  5746. }
  5747. TEST_F(ServerTest, PercentEncoding) {
  5748. auto res = cli_.Get("/e%6edwith%");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. }
  5752. TEST_F(ServerTest, PercentEncodingUnicode) {
  5753. auto res = cli_.Get("/e%u006edwith%");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. }
  5757. TEST_F(ServerTest, InvalidPercentEncoding) {
  5758. auto res = cli_.Get("/%endwith%");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5761. }
  5762. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5763. auto res = cli_.Get("/%uendwith%");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5766. }
  5767. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5768. auto res = cli_.Get("/hello?aaa=bbb%");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5771. }
  5772. TEST_F(ServerTest, PlusSignEncoding) {
  5773. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_EQ("a +b", res->body);
  5777. }
  5778. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5779. // This test simulates a potential DoS attack using many headers
  5780. // to verify our security fix prevents memory exhaustion
  5781. httplib::Headers attack_headers;
  5782. // Attempt to add many headers like an attacker would (200 headers to far
  5783. // exceed limit)
  5784. for (int i = 0; i < 200; i++) {
  5785. std::string name = "X-Attack-Header-" + std::to_string(i);
  5786. std::string value = "attack_payload_" + std::to_string(i);
  5787. attack_headers.emplace(name, value);
  5788. }
  5789. // Try to POST with excessive headers
  5790. cli_.set_keep_alive(true);
  5791. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5792. // Should either fail or return 400 Bad Request due to security limit
  5793. if (res) {
  5794. // If we get a response, it should be 400 Bad Request
  5795. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5796. EXPECT_EQ("close", res->get_header_value("Connection"));
  5797. }
  5798. EXPECT_FALSE(cli_.is_socket_open());
  5799. }
  5800. TEST_F(ServerTest, MultipartFormData) {
  5801. UploadFormDataItems items = {
  5802. {"text1", "text default", "", ""},
  5803. {"text2", "aωb", "", ""},
  5804. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5805. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5806. {"file3", "", "", "application/octet-stream"},
  5807. {"file4", "", "", " application/json tmp-string "}};
  5808. auto res = cli_.Post("/multipart", items);
  5809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5810. EXPECT_EQ(StatusCode::OK_200, res->status);
  5811. }
  5812. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5813. UploadFormDataItems items = {
  5814. {"text", "default text", "", ""},
  5815. {"multi_text1", "aaaaa", "", ""},
  5816. {"multi_text1", "bbbbb", "", ""},
  5817. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5818. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5819. "application/json"},
  5820. };
  5821. auto res = cli_.Post("/multipart/multi_file_values", items);
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. }
  5825. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5826. auto res = cli_.Get("/hi");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::OK_200, res->status);
  5829. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5830. EXPECT_EQ("Hello World!", res->body);
  5831. }
  5832. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5833. Request req;
  5834. req.method = "POST";
  5835. req.path = "/chunked";
  5836. std::string host_and_port;
  5837. host_and_port += HOST;
  5838. host_and_port += ":";
  5839. host_and_port += std::to_string(PORT);
  5840. req.headers.emplace("Host", host_and_port.c_str());
  5841. req.headers.emplace("Accept", "*/*");
  5842. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5843. req.headers.emplace("Content-Type", "text/plain");
  5844. req.headers.emplace("Content-Length", "0");
  5845. req.headers.emplace(
  5846. "Transfer-Encoding",
  5847. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5848. // Client does not chunk, so make a chunked body manually.
  5849. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5850. auto res = std::make_shared<Response>();
  5851. auto error = Error::Success;
  5852. auto ret = cli_.send(req, *res, error);
  5853. ASSERT_TRUE(ret);
  5854. EXPECT_EQ(StatusCode::OK_200, res->status);
  5855. }
  5856. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5857. // rather than treat them as valid lengths.
  5858. template <typename ClientT>
  5859. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5860. Request req;
  5861. req.method = "POST";
  5862. req.path = "/chunked";
  5863. std::string host_and_port;
  5864. host_and_port += HOST;
  5865. host_and_port += ":";
  5866. host_and_port += std::to_string(PORT);
  5867. req.headers.emplace("Host", host_and_port.c_str());
  5868. req.headers.emplace("Content-Length", "0");
  5869. req.headers.emplace("Transfer-Encoding", "chunked");
  5870. req.body = body;
  5871. auto res = std::make_shared<Response>();
  5872. auto error = Error::Success;
  5873. ASSERT_TRUE(cli.send(req, *res, error));
  5874. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5875. }
  5876. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5877. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5878. }
  5879. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5880. expect_chunked_body_rejected(
  5881. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5882. }
  5883. TEST_F(ServerTest, GetStreamed2) {
  5884. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5886. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5887. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5888. EXPECT_EQ(true, res->has_header("Content-Range"));
  5889. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5890. EXPECT_EQ(std::string("ab"), res->body);
  5891. }
  5892. TEST_F(ServerTest, GetStreamed) {
  5893. auto res = cli_.Get("/streamed");
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5897. EXPECT_EQ(std::string("aaabbb"), res->body);
  5898. }
  5899. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5900. auto res = cli_.Get("/streamed-without-length",
  5901. Headers{make_range_header({{0, -1}})});
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ(false, res->has_header("Content-Length"));
  5905. EXPECT_EQ(false, res->has_header("Content-Range"));
  5906. EXPECT_EQ(std::string("abcdefg"), res->body);
  5907. }
  5908. TEST_F(ServerTest, GetStreamedWithRange1) {
  5909. auto res =
  5910. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5913. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5914. EXPECT_EQ(true, res->has_header("Content-Range"));
  5915. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5916. EXPECT_EQ(std::string("def"), res->body);
  5917. }
  5918. TEST_F(ServerTest, GetStreamedWithRange2) {
  5919. auto res =
  5920. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5923. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5924. EXPECT_EQ(true, res->has_header("Content-Range"));
  5925. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5926. EXPECT_EQ(std::string("bcdefg"), res->body);
  5927. }
  5928. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5929. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5932. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5933. EXPECT_EQ(true, res->has_header("Content-Range"));
  5934. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5935. EXPECT_EQ(std::string("efg"), res->body);
  5936. }
  5937. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5938. auto res =
  5939. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5942. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5943. EXPECT_EQ(false, res->has_header("Content-Range"));
  5944. EXPECT_EQ(0U, res->body.size());
  5945. }
  5946. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5947. // Only a 206 is served as a partial representation. Under any other status
  5948. // `apply_ranges()` reported the full content length, so the body must match
  5949. // that header, and the content provider must never be asked for an offset
  5950. // outside the representation.
  5951. auto check = [&](int status, const char *range) {
  5952. auto path =
  5953. std::string("/streamed-with-range?status=") + std::to_string(status);
  5954. auto ctx = path + " Range: " + range;
  5955. auto res = cli_.Get(path, Headers{{"Range", range}});
  5956. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5957. EXPECT_EQ(status, res->status) << ctx;
  5958. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5960. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5961. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5962. };
  5963. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5964. check(403, "bytes=3-5");
  5965. // The offset is far past the representation.
  5966. check(403, "bytes=100000-100200");
  5967. // `first_pos` is still -1 here, and the bounds asserts in
  5968. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5969. check(403, "bytes=-3");
  5970. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5971. // multipart branch would have written one that is empty.
  5972. check(403, "bytes=1-2, 4-5");
  5973. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5974. // covers the whole representation.
  5975. check(200, "bytes=3-5");
  5976. check(200, "bytes=1-2, 4-5");
  5977. }
  5978. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5979. auto res =
  5980. cli_.Get("/streamed-with-range",
  5981. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5982. "92233720368547758079223372036854775807"}});
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5985. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5986. EXPECT_EQ(false, res->has_header("Content-Range"));
  5987. EXPECT_EQ(0U, res->body.size());
  5988. }
  5989. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5990. auto res = cli_.Get(
  5991. "/with-range",
  5992. Headers{{"Range",
  5993. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5994. {"Accept-Encoding", ""}});
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5997. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5998. EXPECT_EQ(true, res->has_header("Content-Range"));
  5999. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6000. EXPECT_EQ(std::string("abcdefg"), res->body);
  6001. }
  6002. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6003. auto res = cli_.Get("/with-range", Headers{
  6004. {"Range", "bytes=0-"},
  6005. {"Accept-Encoding", ""},
  6006. });
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6009. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6010. EXPECT_EQ(true, res->has_header("Content-Range"));
  6011. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6012. EXPECT_EQ(std::string("abcdefg"), res->body);
  6013. }
  6014. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6015. auto res = cli_.Get("/streamed-with-range",
  6016. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6019. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6020. EXPECT_EQ(false, res->has_header("Content-Range"));
  6021. EXPECT_EQ(267U, res->body.size());
  6022. // Check that both range contents are present
  6023. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6024. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6025. // Check that Content-Range headers are present for both ranges
  6026. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6027. std::string::npos);
  6028. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6029. std::string::npos);
  6030. }
  6031. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6032. Ranges ranges;
  6033. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6034. ranges.emplace_back(0, -1);
  6035. }
  6036. auto res = cli_.Get("/streamed-with-range?error",
  6037. Headers{{make_range_header(ranges)}});
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6040. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6041. EXPECT_EQ(false, res->has_header("Content-Range"));
  6042. EXPECT_EQ(0U, res->body.size());
  6043. }
  6044. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6045. auto res = cli_.Get("/streamed-with-range",
  6046. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6049. EXPECT_EQ(5U, res->body.size());
  6050. // Check that overlapping ranges are coalesced into a single range
  6051. EXPECT_EQ("bcdef", res->body);
  6052. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6053. // Should be single range, not multipart
  6054. EXPECT_TRUE(res->has_header("Content-Range"));
  6055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6056. }
  6057. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6058. auto res = cli_.Get("/streamed-with-range",
  6059. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6062. EXPECT_EQ(268U, res->body.size());
  6063. // Check that both range contents are present
  6064. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6065. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6066. // Check that Content-Range headers are present for both ranges
  6067. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6068. std::string::npos);
  6069. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6070. std::string::npos);
  6071. }
  6072. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6073. auto res = cli_.Get("/streamed-with-range",
  6074. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6077. EXPECT_EQ(269U, res->body.size());
  6078. // Check that both duplicate range contents are present
  6079. size_t first_abc = res->body.find("abc\r\n");
  6080. EXPECT_TRUE(first_abc != std::string::npos);
  6081. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6082. EXPECT_TRUE(second_abc != std::string::npos);
  6083. // Check that Content-Range headers are present for both ranges
  6084. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6085. EXPECT_TRUE(first_range != std::string::npos);
  6086. size_t second_range =
  6087. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6088. EXPECT_TRUE(second_range != std::string::npos);
  6089. }
  6090. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6091. auto res =
  6092. cli_.Get("/streamed-with-range?error",
  6093. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6097. EXPECT_EQ(false, res->has_header("Content-Range"));
  6098. EXPECT_EQ(0U, res->body.size());
  6099. }
  6100. TEST_F(ServerTest, GetStreamedEndless) {
  6101. uint64_t offset = 0;
  6102. auto res = cli_.Get("/streamed-cancel",
  6103. [&](const char * /*data*/, uint64_t data_length) {
  6104. if (offset < 100) {
  6105. offset += data_length;
  6106. return true;
  6107. }
  6108. return false;
  6109. });
  6110. ASSERT_TRUE(!res);
  6111. EXPECT_EQ(Error::Canceled, res.error());
  6112. }
  6113. TEST_F(ServerTest, ClientStop) {
  6114. std::atomic_size_t count{4};
  6115. std::vector<std::thread> threads;
  6116. for (auto i = count.load(); i != 0; --i) {
  6117. threads.emplace_back([&]() {
  6118. auto res = cli_.Get("/streamed-cancel",
  6119. [&](const char *, uint64_t) { return true; });
  6120. --count;
  6121. ASSERT_TRUE(!res);
  6122. EXPECT_TRUE(res.error() == Error::Canceled ||
  6123. res.error() == Error::Read || res.error() == Error::Write);
  6124. });
  6125. }
  6126. std::this_thread::sleep_for(std::chrono::seconds(2));
  6127. while (count != 0) {
  6128. cli_.stop();
  6129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6130. }
  6131. for (auto &t : threads) {
  6132. t.join();
  6133. }
  6134. }
  6135. TEST_F(ServerTest, GetWithRange1) {
  6136. auto res = cli_.Get("/with-range", Headers{
  6137. make_range_header({{3, 5}}),
  6138. {"Accept-Encoding", ""},
  6139. });
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6142. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6143. EXPECT_EQ(true, res->has_header("Content-Range"));
  6144. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6145. EXPECT_EQ(std::string("def"), res->body);
  6146. }
  6147. TEST_F(ServerTest, GetWithRange2) {
  6148. auto res = cli_.Get("/with-range", Headers{
  6149. make_range_header({{1, -1}}),
  6150. {"Accept-Encoding", ""},
  6151. });
  6152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6153. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6154. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ(true, res->has_header("Content-Range"));
  6156. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6157. EXPECT_EQ(std::string("bcdefg"), res->body);
  6158. }
  6159. TEST_F(ServerTest, GetWithRange3) {
  6160. auto res = cli_.Get("/with-range", Headers{
  6161. make_range_header({{0, 0}}),
  6162. {"Accept-Encoding", ""},
  6163. });
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6166. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6167. EXPECT_EQ(true, res->has_header("Content-Range"));
  6168. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6169. EXPECT_EQ(std::string("a"), res->body);
  6170. }
  6171. TEST_F(ServerTest, GetWithRange4) {
  6172. auto res = cli_.Get("/with-range", Headers{
  6173. make_range_header({{-1, 2}}),
  6174. {"Accept-Encoding", ""},
  6175. });
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ(true, res->has_header("Content-Range"));
  6180. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6181. EXPECT_EQ(std::string("fg"), res->body);
  6182. }
  6183. TEST_F(ServerTest, GetWithRange5) {
  6184. auto res = cli_.Get("/with-range", Headers{
  6185. make_range_header({{0, 5}}),
  6186. {"Accept-Encoding", ""},
  6187. });
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6190. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ(true, res->has_header("Content-Range"));
  6192. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6193. EXPECT_EQ(std::string("abcdef"), res->body);
  6194. }
  6195. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6196. auto res =
  6197. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6200. }
  6201. TEST_F(ServerTest, GetWithRangeMultipart) {
  6202. auto res =
  6203. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6206. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6207. EXPECT_EQ(false, res->has_header("Content-Range"));
  6208. EXPECT_EQ(267U, res->body.size());
  6209. }
  6210. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6211. auto res = cli_.Get("/with-range",
  6212. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6215. }
  6216. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6217. auto res = cli_.Get("/with-range-customized-response",
  6218. Headers{{make_range_header({{1, 2}})}});
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6221. EXPECT_EQ(true, res->has_header("Content-Length"));
  6222. EXPECT_EQ(false, res->has_header("Content-Range"));
  6223. EXPECT_EQ(JSON_DATA, res->body);
  6224. }
  6225. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6226. auto res = cli_.Get("/with-range-customized-response",
  6227. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6230. EXPECT_EQ(true, res->has_header("Content-Length"));
  6231. EXPECT_EQ(false, res->has_header("Content-Range"));
  6232. EXPECT_EQ(JSON_DATA, res->body);
  6233. }
  6234. TEST_F(ServerTest, Issue1772) {
  6235. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6238. }
  6239. TEST_F(ServerTest, Issue609) {
  6240. auto res = cli_.Delete("/issue609");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::OK_200, res->status);
  6243. EXPECT_EQ(std::string("ok"), res->body);
  6244. }
  6245. TEST_F(ServerTest, GetStreamedChunked) {
  6246. auto res = cli_.Get("/streamed-chunked");
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. EXPECT_EQ(std::string("123456789"), res->body);
  6250. }
  6251. TEST_F(ServerTest, GetStreamedChunked2) {
  6252. auto res = cli_.Get("/streamed-chunked2");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. EXPECT_EQ(std::string("123456789"), res->body);
  6256. }
  6257. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6258. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::OK_200, res->status);
  6261. EXPECT_EQ(std::string("123456789"), res->body);
  6262. EXPECT_TRUE(res->has_header("Trailer"));
  6263. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6264. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6265. // Trailers are now stored separately from headers (security fix)
  6266. EXPECT_EQ(2U, res->trailers.size());
  6267. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6268. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6269. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6270. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6271. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6272. // Verify trailers are NOT in headers (security verification)
  6273. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6274. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6275. }
  6276. TEST_F(ServerTest, LargeChunkedPost) {
  6277. Request req;
  6278. req.method = "POST";
  6279. req.path = "/large-chunked";
  6280. std::string host_and_port;
  6281. host_and_port += HOST;
  6282. host_and_port += ":";
  6283. host_and_port += std::to_string(PORT);
  6284. req.headers.emplace("Host", host_and_port.c_str());
  6285. req.headers.emplace("Accept", "*/*");
  6286. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6287. req.headers.emplace("Content-Type", "text/plain");
  6288. req.headers.emplace("Content-Length", "0");
  6289. req.headers.emplace("Transfer-Encoding", "chunked");
  6290. std::string long_string(30 * 1024u, 'a');
  6291. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6292. // Attempt to make a large enough post to exceed OS buffers, to test that
  6293. // the server handles short reads if the full chunk data isn't available.
  6294. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6295. auto res = std::make_shared<Response>();
  6296. auto error = Error::Success;
  6297. auto ret = cli_.send(req, *res, error);
  6298. ASSERT_TRUE(ret);
  6299. EXPECT_EQ(StatusCode::OK_200, res->status);
  6300. }
  6301. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6302. auto res = cli_.Get("/remote_addr");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::OK_200, res->status);
  6305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6306. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6307. }
  6308. TEST_F(ServerTest, GetMethodLocalAddr) {
  6309. auto res = cli_.Get("/local_addr");
  6310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6311. EXPECT_EQ(StatusCode::OK_200, res->status);
  6312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6313. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6314. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6315. }
  6316. TEST_F(ServerTest, HTTPResponseSplitting) {
  6317. auto res = cli_.Get("/http_response_splitting");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. }
  6321. TEST_F(ServerTest, SlowRequest) {
  6322. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6323. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6324. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6325. }
  6326. #if 0
  6327. TEST_F(ServerTest, SlowPost) {
  6328. char buffer[64 * 1024];
  6329. memset(buffer, 0x42, sizeof(buffer));
  6330. auto res = cli_.Post(
  6331. "/slowpost", 64 * 1024 * 1024,
  6332. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6333. auto ret = sink.write(buffer, sizeof(buffer));
  6334. EXPECT_TRUE(ret);
  6335. return true;
  6336. },
  6337. "text/plain");
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. }
  6341. TEST_F(ServerTest, SlowPostFail) {
  6342. char buffer[64 * 1024];
  6343. memset(buffer, 0x42, sizeof(buffer));
  6344. cli_.set_write_timeout(std::chrono::seconds(0));
  6345. auto res = cli_.Post(
  6346. "/slowpost", 64 * 1024 * 1024,
  6347. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6348. sink.write(buffer, sizeof(buffer));
  6349. return true;
  6350. },
  6351. "text/plain");
  6352. ASSERT_TRUE(!res);
  6353. EXPECT_EQ(Error::Write, res.error());
  6354. }
  6355. #endif
  6356. TEST_F(ServerTest, Put) {
  6357. auto res = cli_.Put("/put", "PUT", "text/plain");
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::OK_200, res->status);
  6360. EXPECT_EQ("PUT", res->body);
  6361. }
  6362. TEST_F(ServerTest, PutWithContentProvider) {
  6363. auto res = cli_.Put(
  6364. "/put", 3,
  6365. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6366. sink.os << "PUT";
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. EXPECT_EQ("PUT", res->body);
  6373. }
  6374. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6375. auto res = cli_.Post(
  6376. "/post", 42,
  6377. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6378. return false;
  6379. },
  6380. "text/plain");
  6381. ASSERT_TRUE(!res);
  6382. EXPECT_EQ(Error::Canceled, res.error());
  6383. }
  6384. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6385. auto res = cli_.Put(
  6386. "/put",
  6387. [](size_t /*offset*/, DataSink &sink) {
  6388. sink.os << "PUT";
  6389. sink.done();
  6390. return true;
  6391. },
  6392. "text/plain");
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::OK_200, res->status);
  6395. EXPECT_EQ("PUT", res->body);
  6396. }
  6397. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6398. auto res = cli_.Post(
  6399. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6400. "text/plain");
  6401. ASSERT_TRUE(!res);
  6402. EXPECT_EQ(Error::Canceled, res.error());
  6403. }
  6404. TEST_F(ServerTest, PostLoopBack) {
  6405. std::string body;
  6406. auto res = cli_.Post(
  6407. "/post-loopback", 9,
  6408. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6409. EXPECT_EQ(9u, length);
  6410. sink.write("123", 3);
  6411. sink.write("456", 3);
  6412. sink.write("789", 3);
  6413. return true;
  6414. },
  6415. "text/plain",
  6416. [&body](const char *data, size_t data_length) {
  6417. body.append(data, data_length);
  6418. return true;
  6419. });
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::OK_200, res->status);
  6422. EXPECT_EQ("123456789", body);
  6423. }
  6424. TEST_F(ServerTest, PutLoopBack) {
  6425. std::string body;
  6426. auto res = cli_.Put(
  6427. "/put-loopback", 9,
  6428. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6429. EXPECT_EQ(9u, length);
  6430. sink.write("123", 3);
  6431. sink.write("456", 3);
  6432. sink.write("789", 3);
  6433. return true;
  6434. },
  6435. "text/plain",
  6436. [&body](const char *data, size_t data_length) {
  6437. body.append(data, data_length);
  6438. return true;
  6439. });
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("123456789", body);
  6443. }
  6444. TEST_F(ServerTest, PatchLoopBack) {
  6445. std::string body;
  6446. auto res = cli_.Patch(
  6447. "/patch-loopback", 9,
  6448. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6449. EXPECT_EQ(9u, length);
  6450. sink.write("123", 3);
  6451. sink.write("456", 3);
  6452. sink.write("789", 3);
  6453. return true;
  6454. },
  6455. "text/plain",
  6456. [&body](const char *data, size_t data_length) {
  6457. body.append(data, data_length);
  6458. return true;
  6459. });
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::OK_200, res->status);
  6462. EXPECT_EQ("123456789", body);
  6463. }
  6464. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6465. std::string body;
  6466. auto res = cli_.Post(
  6467. "/post-loopback",
  6468. [](size_t /*offset*/, DataSink &sink) {
  6469. sink.write("123", 3);
  6470. sink.write("456", 3);
  6471. sink.write("789", 3);
  6472. sink.done();
  6473. return true;
  6474. },
  6475. "text/plain",
  6476. [&body](const char *data, size_t data_length) {
  6477. body.append(data, data_length);
  6478. return true;
  6479. });
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::OK_200, res->status);
  6482. EXPECT_EQ("123456789", body);
  6483. }
  6484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6485. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6486. cli_.set_compress(true);
  6487. auto res = cli_.Put(
  6488. "/put", 3,
  6489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6490. sink.os << "PUT";
  6491. return true;
  6492. },
  6493. "text/plain");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ("PUT", res->body);
  6497. }
  6498. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6499. cli_.set_compress(true);
  6500. auto res = cli_.Post(
  6501. "/post", 42,
  6502. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6503. return false;
  6504. },
  6505. "text/plain");
  6506. ASSERT_TRUE(!res);
  6507. EXPECT_EQ(Error::Canceled, res.error());
  6508. }
  6509. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6510. cli_.set_compress(true);
  6511. auto res = cli_.Put(
  6512. "/put",
  6513. [](size_t /*offset*/, DataSink &sink) {
  6514. sink.os << "PUT";
  6515. sink.done();
  6516. return true;
  6517. },
  6518. "text/plain");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::OK_200, res->status);
  6521. EXPECT_EQ("PUT", res->body);
  6522. }
  6523. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6524. cli_.set_compress(true);
  6525. auto res = cli_.Post(
  6526. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6527. "text/plain");
  6528. ASSERT_TRUE(!res);
  6529. EXPECT_EQ(Error::Canceled, res.error());
  6530. }
  6531. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6532. cli_.set_compress(true);
  6533. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::OK_200, res->status);
  6536. EXPECT_EQ(LARGE_DATA, res->body);
  6537. }
  6538. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6539. #ifdef CPPHTTPLIB_SSL_ENABLED
  6540. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6541. Client cli(s.c_str());
  6542. cli.enable_server_certificate_verification(false);
  6543. #else
  6544. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6545. Client cli(s.c_str());
  6546. #endif
  6547. cli.set_compress(true);
  6548. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::OK_200, res->status);
  6551. EXPECT_EQ(LARGE_DATA, res->body);
  6552. // The compressed size should be less than a 10th of the original. May vary
  6553. // depending on the zlib library.
  6554. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6555. static_cast<uint64_t>(10 * 1024 * 1024));
  6556. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6557. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6558. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6559. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6560. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6561. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6562. #endif
  6563. }
  6564. TEST_F(ServerTest, PutContentWithDeflate) {
  6565. cli_.set_compress(false);
  6566. Headers headers;
  6567. headers.emplace("Content-Encoding", "deflate");
  6568. // PUT in deflate format:
  6569. auto res = cli_.Put("/put", headers,
  6570. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6572. EXPECT_EQ(StatusCode::OK_200, res->status);
  6573. EXPECT_EQ("PUT", res->body);
  6574. }
  6575. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6576. Headers headers;
  6577. headers.emplace("Accept-Encoding", "gzip, deflate");
  6578. auto res = cli_.Get("/streamed-chunked", headers);
  6579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. EXPECT_EQ(std::string("123456789"), res->body);
  6582. }
  6583. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6584. Headers headers;
  6585. headers.emplace("Accept-Encoding", "gzip, deflate");
  6586. auto res = cli_.Get("/streamed-chunked2", headers);
  6587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6588. EXPECT_EQ(StatusCode::OK_200, res->status);
  6589. EXPECT_EQ(std::string("123456789"), res->body);
  6590. }
  6591. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6592. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. }
  6596. TEST(GzipDecompressor, ChunkedDecompression) {
  6597. std::string data;
  6598. for (size_t i = 0; i < 32 * 1024; ++i) {
  6599. data.push_back(static_cast<char>('a' + i % 26));
  6600. }
  6601. std::string compressed_data;
  6602. {
  6603. httplib::detail::gzip_compressor compressor;
  6604. bool result = compressor.compress(
  6605. data.data(), data.size(),
  6606. /*last=*/true,
  6607. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6608. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6609. compressed_data_size);
  6610. return true;
  6611. });
  6612. ASSERT_TRUE(result);
  6613. }
  6614. std::string decompressed_data;
  6615. {
  6616. httplib::detail::gzip_decompressor decompressor;
  6617. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6618. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6619. size_t chunk_size = 130;
  6620. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6621. chunk_begin += chunk_size) {
  6622. size_t current_chunk_size =
  6623. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6624. bool result = decompressor.decompress(
  6625. compressed_data.data() + chunk_begin, current_chunk_size,
  6626. [&](const char *decompressed_data_chunk,
  6627. size_t decompressed_data_chunk_size) {
  6628. decompressed_data.insert(decompressed_data.size(),
  6629. decompressed_data_chunk,
  6630. decompressed_data_chunk_size);
  6631. return true;
  6632. });
  6633. ASSERT_TRUE(result);
  6634. }
  6635. }
  6636. ASSERT_EQ(data, decompressed_data);
  6637. }
  6638. TEST(GzipDecompressor, DeflateDecompression) {
  6639. std::string original_text = "Raw deflate without gzip";
  6640. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6641. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6642. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6643. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6644. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6645. std::string decompressed_data;
  6646. {
  6647. httplib::detail::gzip_decompressor decompressor;
  6648. bool result = decompressor.decompress(
  6649. compressed_data.data(), compressed_data.size(),
  6650. [&](const char *decompressed_data_chunk,
  6651. size_t decompressed_data_chunk_size) {
  6652. decompressed_data.insert(decompressed_data.size(),
  6653. decompressed_data_chunk,
  6654. decompressed_data_chunk_size);
  6655. return true;
  6656. });
  6657. ASSERT_TRUE(result);
  6658. }
  6659. ASSERT_EQ(original_text, decompressed_data);
  6660. }
  6661. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6662. std::string original_text = "Raw deflate without gzip";
  6663. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6664. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6665. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6666. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6667. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6668. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6669. std::string decompressed_data;
  6670. {
  6671. httplib::detail::gzip_decompressor decompressor;
  6672. bool result = decompressor.decompress(
  6673. compressed_data.data(), compressed_data.size(),
  6674. [&](const char *decompressed_data_chunk,
  6675. size_t decompressed_data_chunk_size) {
  6676. decompressed_data.insert(decompressed_data.size(),
  6677. decompressed_data_chunk,
  6678. decompressed_data_chunk_size);
  6679. return true;
  6680. });
  6681. ASSERT_TRUE(result);
  6682. }
  6683. ASSERT_EQ(original_text, decompressed_data);
  6684. }
  6685. #endif
  6686. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6687. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6688. Headers headers;
  6689. headers.emplace("Accept-Encoding", "br");
  6690. auto res = cli_.Get("/streamed-chunked", headers);
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ(StatusCode::OK_200, res->status);
  6693. EXPECT_EQ(std::string("123456789"), res->body);
  6694. }
  6695. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6696. Headers headers;
  6697. headers.emplace("Accept-Encoding", "br");
  6698. auto res = cli_.Get("/streamed-chunked2", headers);
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. EXPECT_EQ(std::string("123456789"), res->body);
  6702. }
  6703. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Put(
  6706. "/put", 3,
  6707. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6708. sink.os << "PUT";
  6709. return true;
  6710. },
  6711. "text/plain");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("PUT", res->body);
  6715. }
  6716. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6717. cli_.set_compress(true);
  6718. auto res = cli_.Put(
  6719. "/put",
  6720. [](size_t /*offset*/, DataSink &sink) {
  6721. sink.os << "PUT";
  6722. sink.done();
  6723. return true;
  6724. },
  6725. "text/plain");
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::OK_200, res->status);
  6728. EXPECT_EQ("PUT", res->body);
  6729. }
  6730. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6731. cli_.set_compress(true);
  6732. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. EXPECT_EQ(LARGE_DATA, res->body);
  6736. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6737. }
  6738. #endif
  6739. TEST_F(ServerTest, Patch) {
  6740. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("PATCH", res->body);
  6744. }
  6745. TEST_F(ServerTest, Delete) {
  6746. auto res = cli_.Delete("/delete");
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. EXPECT_EQ("DELETE", res->body);
  6750. }
  6751. TEST_F(ServerTest, DeleteContentReceiver) {
  6752. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. EXPECT_EQ("content", res->body);
  6756. }
  6757. TEST_F(ServerTest, Options) {
  6758. auto res = cli_.Options("*");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6762. EXPECT_TRUE(res->body.empty());
  6763. }
  6764. TEST_F(ServerTest, URL) {
  6765. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. }
  6769. TEST_F(ServerTest, ArrayParam) {
  6770. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. }
  6774. TEST_F(ServerTest, ArrayParamValues) {
  6775. auto res =
  6776. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. }
  6780. TEST_F(ServerTest, NoMultipleHeaders) {
  6781. Headers headers = {{"Content-Length", "5"}};
  6782. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6783. "text/plain");
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. }
  6787. TEST_F(ServerTest, PostContentReceiver) {
  6788. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. ASSERT_EQ(StatusCode::OK_200, res->status);
  6791. ASSERT_EQ("content", res->body);
  6792. }
  6793. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6794. UploadFormDataItems items = {
  6795. {"text1", "text default", "", ""},
  6796. {"text2", "aωb", "", ""},
  6797. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6798. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6799. {"file3", "", "", "application/octet-stream"},
  6800. };
  6801. auto res = cli_.Post("/content_receiver", items);
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. }
  6805. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6806. UploadFormDataItems items = {
  6807. {"text1", "text default", "", ""},
  6808. {"text2", "aωb", "", ""},
  6809. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6810. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6811. {"file3", "", "", "application/octet-stream"},
  6812. };
  6813. auto boundary = std::string("+++++");
  6814. std::string body;
  6815. for (const auto &item : items) {
  6816. body += "--" + boundary + "\r\n";
  6817. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6818. if (!item.filename.empty()) {
  6819. body += "; filename=\"" + item.filename + "\"";
  6820. }
  6821. body += "\r\n";
  6822. if (!item.content_type.empty()) {
  6823. body += "Content-Type: " + item.content_type + "\r\n";
  6824. }
  6825. body += "\r\n";
  6826. body += item.content + "\r\n";
  6827. }
  6828. body += "--" + boundary + "--\r\n";
  6829. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6830. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. EXPECT_EQ(StatusCode::OK_200, res->status);
  6833. }
  6834. TEST(MultipartFormDataTest, FieldEscaping) {
  6835. Server svr;
  6836. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6837. const ContentReader &content_reader) {
  6838. ASSERT_TRUE(req.is_multipart_form_data());
  6839. std::vector<FormData> received;
  6840. content_reader(
  6841. [&](const FormData &file) {
  6842. received.push_back(file);
  6843. return true;
  6844. },
  6845. [&](const char *data, size_t data_length) {
  6846. received.back().content.append(data, data_length);
  6847. return true;
  6848. });
  6849. // '"', CR and LF in names and filenames are escaped following the
  6850. // WHATWG HTML standard, so each part still parses as a single part
  6851. // with no injected headers. Content types get CR/LF escaped too,
  6852. // while '"' (legal there, e.g. quoted charset) is preserved.
  6853. ASSERT_EQ(4U, received.size());
  6854. EXPECT_EQ("na%22me", received[0].name);
  6855. EXPECT_EQ("quoted name", received[0].content);
  6856. EXPECT_EQ("file", received[1].name);
  6857. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6858. received[1].filename);
  6859. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6860. EXPECT_EQ("injected", received[1].content);
  6861. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6862. EXPECT_EQ("my%22file.txt", received[2].filename);
  6863. EXPECT_EQ("cr lf name", received[2].content);
  6864. EXPECT_EQ("typed", received[3].name);
  6865. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6866. received[3].content_type);
  6867. EXPECT_EQ("typed content", received[3].content);
  6868. });
  6869. auto port = svr.bind_to_any_port("localhost");
  6870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6871. auto se = detail::scope_exit([&] {
  6872. svr.stop();
  6873. t.join();
  6874. ASSERT_FALSE(svr.is_running());
  6875. });
  6876. svr.wait_until_ready();
  6877. Client cli("localhost", port);
  6878. UploadFormDataItems items = {
  6879. {"na\"me", "quoted name", "", ""},
  6880. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6881. "application/octet-stream"},
  6882. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6883. {"typed", "typed content", "",
  6884. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6885. };
  6886. auto res = cli.Post("/post", items);
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. }
  6890. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6891. const UploadFormDataItems items = {
  6892. {"name1", "Content 1", "", ""},
  6893. {"name2", "Content 2", "file2.txt", "text/plain"},
  6894. };
  6895. Server svr;
  6896. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6897. const ContentReader &content_reader) {
  6898. ASSERT_TRUE(req.is_multipart_form_data());
  6899. std::vector<FormData> received;
  6900. content_reader(
  6901. [&](const FormData &file) {
  6902. received.push_back(file);
  6903. return true;
  6904. },
  6905. [&](const char *data, size_t data_length) {
  6906. received.back().content.append(data, data_length);
  6907. return true;
  6908. });
  6909. ASSERT_EQ(2U, received.size());
  6910. EXPECT_EQ("name1", received[0].name);
  6911. EXPECT_EQ("Content 1", received[0].content);
  6912. EXPECT_EQ("name2", received[1].name);
  6913. EXPECT_EQ("Content 2", received[1].content);
  6914. EXPECT_EQ("file2.txt", received[1].filename);
  6915. EXPECT_EQ("text/plain", received[1].content_type);
  6916. });
  6917. auto port = svr.bind_to_any_port("localhost");
  6918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6919. auto se = detail::scope_exit([&] {
  6920. svr.stop();
  6921. t.join();
  6922. ASSERT_FALSE(svr.is_running());
  6923. });
  6924. svr.wait_until_ready();
  6925. Client cli("localhost", port);
  6926. // Whole-body serialization with a generated boundary
  6927. {
  6928. MultipartFormDataWriter writer;
  6929. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6930. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6931. writer.content_type());
  6932. auto body = writer.serialize(items);
  6933. EXPECT_EQ(body.size(), writer.content_length(items));
  6934. auto res = cli.Post("/post", body, writer.content_type());
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. }
  6938. // Per-part framing with a custom boundary via a content provider
  6939. {
  6940. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6941. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6942. MultipartFormDataWriter writer("custom-boundary_123");
  6943. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6944. std::string body;
  6945. for (const auto &item : items) {
  6946. body += writer.item_begin(item);
  6947. body += item.content;
  6948. body += MultipartFormDataWriter::item_end();
  6949. }
  6950. body += writer.finish();
  6951. EXPECT_EQ(body.size(), writer.content_length(items));
  6952. auto res = cli.Post(
  6953. "/post", body.size(),
  6954. [&](size_t offset, size_t length, DataSink &sink) {
  6955. sink.write(body.data() + offset, length);
  6956. return true;
  6957. },
  6958. writer.content_type());
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. }
  6963. TEST_F(ServerTest, PostContentReceiverGzip) {
  6964. cli_.set_compress(true);
  6965. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. ASSERT_EQ(StatusCode::OK_200, res->status);
  6968. ASSERT_EQ("content", res->body);
  6969. }
  6970. TEST_F(ServerTest, PutContentReceiver) {
  6971. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. ASSERT_EQ(StatusCode::OK_200, res->status);
  6974. ASSERT_EQ("content", res->body);
  6975. }
  6976. TEST_F(ServerTest, PatchContentReceiver) {
  6977. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. ASSERT_EQ(StatusCode::OK_200, res->status);
  6980. ASSERT_EQ("content", res->body);
  6981. }
  6982. template <typename ClientType>
  6983. void TestWithHeadersAndContentReceiver(
  6984. ClientType &cli,
  6985. std::function<Result(ClientType &, const std::string &, const Headers &,
  6986. const std::string &, const std::string &,
  6987. ContentReceiver, DownloadProgress)>
  6988. request_func) {
  6989. Headers headers;
  6990. headers.emplace("X-Custom-Header", "test-value");
  6991. std::string received_body;
  6992. auto res = request_func(
  6993. cli, "/content_receiver", headers, "content", "application/json",
  6994. [&](const char *data, size_t data_length) {
  6995. received_body.append(data, data_length);
  6996. return true;
  6997. },
  6998. nullptr);
  6999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7000. EXPECT_EQ(StatusCode::OK_200, res->status);
  7001. EXPECT_EQ("content", received_body);
  7002. }
  7003. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7004. #ifdef CPPHTTPLIB_SSL_ENABLED
  7005. using ClientT = SSLClient;
  7006. #else
  7007. using ClientT = Client;
  7008. #endif
  7009. TestWithHeadersAndContentReceiver<ClientT>(
  7010. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7011. const std::string &body, const std::string &content_type,
  7012. ContentReceiver receiver, DownloadProgress progress) {
  7013. return cli.Post(path, headers, body, content_type, receiver, progress);
  7014. });
  7015. }
  7016. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7017. #ifdef CPPHTTPLIB_SSL_ENABLED
  7018. using ClientT = SSLClient;
  7019. #else
  7020. using ClientT = Client;
  7021. #endif
  7022. TestWithHeadersAndContentReceiver<ClientT>(
  7023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7024. const std::string &body, const std::string &content_type,
  7025. ContentReceiver receiver, DownloadProgress progress) {
  7026. return cli.Put(path, headers, body, content_type, receiver, progress);
  7027. });
  7028. }
  7029. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7030. #ifdef CPPHTTPLIB_SSL_ENABLED
  7031. using ClientT = SSLClient;
  7032. #else
  7033. using ClientT = Client;
  7034. #endif
  7035. TestWithHeadersAndContentReceiver<ClientT>(
  7036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7037. const std::string &body, const std::string &content_type,
  7038. ContentReceiver receiver, DownloadProgress progress) {
  7039. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7040. });
  7041. }
  7042. template <typename ClientType>
  7043. void TestWithHeadersAndContentReceiverWithProgress(
  7044. ClientType &cli,
  7045. std::function<Result(ClientType &, const std::string &, const Headers &,
  7046. const std::string &, const std::string &,
  7047. ContentReceiver, DownloadProgress)>
  7048. request_func) {
  7049. Headers headers;
  7050. headers.emplace("X-Test-Header", "progress-test");
  7051. std::string received_body;
  7052. auto progress_called = false;
  7053. auto res = request_func(
  7054. cli, "/content_receiver", headers, "content", "text/plain",
  7055. [&](const char *data, size_t data_length) {
  7056. received_body.append(data, data_length);
  7057. return true;
  7058. },
  7059. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7060. progress_called = true;
  7061. return true;
  7062. });
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::OK_200, res->status);
  7065. EXPECT_EQ("content", received_body);
  7066. EXPECT_TRUE(progress_called);
  7067. }
  7068. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7069. #ifdef CPPHTTPLIB_SSL_ENABLED
  7070. using ClientT = SSLClient;
  7071. #else
  7072. using ClientT = Client;
  7073. #endif
  7074. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7076. const std::string &body, const std::string &content_type,
  7077. ContentReceiver receiver, DownloadProgress progress) {
  7078. return cli.Post(path, headers, body, content_type, receiver, progress);
  7079. });
  7080. }
  7081. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7082. #ifdef CPPHTTPLIB_SSL_ENABLED
  7083. using ClientT = SSLClient;
  7084. #else
  7085. using ClientT = Client;
  7086. #endif
  7087. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7088. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7089. const std::string &body, const std::string &content_type,
  7090. ContentReceiver receiver, DownloadProgress progress) {
  7091. return cli.Put(path, headers, body, content_type, receiver, progress);
  7092. });
  7093. }
  7094. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7095. #ifdef CPPHTTPLIB_SSL_ENABLED
  7096. using ClientT = SSLClient;
  7097. #else
  7098. using ClientT = Client;
  7099. #endif
  7100. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7101. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7102. const std::string &body, const std::string &content_type,
  7103. ContentReceiver receiver, DownloadProgress progress) {
  7104. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7105. });
  7106. }
  7107. template <typename ClientType>
  7108. void TestWithHeadersAndContentReceiverError(
  7109. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7110. const Headers &, const std::string &,
  7111. const std::string &, ContentReceiver)>
  7112. request_func) {
  7113. Headers headers;
  7114. headers.emplace("X-Error-Test", "true");
  7115. std::string received_body;
  7116. auto receiver_failed = false;
  7117. auto res =
  7118. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7119. [&](const char *data, size_t data_length) {
  7120. received_body.append(data, data_length);
  7121. receiver_failed = true;
  7122. return false;
  7123. });
  7124. ASSERT_FALSE(res);
  7125. EXPECT_TRUE(receiver_failed);
  7126. }
  7127. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7128. #ifdef CPPHTTPLIB_SSL_ENABLED
  7129. using ClientT = SSLClient;
  7130. #else
  7131. using ClientT = Client;
  7132. #endif
  7133. TestWithHeadersAndContentReceiverError<ClientT>(
  7134. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7135. const std::string &body, const std::string &content_type,
  7136. ContentReceiver receiver) {
  7137. return cli.Post(path, headers, body, content_type, receiver);
  7138. });
  7139. }
  7140. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7141. #ifdef CPPHTTPLIB_SSL_ENABLED
  7142. using ClientT = SSLClient;
  7143. #else
  7144. using ClientT = Client;
  7145. #endif
  7146. TestWithHeadersAndContentReceiverError<ClientT>(
  7147. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7148. const std::string &body, const std::string &content_type,
  7149. ContentReceiver receiver) {
  7150. return cli.Put(path, headers, body, content_type, receiver);
  7151. });
  7152. }
  7153. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7154. #ifdef CPPHTTPLIB_SSL_ENABLED
  7155. using ClientT = SSLClient;
  7156. #else
  7157. using ClientT = Client;
  7158. #endif
  7159. TestWithHeadersAndContentReceiverError<ClientT>(
  7160. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7161. const std::string &body, const std::string &content_type,
  7162. ContentReceiver receiver) {
  7163. return cli.Patch(path, headers, body, content_type, receiver);
  7164. });
  7165. }
  7166. TEST_F(ServerTest, PostQueryStringAndBody) {
  7167. auto res =
  7168. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. ASSERT_EQ(StatusCode::OK_200, res->status);
  7171. }
  7172. TEST_F(ServerTest, HTTP2Magic) {
  7173. Request req;
  7174. req.method = "PRI";
  7175. req.path = "*";
  7176. req.body = "SM";
  7177. auto res = std::make_shared<Response>();
  7178. auto error = Error::Success;
  7179. auto ret = cli_.send(req, *res, error);
  7180. ASSERT_TRUE(ret);
  7181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7182. }
  7183. TEST_F(ServerTest, KeepAlive) {
  7184. auto res = cli_.Get("/hi");
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::OK_200, res->status);
  7187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7188. EXPECT_EQ("Hello World!", res->body);
  7189. res = cli_.Get("/hi");
  7190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7191. EXPECT_EQ(StatusCode::OK_200, res->status);
  7192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7193. EXPECT_EQ("Hello World!", res->body);
  7194. res = cli_.Get("/hi");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7198. EXPECT_EQ("Hello World!", res->body);
  7199. res = cli_.Get("/not-exist");
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7202. res = cli_.Post("/empty", "", "text/plain");
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7206. EXPECT_EQ("empty", res->body);
  7207. EXPECT_EQ("close", res->get_header_value("Connection"));
  7208. res = cli_.Post(
  7209. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7210. "text/plain");
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ(StatusCode::OK_200, res->status);
  7213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7214. EXPECT_EQ("empty", res->body);
  7215. cli_.set_keep_alive(false);
  7216. res = cli_.Get("/last-request");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("close", res->get_header_value("Connection"));
  7220. }
  7221. TEST_F(ServerTest, TooManyRedirect) {
  7222. cli_.set_follow_location(true);
  7223. auto res = cli_.Get("/redirect/0");
  7224. ASSERT_TRUE(!res);
  7225. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7226. }
  7227. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7228. Request req;
  7229. req.method = "FOOBAR";
  7230. req.path = "/hi";
  7231. cli_.set_keep_alive(true);
  7232. auto res = cli_.send(req);
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7235. EXPECT_EQ("close", res->get_header_value("Connection"));
  7236. EXPECT_FALSE(cli_.is_socket_open());
  7237. }
  7238. TEST_F(ServerTest, CustomRouteReadsBody) {
  7239. const std::string xml =
  7240. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7241. Request req;
  7242. req.method = "PROPFIND";
  7243. req.path = "/dav/dir";
  7244. req.set_header("Depth", "1");
  7245. req.body = xml;
  7246. auto res = cli_.send(req);
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7249. EXPECT_EQ(xml, res->body);
  7250. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7251. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7252. }
  7253. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7254. Request req;
  7255. req.method = "PROPFIND";
  7256. req.path = "/dav/42";
  7257. auto res = cli_.send(req);
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7260. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7261. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7262. }
  7263. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7264. Request req;
  7265. req.method = "PROPFIND";
  7266. req.path = "/dav-re/123";
  7267. auto res = cli_.send(req);
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7270. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7271. }
  7272. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7273. Request req;
  7274. req.method = "MKCOL";
  7275. req.path = "/dav-mkcol";
  7276. auto res = cli_.send(req);
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. EXPECT_EQ(StatusCode::Created_201, res->status);
  7279. }
  7280. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7281. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7282. Request req;
  7283. req.method = "REPORT";
  7284. req.path = "/dav-report";
  7285. req.body = xml;
  7286. auto res = cli_.send(req);
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7289. EXPECT_EQ(xml, res->body);
  7290. }
  7291. // A content reader route must fire even when the request carries no body,
  7292. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7293. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7294. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7295. Request req;
  7296. req.method = "REPORT";
  7297. req.path = "/dav-report";
  7298. auto res = cli_.send(req);
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7301. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7302. }
  7303. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7304. Request req;
  7305. req.method = "PROPFIND";
  7306. req.path = "/not-dav";
  7307. auto res = cli_.send(req);
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7310. }
  7311. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7312. Request req;
  7313. req.method = "UNLOCK";
  7314. req.path = "/dav/dir";
  7315. cli_.set_keep_alive(true);
  7316. auto res = cli_.send(req);
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7319. EXPECT_EQ("close", res->get_header_value("Connection"));
  7320. EXPECT_FALSE(cli_.is_socket_open());
  7321. }
  7322. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7323. // The mount point serves this path, but only for GET and HEAD.
  7324. auto get_res = cli_.Get("/dir/index.html");
  7325. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7326. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7327. Request req;
  7328. req.method = "PROPFIND";
  7329. req.path = "/dir/index.html";
  7330. auto res = cli_.send(req);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7333. }
  7334. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7335. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7336. cli_.set_keep_alive(true);
  7337. for (auto i = 0; i < 2; i++) {
  7338. Request req;
  7339. req.method = "PROPFIND";
  7340. req.path = "/dav/dir";
  7341. req.body = xml;
  7342. auto res = cli_.send(req);
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7345. EXPECT_EQ(xml, res->body);
  7346. EXPECT_TRUE(cli_.is_socket_open());
  7347. }
  7348. // A built-in method must still be served on the same connection.
  7349. cli_.set_keep_alive(false);
  7350. auto res = cli_.Get("/hi");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. EXPECT_EQ("close", res->get_header_value("Connection"));
  7354. }
  7355. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7357. Request req;
  7358. req.method = "PROPFIND";
  7359. req.path = "/dav/dir";
  7360. req.set_header("Expect", "100-continue");
  7361. req.body = xml;
  7362. auto res = cli_.send(req);
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7365. EXPECT_EQ(xml, res->body);
  7366. }
  7367. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7369. TEST_F(ServerTest, Gzip) {
  7370. Headers headers;
  7371. headers.emplace("Accept-Encoding", "gzip, deflate");
  7372. auto res = cli_.Get("/compress", headers);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7376. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7377. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7378. "7890123456789012345678901234567890",
  7379. res->body);
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. }
  7382. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7383. Headers headers;
  7384. headers.emplace("Accept-Encoding", "gzip, deflate");
  7385. auto res = cli_.Get("/compress-with-charset", headers);
  7386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7388. EXPECT_EQ("application/json; charset=utf-8",
  7389. res->get_header_value("Content-Type"));
  7390. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7391. "7890123456789012345678901234567890",
  7392. res->body);
  7393. EXPECT_EQ(StatusCode::OK_200, res->status);
  7394. }
  7395. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7396. Headers headers;
  7397. headers.emplace("Accept-Encoding", "");
  7398. auto res = cli_.Get("/compress", headers);
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7402. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7404. "7890123456789012345678901234567890",
  7405. res->body);
  7406. EXPECT_EQ(StatusCode::OK_200, res->status);
  7407. }
  7408. TEST_F(ServerTest, GzipWithContentReceiver) {
  7409. Headers headers;
  7410. headers.emplace("Accept-Encoding", "gzip, deflate");
  7411. std::string body;
  7412. auto res = cli_.Get("/compress", headers,
  7413. [&](const char *data, uint64_t data_length) {
  7414. EXPECT_EQ(100U, data_length);
  7415. body.append(data, data_length);
  7416. return true;
  7417. });
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7421. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7423. "7890123456789012345678901234567890",
  7424. body);
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7428. Headers headers;
  7429. headers.emplace("Accept-Encoding", "gzip, deflate");
  7430. cli_.set_decompress(false);
  7431. auto res = cli_.Get("/compress", headers);
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7434. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7435. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7436. EXPECT_EQ(33U, res->body.size());
  7437. EXPECT_EQ(StatusCode::OK_200, res->status);
  7438. }
  7439. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7440. Headers headers;
  7441. headers.emplace("Accept-Encoding", "");
  7442. std::string body;
  7443. auto res = cli_.Get("/compress", headers,
  7444. [&](const char *data, uint64_t data_length) {
  7445. EXPECT_EQ(100U, data_length);
  7446. body.append(data, data_length);
  7447. return true;
  7448. });
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7452. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7453. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7454. "7890123456789012345678901234567890",
  7455. body);
  7456. EXPECT_EQ(StatusCode::OK_200, res->status);
  7457. }
  7458. TEST_F(ServerTest, NoGzip) {
  7459. Headers headers;
  7460. headers.emplace("Accept-Encoding", "gzip, deflate");
  7461. auto res = cli_.Get("/nocompress", headers);
  7462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7463. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7464. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7467. "7890123456789012345678901234567890",
  7468. res->body);
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. }
  7471. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7472. Headers headers;
  7473. headers.emplace("Accept-Encoding", "gzip, deflate");
  7474. std::string body;
  7475. auto res = cli_.Get("/nocompress", headers,
  7476. [&](const char *data, uint64_t data_length) {
  7477. EXPECT_EQ(100U, data_length);
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7483. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7486. "7890123456789012345678901234567890",
  7487. body);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, MultipartFormDataGzip) {
  7491. UploadFormDataItems items = {
  7492. {"key1", "test", "", ""},
  7493. {"key2", "--abcdefg123", "", ""},
  7494. };
  7495. cli_.set_compress(true);
  7496. auto res = cli_.Post("/compress-multipart", items);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. }
  7500. #endif
  7501. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7502. // Static file compression is opt-in, so these run their own server rather than
  7503. // flipping it on for the shared ServerTest fixture, which would silently
  7504. // rewrite what every other static file test is asserting.
  7505. class StaticFileCompressionTest : public ::testing::Test {
  7506. protected:
  7507. void TearDown() override {
  7508. if (t_.joinable()) {
  7509. svr_.stop();
  7510. t_.join();
  7511. }
  7512. }
  7513. int start(const std::function<void(Server &)> &configure = nullptr) {
  7514. svr_.set_mount_point("/", "./www");
  7515. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7516. res.set_file_content("./www/dir/index.html", "text/html");
  7517. });
  7518. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7519. res.set_content_provider(
  7520. 6, "text/plain",
  7521. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7522. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7523. return true;
  7524. });
  7525. });
  7526. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7527. res.set_content_provider(
  7528. 1000, "text/plain",
  7529. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7530. if (offset < 100) {
  7531. std::string data(100, 'A');
  7532. sink.write(data.data(), data.size());
  7533. return true;
  7534. }
  7535. std::this_thread::sleep_for(std::chrono::seconds(2));
  7536. std::string data(900, 'B');
  7537. sink.write(data.data(), data.size());
  7538. return true;
  7539. });
  7540. });
  7541. if (configure) { configure(svr_); }
  7542. auto port = svr_.bind_to_any_port(HOST);
  7543. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7544. svr_.wait_until_ready();
  7545. return port;
  7546. }
  7547. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7548. // Every file under ./www except 1MB.txt is smaller than the default
  7549. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7550. // it out of the way.
  7551. static void enable_without_floor(Server &svr) {
  7552. svr.set_static_file_compression(true);
  7553. svr.set_static_file_compression_min_length(0);
  7554. }
  7555. Server svr_;
  7556. std::thread t_;
  7557. };
  7558. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7559. auto port = start();
  7560. Client cli(HOST, port);
  7561. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7565. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7566. EXPECT_EQ(1048576U, res->body.size());
  7567. }
  7568. TEST_F(StaticFileCompressionTest, MountPoint) {
  7569. auto port = start(enable);
  7570. Client cli(HOST, port);
  7571. cli.set_decompress(false);
  7572. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::OK_200, res->status);
  7575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7576. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7577. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7578. // The response stays self-delimiting: a length, not a chunked body.
  7579. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7580. EXPECT_EQ(std::to_string(res->body.size()),
  7581. res->get_header_value("Content-Length"));
  7582. EXPECT_LT(res->body.size(), 1048576U);
  7583. EXPECT_FALSE(res->body.empty());
  7584. }
  7585. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7586. auto port = start(enable);
  7587. Client cli(HOST, port);
  7588. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7592. EXPECT_EQ(1048576U, res->body.size());
  7593. }
  7594. TEST_F(StaticFileCompressionTest, FileContent) {
  7595. auto port = start(enable_without_floor);
  7596. Client cli(HOST, port);
  7597. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7601. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7602. EXPECT_EQ(104U, res->body.size());
  7603. }
  7604. TEST_F(StaticFileCompressionTest, Head) {
  7605. auto port = start(enable);
  7606. Client cli(HOST, port);
  7607. cli.set_decompress(false);
  7608. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7609. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7610. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ(StatusCode::OK_200, res->status);
  7613. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7614. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7615. // HEAD still reports the size a GET would return.
  7616. EXPECT_EQ(get->get_header_value("Content-Length"),
  7617. res->get_header_value("Content-Length"));
  7618. EXPECT_TRUE(res->body.empty());
  7619. }
  7620. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7621. auto port = start(enable);
  7622. Client cli(HOST, port);
  7623. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7624. {"Accept-Encoding", "gzip"}});
  7625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7626. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7627. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7628. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7629. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7630. EXPECT_EQ("cd", res->body);
  7631. }
  7632. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7633. auto port = start(enable);
  7634. Client cli(HOST, port);
  7635. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7639. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7640. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7641. }
  7642. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7643. auto port = start(enable);
  7644. Client cli(HOST, port);
  7645. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7647. EXPECT_EQ(StatusCode::OK_200, res->status);
  7648. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7649. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7650. EXPECT_TRUE(res->body.empty());
  7651. }
  7652. TEST_F(StaticFileCompressionTest, MinLength) {
  7653. auto port = start(enable);
  7654. Client cli(HOST, port);
  7655. // 104 bytes, well under the default floor. Compressing it would add the
  7656. // gzip header and trailer to a body that already fits in one packet.
  7657. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::OK_200, res->status);
  7660. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7661. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7662. }
  7663. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7664. auto port = start([](Server &svr) {
  7665. svr.set_static_file_compression(true);
  7666. svr.set_static_file_compression_min_length(1);
  7667. });
  7668. Client cli(HOST, port);
  7669. cli.set_decompress(false);
  7670. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7673. // A 9-byte file comes back larger than it went in, because gzip's header and
  7674. // trailer outweigh anything deflate can save. That is the end of the range
  7675. // the floor exists to keep out.
  7676. EXPECT_GT(res->body.size(), 9U);
  7677. }
  7678. TEST_F(StaticFileCompressionTest, MaxLength) {
  7679. auto port = start([](Server &svr) {
  7680. svr.set_static_file_compression(true);
  7681. svr.set_static_file_compression_min_length(0);
  7682. svr.set_static_file_compression_max_length(1024);
  7683. });
  7684. Client cli(HOST, port);
  7685. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7686. // defines `small` as a macro on Windows.
  7687. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7688. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7689. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7690. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7691. // Under it: compressed.
  7692. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7693. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7694. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7695. }
  7696. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7697. auto port = start(enable_without_floor);
  7698. Client cli(HOST, port);
  7699. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7700. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7701. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7702. auto identity_etag = identity->get_header_value("ETag");
  7703. ASSERT_FALSE(identity_etag.empty());
  7704. auto gzipped =
  7705. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7706. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7707. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7708. auto gzip_etag = gzipped->get_header_value("ETag");
  7709. ASSERT_FALSE(gzip_etag.empty());
  7710. // Two representations, two validators.
  7711. EXPECT_NE(identity_etag, gzip_etag);
  7712. // Each one revalidates against the request that would produce it...
  7713. auto fresh =
  7714. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7715. {"If-None-Match", gzip_etag}});
  7716. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7717. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7718. auto fresh_identity =
  7719. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7720. {"If-None-Match", identity_etag}});
  7721. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7722. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7723. // ...and not against the other representation.
  7724. auto crossed =
  7725. cli.Get("/dir/index.html",
  7726. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7727. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7728. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7729. }
  7730. // The opt-in covers responses the server reads off disk itself. A caller's own
  7731. // known-length provider keeps its Content-Length and, more importantly, keeps
  7732. // delivering incrementally: routing it through a compressor would hold every
  7733. // write back until zlib's window filled.
  7734. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7735. auto port = start(enable);
  7736. Client cli(HOST, port);
  7737. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7741. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7742. EXPECT_EQ("aaabbb", res->body);
  7743. }
  7744. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7745. auto port = start(enable);
  7746. Client cli(HOST, port);
  7747. cli.set_read_timeout(1, 0);
  7748. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7749. Headers{{"Accept-Encoding", "gzip"}});
  7750. ASSERT_TRUE(handle.is_valid());
  7751. // The provider writes 100 bytes and then stalls for longer than the read
  7752. // timeout. Those first bytes have to arrive anyway: run the response through
  7753. // a compressor and zlib holds them until its window fills, so the read would
  7754. // come back empty instead.
  7755. char buf[256];
  7756. auto n = handle.read(buf, sizeof(buf));
  7757. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7758. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7759. }
  7760. #endif
  7761. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7762. TEST_F(ServerTest, Brotli) {
  7763. Headers headers;
  7764. headers.emplace("Accept-Encoding", "br");
  7765. auto res = cli_.Get("/compress", headers);
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7769. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7770. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7771. "7890123456789012345678901234567890",
  7772. res->body);
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. }
  7775. #endif
  7776. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7777. TEST_F(ServerTest, Zstd) {
  7778. Headers headers;
  7779. headers.emplace("Accept-Encoding", "zstd");
  7780. auto res = cli_.Get("/compress", headers);
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7783. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7784. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7785. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7786. "7890123456789012345678901234567890",
  7787. res->body);
  7788. EXPECT_EQ(StatusCode::OK_200, res->status);
  7789. }
  7790. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7791. Headers headers;
  7792. headers.emplace("Accept-Encoding", "");
  7793. auto res = cli_.Get("/compress", headers);
  7794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7795. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7796. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7797. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7799. "7890123456789012345678901234567890",
  7800. res->body);
  7801. EXPECT_EQ(StatusCode::OK_200, res->status);
  7802. }
  7803. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7804. Headers headers;
  7805. headers.emplace("Accept-Encoding", "zstd");
  7806. std::string body;
  7807. auto res = cli_.Get("/compress", headers,
  7808. [&](const char *data, uint64_t data_length) {
  7809. EXPECT_EQ(100U, data_length);
  7810. body.append(data, data_length);
  7811. return true;
  7812. });
  7813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7814. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7816. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7818. "7890123456789012345678901234567890",
  7819. body);
  7820. EXPECT_EQ(StatusCode::OK_200, res->status);
  7821. }
  7822. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7823. Headers headers;
  7824. headers.emplace("Accept-Encoding", "zstd");
  7825. cli_.set_decompress(false);
  7826. auto res = cli_.Get("/compress", headers);
  7827. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7828. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7829. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7830. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7834. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. ASSERT_EQ(26U, res->body.size());
  7837. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7838. 0);
  7839. }
  7840. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7841. Headers headers;
  7842. headers.emplace("Accept-Encoding", "");
  7843. std::string body;
  7844. auto res = cli_.Get("/compress", headers,
  7845. [&](const char *data, uint64_t data_length) {
  7846. EXPECT_EQ(100U, data_length);
  7847. body.append(data, data_length);
  7848. return true;
  7849. });
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7853. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7855. "7890123456789012345678901234567890",
  7856. body);
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. }
  7859. TEST_F(ServerTest, NoZstd) {
  7860. Headers headers;
  7861. headers.emplace("Accept-Encoding", "zstd");
  7862. auto res = cli_.Get("/nocompress", headers);
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7865. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7866. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7867. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7868. "7890123456789012345678901234567890",
  7869. res->body);
  7870. EXPECT_EQ(StatusCode::OK_200, res->status);
  7871. }
  7872. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7873. Headers headers;
  7874. headers.emplace("Accept-Encoding", "zstd");
  7875. std::string body;
  7876. auto res = cli_.Get("/nocompress", headers,
  7877. [&](const char *data, uint64_t data_length) {
  7878. EXPECT_EQ(100U, data_length);
  7879. body.append(data, data_length);
  7880. return true;
  7881. });
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7884. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7885. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7886. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7887. "7890123456789012345678901234567890",
  7888. body);
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. }
  7891. // TODO: How to enable zstd ??
  7892. TEST_F(ServerTest, MultipartFormDataZstd) {
  7893. UploadFormDataItems items = {
  7894. {"key1", "test", "", ""},
  7895. {"key2", "--abcdefg123", "", ""},
  7896. };
  7897. Headers headers;
  7898. headers.emplace("Accept-Encoding", "zstd");
  7899. cli_.set_compress(true);
  7900. auto res = cli_.Post("/compress-multipart", headers, items);
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. }
  7904. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7905. Headers headers;
  7906. headers.emplace("Accept-Encoding", "zstd");
  7907. cli_.set_compress(true);
  7908. auto res = cli_.Put(
  7909. "/put", headers, 3,
  7910. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7911. sink.os << "PUT";
  7912. return true;
  7913. },
  7914. "text/plain");
  7915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7916. EXPECT_EQ(StatusCode::OK_200, res->status);
  7917. EXPECT_EQ("PUT", res->body);
  7918. }
  7919. // Pre-compression logging tests
  7920. TEST_F(ServerTest, PreCompressionLogging) {
  7921. // Test data for compression (matches the actual /compress endpoint content)
  7922. const std::string test_content =
  7923. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7924. "3456789012345678901234567890";
  7925. // Variables to capture logging data
  7926. std::string pre_compression_body;
  7927. std::string pre_compression_content_type;
  7928. std::string pre_compression_content_encoding;
  7929. std::string post_compression_body;
  7930. std::string post_compression_content_type;
  7931. std::string post_compression_content_encoding;
  7932. // Set up pre-compression logger
  7933. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7934. const Response &res) {
  7935. pre_compression_body = res.body;
  7936. pre_compression_content_type = res.get_header_value("Content-Type");
  7937. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7938. });
  7939. // Set up post-compression logger
  7940. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7941. post_compression_body = res.body;
  7942. post_compression_content_type = res.get_header_value("Content-Type");
  7943. post_compression_content_encoding =
  7944. res.get_header_value("Content-Encoding");
  7945. });
  7946. // Test with gzip compression
  7947. Headers headers;
  7948. headers.emplace("Accept-Encoding", "gzip");
  7949. auto res = cli_.Get("/compress", headers);
  7950. // Verify response was compressed
  7951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7954. // Verify pre-compression logger captured uncompressed content
  7955. EXPECT_EQ(test_content, pre_compression_body);
  7956. EXPECT_EQ("text/plain", pre_compression_content_type);
  7957. EXPECT_TRUE(pre_compression_content_encoding
  7958. .empty()); // No encoding header before compression
  7959. // Verify post-compression logger captured compressed content
  7960. EXPECT_NE(test_content,
  7961. post_compression_body); // Should be different after compression
  7962. EXPECT_EQ("text/plain", post_compression_content_type);
  7963. EXPECT_EQ("gzip", post_compression_content_encoding);
  7964. // Verify compressed content is smaller
  7965. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7966. }
  7967. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7968. const std::string test_content =
  7969. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7970. "3456789012345678901234567890";
  7971. std::string pre_compression_body;
  7972. std::string post_compression_body;
  7973. svr_.set_pre_compression_logger(
  7974. [&](const Request & /*req*/, const Response &res) {
  7975. pre_compression_body = res.body;
  7976. });
  7977. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7978. post_compression_body = res.body;
  7979. });
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "br");
  7982. auto res = cli_.Get("/compress", headers);
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7986. // Verify pre-compression content is uncompressed
  7987. EXPECT_EQ(test_content, pre_compression_body);
  7988. // Verify post-compression content is compressed
  7989. EXPECT_NE(test_content, post_compression_body);
  7990. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7991. }
  7992. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7993. const std::string test_content =
  7994. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7995. "3456789012345678901234567890";
  7996. std::string pre_compression_body;
  7997. std::string post_compression_body;
  7998. svr_.set_pre_compression_logger(
  7999. [&](const Request & /*req*/, const Response &res) {
  8000. pre_compression_body = res.body;
  8001. });
  8002. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8003. post_compression_body = res.body;
  8004. });
  8005. // Request without compression (use /nocompress endpoint)
  8006. Headers headers;
  8007. auto res = cli_.Get("/nocompress", headers);
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::OK_200, res->status);
  8010. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8011. // Pre-compression logger should not be called when no compression is applied
  8012. EXPECT_TRUE(
  8013. pre_compression_body.empty()); // Pre-compression logger not called
  8014. EXPECT_EQ(
  8015. test_content,
  8016. post_compression_body); // Post-compression logger captures final content
  8017. }
  8018. TEST_F(ServerTest, LoggerSeesContentLength) {
  8019. size_t logged_content_length = 0;
  8020. std::string logged_content_length_header;
  8021. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8022. logged_content_length = res.content_length_;
  8023. logged_content_length_header = res.get_header_value("Content-Length");
  8024. });
  8025. auto res = cli_.Get("/nocompress");
  8026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. EXPECT_EQ(res->body.size(), logged_content_length);
  8029. EXPECT_EQ(std::to_string(logged_content_length),
  8030. logged_content_length_header);
  8031. }
  8032. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8033. const std::string test_content =
  8034. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8035. "3456789012345678901234567890";
  8036. std::string pre_compression_body;
  8037. bool pre_logger_called = false;
  8038. // Set only pre-compression logger
  8039. svr_.set_pre_compression_logger(
  8040. [&](const Request & /*req*/, const Response &res) {
  8041. pre_compression_body = res.body;
  8042. pre_logger_called = true;
  8043. });
  8044. Headers headers;
  8045. headers.emplace("Accept-Encoding", "gzip");
  8046. auto res = cli_.Get("/compress", headers);
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8050. // Verify pre-compression logger was called
  8051. EXPECT_TRUE(pre_logger_called);
  8052. EXPECT_EQ(test_content, pre_compression_body);
  8053. }
  8054. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8055. {
  8056. // Test with Expect: 100-continue header - success case
  8057. // Server returns 100 Continue, client sends body, server returns 200 OK
  8058. Request req;
  8059. req.method = "POST";
  8060. req.path = "/post-large";
  8061. req.set_header("Expect", "100-continue");
  8062. req.body = LARGE_DATA;
  8063. Response res;
  8064. auto error = Error::Success;
  8065. cli_.set_keep_alive(true);
  8066. auto ret = cli_.send(req, res, error);
  8067. EXPECT_TRUE(ret);
  8068. EXPECT_EQ(StatusCode::OK_200, res.status);
  8069. EXPECT_EQ(LARGE_DATA, res.body);
  8070. }
  8071. {
  8072. // Test with Expect: 100-continue header - error case
  8073. // Client should not send the body when server returns an error
  8074. Request req;
  8075. req.method = "POST";
  8076. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8077. req.set_header("Expect", "100-continue");
  8078. req.body = LARGE_DATA;
  8079. Response res;
  8080. auto error = Error::Success;
  8081. auto start = std::chrono::high_resolution_clock::now();
  8082. cli_.set_keep_alive(true);
  8083. auto ret = cli_.send(req, res, error);
  8084. auto end = std::chrono::high_resolution_clock::now();
  8085. auto elapsed =
  8086. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8087. .count();
  8088. // With Expect: 100-continue, request completes successfully but with error
  8089. EXPECT_TRUE(ret);
  8090. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8091. EXPECT_EQ("close", res.get_header_value("Connection"));
  8092. EXPECT_FALSE(cli_.is_socket_open());
  8093. EXPECT_LE(elapsed, 2000);
  8094. }
  8095. {
  8096. // Send an extra GET request to ensure error recovery without hanging
  8097. Request req;
  8098. req.method = "GET";
  8099. req.path = "/hi";
  8100. auto start = std::chrono::high_resolution_clock::now();
  8101. auto res = cli_.send(req);
  8102. auto end = std::chrono::high_resolution_clock::now();
  8103. auto elapsed =
  8104. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8105. .count();
  8106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8107. EXPECT_EQ(StatusCode::OK_200, res->status);
  8108. EXPECT_EQ("Hello World!", res->body);
  8109. EXPECT_LE(elapsed, 500);
  8110. }
  8111. }
  8112. TEST(ZstdDecompressor, ChunkedDecompression) {
  8113. std::string data;
  8114. for (size_t i = 0; i < 32 * 1024; ++i) {
  8115. data.push_back(static_cast<char>('a' + i % 26));
  8116. }
  8117. std::string compressed_data;
  8118. {
  8119. httplib::detail::zstd_compressor compressor;
  8120. bool result = compressor.compress(
  8121. data.data(), data.size(),
  8122. /*last=*/true,
  8123. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8124. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8125. compressed_data_size);
  8126. return true;
  8127. });
  8128. ASSERT_TRUE(result);
  8129. }
  8130. std::string decompressed_data;
  8131. {
  8132. httplib::detail::zstd_decompressor decompressor;
  8133. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8134. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8135. size_t chunk_size = 130;
  8136. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8137. chunk_begin += chunk_size) {
  8138. size_t current_chunk_size =
  8139. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8140. bool result = decompressor.decompress(
  8141. compressed_data.data() + chunk_begin, current_chunk_size,
  8142. [&](const char *decompressed_data_chunk,
  8143. size_t decompressed_data_chunk_size) {
  8144. decompressed_data.insert(decompressed_data.size(),
  8145. decompressed_data_chunk,
  8146. decompressed_data_chunk_size);
  8147. return true;
  8148. });
  8149. ASSERT_TRUE(result);
  8150. }
  8151. }
  8152. ASSERT_EQ(data, decompressed_data);
  8153. }
  8154. TEST(ZstdDecompressor, Decompress) {
  8155. std::string original_text = "Compressed with ZSTD";
  8156. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8157. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8158. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8159. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8160. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8161. std::string decompressed_data;
  8162. {
  8163. httplib::detail::zstd_decompressor decompressor;
  8164. bool result = decompressor.decompress(
  8165. compressed_data.data(), compressed_data.size(),
  8166. [&](const char *decompressed_data_chunk,
  8167. size_t decompressed_data_chunk_size) {
  8168. decompressed_data.insert(decompressed_data.size(),
  8169. decompressed_data_chunk,
  8170. decompressed_data_chunk_size);
  8171. return true;
  8172. });
  8173. ASSERT_TRUE(result);
  8174. }
  8175. ASSERT_EQ(original_text, decompressed_data);
  8176. }
  8177. #endif
  8178. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8179. // separate chunks so that the server sees each part in its own read(). Used to
  8180. // place a read boundary at a specific offset of a request body.
  8181. static bool send_request_in_parts(time_t read_timeout_sec,
  8182. const std::vector<std::string> &parts,
  8183. std::string *resp = nullptr,
  8184. int port = PORT) {
  8185. auto error = Error::Success;
  8186. auto client_sock = detail::create_client_socket(
  8187. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8188. /*connection_timeout_sec=*/5, 0,
  8189. /*read_timeout_sec=*/5, 0,
  8190. /*write_timeout_sec=*/5, 0, std::string(), error);
  8191. if (client_sock == INVALID_SOCKET) { return false; }
  8192. auto ret = detail::process_client_socket(
  8193. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8194. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8195. for (size_t i = 0; i < parts.size(); i++) {
  8196. const auto &part = parts[i];
  8197. if (part.size() !=
  8198. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8199. return false;
  8200. }
  8201. if (i + 1 < parts.size()) {
  8202. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8203. }
  8204. }
  8205. char buf[512];
  8206. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8207. while (line_reader.getline()) {
  8208. if (resp) { *resp += line_reader.ptr(); }
  8209. }
  8210. return true;
  8211. });
  8212. detail::close_socket(client_sock);
  8213. return ret;
  8214. }
  8215. // Sends a raw request to a server listening at HOST:PORT.
  8216. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8217. std::string *resp = nullptr, int port = PORT) {
  8218. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8219. }
  8220. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8221. Server svr;
  8222. std::string header_value;
  8223. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8224. header_value = req.get_header_value("foo");
  8225. res.set_content("ok", "text/plain");
  8226. });
  8227. thread t = thread([&] { svr.listen(HOST, PORT); });
  8228. auto se = detail::scope_exit([&] {
  8229. svr.stop();
  8230. t.join();
  8231. ASSERT_FALSE(svr.is_running());
  8232. });
  8233. svr.wait_until_ready();
  8234. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8235. // like characters are not treated the same - use vertical tab and escape.
  8236. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8237. "foo: \t \v bar \x1B\t \r\n"
  8238. "Connection: close\r\n"
  8239. "\r\n";
  8240. std::string res;
  8241. ASSERT_TRUE(send_request(5, req, &res));
  8242. EXPECT_EQ(header_value, "");
  8243. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8244. }
  8245. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8246. Server svr;
  8247. std::string received;
  8248. svr.Get("/order", [&](const Request &req, Response &res) {
  8249. received = entries_to_string(req.headers);
  8250. res.set_content("ok", "text/plain");
  8251. });
  8252. auto port = svr.bind_to_any_port(HOST);
  8253. thread t = thread([&] { svr.listen_after_bind(); });
  8254. auto se = detail::scope_exit([&] {
  8255. svr.stop();
  8256. t.join();
  8257. ASSERT_FALSE(svr.is_running());
  8258. });
  8259. svr.wait_until_ready();
  8260. const std::string req = "GET /order HTTP/1.1\r\n"
  8261. "X-First: 1\r\n"
  8262. "X-Dup: a\r\n"
  8263. "X-Second: 2\r\n"
  8264. "X-Dup: b\r\n"
  8265. "Connection: close\r\n"
  8266. "\r\n";
  8267. std::string res;
  8268. ASSERT_TRUE(send_request(5, req, &res, port));
  8269. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8270. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8271. }
  8272. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8273. Server svr;
  8274. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8275. res.set_header("Set-Cookie", "first=1");
  8276. res.set_header("X-Between", "y");
  8277. res.set_header("Set-Cookie", "second=2");
  8278. res.set_content("ok", "text/plain");
  8279. });
  8280. auto port = svr.bind_to_any_port(HOST);
  8281. thread t = thread([&] { svr.listen_after_bind(); });
  8282. auto se = detail::scope_exit([&] {
  8283. svr.stop();
  8284. t.join();
  8285. ASSERT_FALSE(svr.is_running());
  8286. });
  8287. svr.wait_until_ready();
  8288. Client cli(HOST, port);
  8289. auto res = cli.Get("/cookies");
  8290. ASSERT_TRUE(res);
  8291. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8292. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8293. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8294. }
  8295. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8296. Server svr;
  8297. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8298. auto i = new int(0);
  8299. res.set_header("Trailer", "X-Safe, X-Reflected");
  8300. res.set_chunked_content_provider(
  8301. "text/plain",
  8302. [i](size_t /*offset*/, DataSink &sink) {
  8303. if (*i == 0) {
  8304. sink.os << "body";
  8305. } else {
  8306. Headers trailer;
  8307. // A valid trailer that must survive.
  8308. trailer.emplace("X-Safe", "safe");
  8309. // Attacker-controlled value carrying CR/LF (response splitting).
  8310. trailer.emplace("X-Reflected",
  8311. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8312. // Attacker-controlled name carrying CR/LF.
  8313. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8314. sink.done_with_trailer(trailer);
  8315. }
  8316. (*i)++;
  8317. return true;
  8318. },
  8319. [i](bool /*success*/) { delete i; });
  8320. });
  8321. thread t = thread([&] { svr.listen(HOST, PORT); });
  8322. auto se = detail::scope_exit([&] {
  8323. svr.stop();
  8324. t.join();
  8325. ASSERT_FALSE(svr.is_running());
  8326. });
  8327. svr.wait_until_ready();
  8328. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8329. "Host: " + HOST +
  8330. "\r\n"
  8331. "Connection: close\r\n"
  8332. "\r\n";
  8333. std::string res;
  8334. ASSERT_TRUE(send_request(5, req, &res));
  8335. // The injected fields must not appear anywhere in the raw response.
  8336. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8337. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8338. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8339. // Invalid trailers are dropped entirely, matching set_header().
  8340. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8341. // The valid trailer still passes through.
  8342. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8343. }
  8344. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8345. Server svr;
  8346. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8347. // res.headers is a public field an application can populate directly,
  8348. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8349. // A valid header that must survive.
  8350. res.headers.emplace("X-Safe", "safe");
  8351. // Attacker-controlled value carrying CR/LF (response splitting).
  8352. res.headers.emplace("X-Reflected",
  8353. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8354. // Attacker-controlled name carrying CR/LF.
  8355. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8356. res.set_content("body", "text/plain");
  8357. });
  8358. thread t = thread([&] { svr.listen(HOST, PORT); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8366. "Host: " + HOST +
  8367. "\r\n"
  8368. "Connection: close\r\n"
  8369. "\r\n";
  8370. std::string res;
  8371. ASSERT_TRUE(send_request(5, req, &res));
  8372. // The injected fields must not appear anywhere in the raw response.
  8373. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8374. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8375. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8376. // Invalid headers are dropped entirely, matching set_header().
  8377. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8378. // The valid header still passes through.
  8379. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8380. }
  8381. // Forward declaration: in split builds split.py strips `inline` and moves the
  8382. // definition into httplib.cc, so detail::write_request_line is not visible from
  8383. // the public httplib.h. Re-declaring it here lets the tests link against the
  8384. // symbol in both header-only and split builds.
  8385. namespace httplib {
  8386. namespace detail {
  8387. ssize_t write_request_line(Stream &strm, const std::string &method,
  8388. const std::string &path);
  8389. } // namespace detail
  8390. } // namespace httplib
  8391. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8392. // A well-formed target is written verbatim.
  8393. {
  8394. detail::BufferStream strm;
  8395. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8396. EXPECT_GT(n, 0);
  8397. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8398. }
  8399. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8400. // otherwise it splits the request line and injects a header or a whole
  8401. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8402. // when path encoding is disabled.
  8403. const std::string evil_targets[] = {
  8404. "/a\r\nInjected: pwned",
  8405. "/a\rInjected",
  8406. "/a\nInjected",
  8407. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8408. };
  8409. for (const auto &evil : evil_targets) {
  8410. detail::BufferStream strm;
  8411. auto n = detail::write_request_line(strm, "GET", evil);
  8412. EXPECT_LT(n, 0);
  8413. EXPECT_TRUE(strm.get_buffer().empty());
  8414. }
  8415. }
  8416. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8417. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8418. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8419. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8420. // client must fail cleanly with Error::Write instead of putting a
  8421. // request-line-less, header-injecting request on the wire.
  8422. Server svr;
  8423. svr.Get("/a", [](const Request &, Response &res) {
  8424. res.set_content("ok", "text/plain");
  8425. });
  8426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8427. auto se = detail::scope_exit([&] {
  8428. svr.stop();
  8429. thread.join();
  8430. ASSERT_FALSE(svr.is_running());
  8431. });
  8432. svr.wait_until_ready();
  8433. {
  8434. Client cli(HOST, PORT);
  8435. cli.set_path_encode(false);
  8436. // The request is rejected before anything is written, so the connection
  8437. // stays silent and the subsequent response read would otherwise block for
  8438. // the full default read timeout. Shorten it -- the assertion is on the
  8439. // error, not the timeout.
  8440. cli.set_read_timeout(1, 0);
  8441. auto res = cli.Get("/a\r\nInjected: pwned");
  8442. EXPECT_FALSE(res);
  8443. EXPECT_EQ(Error::Write, res.error());
  8444. }
  8445. }
  8446. // Sends a raw request and verifies that there isn't a crash or exception.
  8447. static void test_raw_request(const std::string &req,
  8448. std::string *out = nullptr) {
  8449. Server svr;
  8450. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8451. res.set_content("ok", "text/plain");
  8452. });
  8453. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8454. res.set_content("ok", "text/plain");
  8455. });
  8456. svr.Get("/header_field_value_check",
  8457. [&](const Request & /*req*/, Response &res) {
  8458. res.set_content("ok", "text/plain");
  8459. });
  8460. svr.CustomRoute("PROPFIND", "/dav",
  8461. [&](const Request & /*req*/, Response &res) {
  8462. res.status = StatusCode::MultiStatus_207;
  8463. });
  8464. // Server read timeout must be longer than the client read timeout for the
  8465. // bug to reproduce, probably to force the server to process a request
  8466. // without a trailing blank line.
  8467. const time_t client_read_timeout_sec = 1;
  8468. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8469. bool listen_thread_ok = false;
  8470. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8471. auto se = detail::scope_exit([&] {
  8472. svr.stop();
  8473. t.join();
  8474. ASSERT_FALSE(svr.is_running());
  8475. EXPECT_TRUE(listen_thread_ok);
  8476. });
  8477. svr.wait_until_ready();
  8478. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8479. }
  8480. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8481. // A certain header line causes an exception if the header property is parsed
  8482. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8483. test_raw_request(
  8484. "GET /hi HTTP/1.1\r\n"
  8485. " : "
  8486. " "
  8487. " ");
  8488. }
  8489. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8490. // A certain header line causes an exception if the header property *name* is
  8491. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8492. // greedy matcher and requires backtracking when there are a lot of ":"
  8493. // characters.
  8494. // This occurs with libc++ but not libstdc++.
  8495. test_raw_request(
  8496. "GET /hi HTTP/1.1\r\n"
  8497. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8498. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8499. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8500. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8501. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8502. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8503. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8504. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8505. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8506. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8507. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8508. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8509. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8510. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8511. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8512. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8513. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8514. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8515. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8516. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8517. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8518. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8519. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8520. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8521. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8522. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8523. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8524. "&&&%%%");
  8525. }
  8526. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8527. // Make sure this doesn't crash the server.
  8528. // In a previous version of the header line regex, the "\r" rendered the line
  8529. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8530. // a new position where the leading white space ended and the field value
  8531. // began.
  8532. // The crash occurs with libc++ but not libstdc++.
  8533. test_raw_request("GET /hi HTTP/1.1\r\n"
  8534. "a:" +
  8535. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8536. "\r\n"
  8537. "\r\n");
  8538. }
  8539. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8540. std::string out;
  8541. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8542. "Content-Type: text/plain\r\n"
  8543. "Transfer-Encoding: chunked\r\n"
  8544. "\r\n"
  8545. "nothex\r\n",
  8546. &out);
  8547. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8548. }
  8549. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8550. std::string out;
  8551. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8552. "Content-Type: text/plain\r\n"
  8553. "Transfer-Encoding: chunked\r\n"
  8554. "\r\n"
  8555. "3\r\n"
  8556. "xyz\r\n"
  8557. "NaN\r\n",
  8558. &out);
  8559. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8560. }
  8561. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8562. std::string out;
  8563. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8564. "Content-Type: text/plain\r\n"
  8565. "Transfer-Encoding: chunked\r\n"
  8566. "\r\n"
  8567. // Length is too large for 64 bits.
  8568. "1ffffffffffffffff\r\n"
  8569. "xyz\r\n",
  8570. &out);
  8571. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8572. }
  8573. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8574. test_raw_request("GET /hi HTTP/1.1\r\n"
  8575. "Content-Type: text/plain\r\n\r");
  8576. }
  8577. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8578. std::string out;
  8579. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8580. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8581. }
  8582. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8583. Server svr;
  8584. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8585. EXPECT_TRUE(!req.remote_addr.empty());
  8586. });
  8587. thread t = thread([&] { svr.listen(HOST, PORT); });
  8588. auto se = detail::scope_exit([&] {
  8589. svr.stop();
  8590. t.join();
  8591. ASSERT_FALSE(svr.is_running());
  8592. });
  8593. svr.wait_until_ready();
  8594. // Send an invalid request line to trigger Bad Request
  8595. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8596. std::string out;
  8597. ASSERT_TRUE(send_request(5, bad_req, &out));
  8598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8599. }
  8600. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8601. // answered right away rather than blocking on a read that waits for EOF.
  8602. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8603. std::string out;
  8604. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8605. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8606. }
  8607. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8608. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8609. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8610. for (const auto *method : methods) {
  8611. Server svr;
  8612. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8613. EXPECT_FALSE(svr.is_valid()) << method;
  8614. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8615. }
  8616. }
  8617. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8618. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8619. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8620. for (const auto *method : methods) {
  8621. Server svr;
  8622. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8623. EXPECT_FALSE(svr.is_valid()) << method;
  8624. }
  8625. }
  8626. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8627. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8628. "COPY", "MOVE", "LOCK",
  8629. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8630. Server svr;
  8631. for (const auto *method : methods) {
  8632. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8633. }
  8634. EXPECT_TRUE(svr.is_valid());
  8635. }
  8636. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8637. Server svr;
  8638. svr.CustomRoute("POST", "/x",
  8639. [](const Request &, Response &, const ContentReader &) {});
  8640. EXPECT_FALSE(svr.is_valid());
  8641. }
  8642. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8643. Server svr;
  8644. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8645. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8646. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8647. EXPECT_FALSE(svr.is_valid());
  8648. }
  8649. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8650. Server svr;
  8651. auto captured = Error::Success;
  8652. svr.set_error_logger(
  8653. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8654. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8655. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8656. }
  8657. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8658. std::string out;
  8659. std::string request(
  8660. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8661. test_raw_request(request, &out);
  8662. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8663. }
  8664. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8665. std::string out;
  8666. std::string request(
  8667. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8668. test_raw_request(request, &out);
  8669. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8670. }
  8671. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8672. std::string out;
  8673. std::string request(
  8674. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8675. test_raw_request(request, &out);
  8676. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8677. }
  8678. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8679. std::string out;
  8680. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8681. "Test: \r\n\r\n",
  8682. &out);
  8683. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8684. }
  8685. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8686. Server svr;
  8687. std::string x_custom;
  8688. std::string cookie;
  8689. std::string xff;
  8690. std::string x_unicode;
  8691. std::string x_iis;
  8692. svr.Get("/check", [&](const Request &req, Response &res) {
  8693. x_custom = req.get_header_value("X-Custom");
  8694. cookie = req.get_header_value("Cookie");
  8695. xff = req.get_header_value("X-Forwarded-For");
  8696. x_unicode = req.get_header_value("X-Unicode");
  8697. x_iis = req.get_header_value("X-IIS");
  8698. res.set_content("ok", "text/plain");
  8699. });
  8700. thread t = thread([&] { svr.listen(HOST, PORT); });
  8701. auto se = detail::scope_exit([&] {
  8702. svr.stop();
  8703. t.join();
  8704. ASSERT_FALSE(svr.is_running());
  8705. });
  8706. svr.wait_until_ready();
  8707. const std::string req = "GET /check HTTP/1.1\r\n"
  8708. "Host: localhost\r\n"
  8709. "X-Custom: a%0D%0AInjected: b\r\n"
  8710. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8711. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8712. "X-Unicode: %E3%81%82\r\n"
  8713. "X-IIS: %u00E9\r\n"
  8714. "Connection: close\r\n"
  8715. "\r\n";
  8716. std::string res;
  8717. ASSERT_TRUE(send_request(5, req, &res));
  8718. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8719. // Every value must be returned verbatim (wire form), with no decoding.
  8720. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8721. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8722. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8723. EXPECT_EQ("%E3%81%82", x_unicode);
  8724. EXPECT_EQ("%u00E9", x_iis);
  8725. }
  8726. // Applications that previously relied on automatic percent-decoding can
  8727. // reproduce the old behavior by explicitly calling decode_path_component()
  8728. // or, for RFC 3986 conformance, decode_uri_component().
  8729. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8730. Server svr;
  8731. std::string decoded;
  8732. svr.Get("/check", [&](const Request &req, Response &res) {
  8733. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8734. res.set_content("ok", "text/plain");
  8735. });
  8736. thread t = thread([&] { svr.listen(HOST, PORT); });
  8737. auto se = detail::scope_exit([&] {
  8738. svr.stop();
  8739. t.join();
  8740. ASSERT_FALSE(svr.is_running());
  8741. });
  8742. svr.wait_until_ready();
  8743. const std::string req = "GET /check HTTP/1.1\r\n"
  8744. "Host: localhost\r\n"
  8745. "X-Custom: hello%20world\r\n"
  8746. "Connection: close\r\n"
  8747. "\r\n";
  8748. std::string res;
  8749. ASSERT_TRUE(send_request(5, req, &res));
  8750. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8751. EXPECT_EQ("hello world", decoded);
  8752. }
  8753. // Regression test for #2033. Browsers send Referer values that include
  8754. // percent-encoded characters such as %0A inside the URL. Decoding the
  8755. // header value would either trip the post-decode CR/LF/NUL guard (the
  8756. // original bug, returning 400) or, after that guard was relaxed, silently
  8757. // store a literal LF — both unacceptable. The wire form must round-trip.
  8758. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8759. Server svr;
  8760. std::string referer;
  8761. svr.Get("/check", [&](const Request &req, Response &res) {
  8762. referer = req.get_header_value("Referer");
  8763. res.set_content("ok", "text/plain");
  8764. });
  8765. thread t = thread([&] { svr.listen(HOST, PORT); });
  8766. auto se = detail::scope_exit([&] {
  8767. svr.stop();
  8768. t.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. const std::string req = "GET /check HTTP/1.1\r\n"
  8773. "Host: localhost\r\n"
  8774. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8775. "Connection: close\r\n"
  8776. "\r\n";
  8777. std::string res;
  8778. ASSERT_TRUE(send_request(5, req, &res));
  8779. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8780. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8781. }
  8782. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8783. Server svr;
  8784. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8785. res.set_header("Cache-Control", "no-cache");
  8786. res.set_chunked_content_provider(
  8787. "text/event-stream", [](size_t offset, DataSink &sink) {
  8788. std::string s = "data:";
  8789. s += std::to_string(offset);
  8790. s += "\n\n";
  8791. auto ret = sink.write(s.data(), s.size());
  8792. EXPECT_TRUE(ret);
  8793. std::this_thread::sleep_for(std::chrono::seconds(1));
  8794. return true;
  8795. });
  8796. });
  8797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8798. svr.wait_until_ready();
  8799. Client client(HOST, PORT);
  8800. const Headers headers = {{"Accept", "text/event-stream"}};
  8801. auto get_thread = std::thread([&client, &headers]() {
  8802. auto res = client.Get(
  8803. "/events", headers,
  8804. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8805. });
  8806. auto se = detail::scope_exit([&] {
  8807. svr.stop();
  8808. get_thread.join();
  8809. listen_thread.join();
  8810. ASSERT_FALSE(svr.is_running());
  8811. });
  8812. // Give GET time to get a few messages.
  8813. std::this_thread::sleep_for(std::chrono::seconds(2));
  8814. }
  8815. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8816. httplib::Server svr;
  8817. svr.Post("/hi",
  8818. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8819. res.status = StatusCode::OK_200;
  8820. });
  8821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8822. svr.wait_until_ready();
  8823. Client cli(HOST, PORT);
  8824. auto res = cli.Post("/hi", "data", "text/plain");
  8825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8826. EXPECT_EQ(StatusCode::OK_200, res->status);
  8827. svr.stop();
  8828. thread.join();
  8829. ASSERT_FALSE(svr.is_running());
  8830. res = cli.Post("/hi", "data", "text/plain");
  8831. ASSERT_FALSE(res);
  8832. }
  8833. TEST(ServerStopTest, ListenFailure) {
  8834. Server svr;
  8835. auto t = thread([&]() {
  8836. auto ret = svr.listen("????", PORT);
  8837. EXPECT_FALSE(ret);
  8838. });
  8839. svr.wait_until_ready();
  8840. svr.stop();
  8841. t.join();
  8842. }
  8843. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8844. TEST(ServerStopTest, Decommision) {
  8845. Server svr;
  8846. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8847. for (int i = 0; i < 4; i++) {
  8848. auto is_even = !(i % 2);
  8849. std::thread t{[&] {
  8850. try {
  8851. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8852. if (is_even) {
  8853. throw std::runtime_error("Some thing that happens to go wrong.");
  8854. }
  8855. svr.listen(HOST, PORT);
  8856. } catch (...) { svr.decommission(); }
  8857. }};
  8858. svr.wait_until_ready();
  8859. // Server is up
  8860. {
  8861. Client cli(HOST, PORT);
  8862. auto res = cli.Get("/hi");
  8863. if (is_even) {
  8864. EXPECT_FALSE(res);
  8865. } else {
  8866. EXPECT_TRUE(res);
  8867. EXPECT_EQ("hi...", res->body);
  8868. }
  8869. }
  8870. svr.stop();
  8871. t.join();
  8872. // Server is down...
  8873. {
  8874. Client cli(HOST, PORT);
  8875. auto res = cli.Get("/hi");
  8876. EXPECT_FALSE(res);
  8877. }
  8878. }
  8879. }
  8880. #endif
  8881. // Helper function for string body upload progress tests
  8882. template <typename SetupHandler, typename ClientCall>
  8883. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8884. ClientCall &&client_call,
  8885. const string &body) {
  8886. Server svr;
  8887. setup_handler(svr);
  8888. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. t.join();
  8892. });
  8893. svr.wait_until_ready();
  8894. Client cli(HOST, PORT);
  8895. vector<uint64_t> progress_values;
  8896. bool progress_called = false;
  8897. auto res =
  8898. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8899. progress_values.push_back(current);
  8900. progress_called = true;
  8901. return true;
  8902. });
  8903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8904. EXPECT_EQ(200, res->status);
  8905. EXPECT_TRUE(progress_called);
  8906. }
  8907. TEST(UploadProgressTest, PostStringBodyBasic) {
  8908. TestStringBodyUploadProgress(
  8909. [](Server &svr) {
  8910. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8911. res.set_content("received", "text/plain");
  8912. });
  8913. },
  8914. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8915. return cli.Post("/test", body, "text/plain", progress_callback);
  8916. },
  8917. "test data for upload progress");
  8918. }
  8919. TEST(UploadProgressTest, PutStringBodyBasic) {
  8920. TestStringBodyUploadProgress(
  8921. [](Server &svr) {
  8922. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8923. res.set_content("put received", "text/plain");
  8924. });
  8925. },
  8926. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8927. return cli.Put("/test", body, "text/plain", progress_callback);
  8928. },
  8929. "put test data for upload progress");
  8930. }
  8931. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8932. TestStringBodyUploadProgress(
  8933. [](Server &svr) {
  8934. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8935. res.set_content("patch received", "text/plain");
  8936. });
  8937. },
  8938. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8939. return cli.Patch("/test", body, "text/plain", progress_callback);
  8940. },
  8941. "patch test data for upload progress");
  8942. }
  8943. // Helper function for content provider upload progress tests
  8944. template <typename SetupHandler, typename ClientCall>
  8945. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8946. ClientCall &&client_call) {
  8947. Server svr;
  8948. setup_handler(svr);
  8949. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8950. auto se = detail::scope_exit([&] {
  8951. svr.stop();
  8952. t.join();
  8953. });
  8954. svr.wait_until_ready();
  8955. Client cli(HOST, PORT);
  8956. vector<uint64_t> progress_values;
  8957. auto res =
  8958. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8959. progress_values.push_back(current);
  8960. return true;
  8961. });
  8962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8963. EXPECT_EQ(200, res->status);
  8964. EXPECT_FALSE(progress_values.empty());
  8965. }
  8966. TEST(UploadProgressTest, PostContentProviderProgress) {
  8967. TestContentProviderUploadProgress(
  8968. [](Server &svr) {
  8969. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8970. res.set_content("provider received", "text/plain");
  8971. });
  8972. },
  8973. [](Client &cli, UploadProgress progress_callback) {
  8974. return cli.Post(
  8975. "/test", 10,
  8976. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8977. sink.os << "test data";
  8978. return true;
  8979. },
  8980. "text/plain", progress_callback);
  8981. });
  8982. }
  8983. // Helper function for multipart upload progress tests
  8984. template <typename SetupHandler, typename ClientCall>
  8985. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8986. ClientCall &&client_call,
  8987. const string &endpoint) {
  8988. Server svr;
  8989. setup_handler(svr);
  8990. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8991. auto se = detail::scope_exit([&] {
  8992. svr.stop();
  8993. t.join();
  8994. });
  8995. svr.wait_until_ready();
  8996. Client cli(HOST, PORT);
  8997. vector<uint64_t> progress_values;
  8998. UploadFormDataItems items = {
  8999. {"field1", "value1", "", ""},
  9000. {"field2", "longer value for progress tracking test", "", ""},
  9001. {"file1", "file content data for upload progress", "test.txt",
  9002. "text/plain"}};
  9003. auto res = client_call(cli, endpoint, items,
  9004. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9005. progress_values.push_back(current);
  9006. return true;
  9007. });
  9008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9009. EXPECT_EQ(200, res->status);
  9010. EXPECT_FALSE(progress_values.empty());
  9011. }
  9012. TEST(UploadProgressTest, PostMultipartProgress) {
  9013. TestMultipartUploadProgress(
  9014. [](Server &svr) {
  9015. svr.Post("/multipart", [](const Request &req, Response &res) {
  9016. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9017. res.set_content("multipart received", "text/plain");
  9018. });
  9019. },
  9020. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9021. UploadProgress progress_callback) {
  9022. return cli.Post(endpoint, items, progress_callback);
  9023. },
  9024. "/multipart");
  9025. }
  9026. // Helper function for basic download progress tests
  9027. template <typename SetupHandler, typename ClientCall>
  9028. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9029. ClientCall &&client_call, const string &endpoint,
  9030. size_t expected_content_size) {
  9031. Server svr;
  9032. setup_handler(svr);
  9033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9034. auto se = detail::scope_exit([&] {
  9035. svr.stop();
  9036. t.join();
  9037. });
  9038. svr.wait_until_ready();
  9039. Client cli(HOST, PORT);
  9040. vector<uint64_t> progress_values;
  9041. auto res = client_call(cli, endpoint,
  9042. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9043. progress_values.push_back(current);
  9044. return true;
  9045. });
  9046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9047. EXPECT_EQ(200, res->status);
  9048. EXPECT_FALSE(progress_values.empty());
  9049. EXPECT_EQ(expected_content_size, res->body.size());
  9050. }
  9051. TEST(DownloadProgressTest, GetBasic) {
  9052. TestBasicDownloadProgress(
  9053. [](Server &svr) {
  9054. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9055. string content(1000, 'D');
  9056. res.set_content(content, "text/plain");
  9057. });
  9058. },
  9059. [](Client &cli, const string &endpoint,
  9060. DownloadProgress progress_callback) {
  9061. return cli.Get(endpoint, progress_callback);
  9062. },
  9063. "/download", 1000u);
  9064. }
  9065. // Helper function for content receiver download progress tests
  9066. template <typename SetupHandler, typename ClientCall>
  9067. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9068. ClientCall &&client_call,
  9069. const string &endpoint,
  9070. size_t expected_content_size) {
  9071. Server svr;
  9072. setup_handler(svr);
  9073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9074. auto se = detail::scope_exit([&] {
  9075. svr.stop();
  9076. t.join();
  9077. });
  9078. svr.wait_until_ready();
  9079. Client cli(HOST, PORT);
  9080. vector<uint64_t> progress_values;
  9081. string received_body;
  9082. auto res = client_call(
  9083. cli, endpoint,
  9084. [&](const char *data, size_t data_length) -> bool {
  9085. received_body.append(data, data_length);
  9086. return true;
  9087. },
  9088. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9089. progress_values.push_back(current);
  9090. return true;
  9091. });
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(200, res->status);
  9094. EXPECT_FALSE(progress_values.empty());
  9095. EXPECT_EQ(expected_content_size, received_body.size());
  9096. EXPECT_TRUE(res->body.empty());
  9097. }
  9098. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9099. TestContentReceiverDownloadProgress(
  9100. [](Server &svr) {
  9101. svr.Get("/download-receiver",
  9102. [](const Request & /*req*/, Response &res) {
  9103. string content(2000, 'R');
  9104. res.set_content(content, "text/plain");
  9105. });
  9106. },
  9107. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9108. DownloadProgress progress_callback) {
  9109. return cli.Get(endpoint, content_receiver, progress_callback);
  9110. },
  9111. "/download-receiver", 2000u);
  9112. }
  9113. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9114. // A provider reaching a pass with nothing to hand over - an empty buffer
  9115. // popped off a queue, say - must not be taken to mean the body is finished.
  9116. // It used to end the loop with the terminating chunk unwritten while the
  9117. // server still considered the response complete, so the peer waited for an
  9118. // end that never arrived.
  9119. Server svr;
  9120. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9121. auto step = std::make_shared<int>(0);
  9122. res.set_chunked_content_provider("text/plain",
  9123. [step](size_t /*offset*/, DataSink &sink) {
  9124. switch ((*step)++) {
  9125. case 0: sink.write("", 0); break;
  9126. case 1: sink.write("hello", 5); break;
  9127. default: sink.done(); break;
  9128. }
  9129. return true;
  9130. });
  9131. });
  9132. auto port = svr.bind_to_any_port(HOST);
  9133. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9134. auto listen_se = detail::scope_exit([&] {
  9135. svr.stop();
  9136. listen_thread.join();
  9137. ASSERT_FALSE(svr.is_running());
  9138. });
  9139. svr.wait_until_ready();
  9140. Client cli(HOST, port);
  9141. // Without the fix the body is never terminated, so bound the wait rather
  9142. // than letting the test hang on the default read timeout.
  9143. cli.set_read_timeout(5, 0);
  9144. auto res = cli.Get("/stream");
  9145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9146. EXPECT_EQ(StatusCode::OK_200, res->status);
  9147. EXPECT_EQ("hello", res->body);
  9148. }
  9149. TEST(StreamingTest, NoContentLengthStreaming) {
  9150. Server svr;
  9151. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9152. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9153. if (offset < 6) {
  9154. sink.os << (offset < 3 ? "a" : "b");
  9155. } else {
  9156. sink.done();
  9157. }
  9158. return true;
  9159. });
  9160. });
  9161. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9162. auto listen_se = detail::scope_exit([&] {
  9163. svr.stop();
  9164. listen_thread.join();
  9165. ASSERT_FALSE(svr.is_running());
  9166. });
  9167. svr.wait_until_ready();
  9168. Client client(HOST, PORT);
  9169. auto get_thread = std::thread([&client]() {
  9170. std::string s;
  9171. auto res =
  9172. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9173. s += std::string(data, len);
  9174. return true;
  9175. });
  9176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9177. EXPECT_EQ(StatusCode::OK_200, res->status);
  9178. EXPECT_EQ("aaabbb", s);
  9179. });
  9180. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9181. // Give GET time to get a few messages.
  9182. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9183. }
  9184. TEST(MountTest, Unmount) {
  9185. Server svr;
  9186. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9187. auto se = detail::scope_exit([&] {
  9188. svr.stop();
  9189. listen_thread.join();
  9190. ASSERT_FALSE(svr.is_running());
  9191. });
  9192. svr.wait_until_ready();
  9193. Client cli("localhost", PORT);
  9194. svr.set_mount_point("/mount2", "./www2");
  9195. auto res = cli.Get("/");
  9196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9198. res = cli.Get("/mount2/dir/test.html");
  9199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9200. EXPECT_EQ(StatusCode::OK_200, res->status);
  9201. svr.set_mount_point("/", "./www");
  9202. res = cli.Get("/dir/");
  9203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9204. EXPECT_EQ(StatusCode::OK_200, res->status);
  9205. svr.remove_mount_point("/");
  9206. res = cli.Get("/dir/");
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9209. svr.remove_mount_point("/mount2");
  9210. res = cli.Get("/mount2/dir/test.html");
  9211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9213. }
  9214. TEST(MountTest, PathSegmentBoundary) {
  9215. Server svr;
  9216. svr.set_mount_point("/mount2", "./www2");
  9217. svr.set_mount_point("/", "./www");
  9218. auto port = svr.bind_to_any_port(HOST);
  9219. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9220. auto se = detail::scope_exit([&] {
  9221. svr.stop();
  9222. listen_thread.join();
  9223. ASSERT_FALSE(svr.is_running());
  9224. });
  9225. svr.wait_until_ready();
  9226. Client cli(HOST, port);
  9227. auto res = cli.Get("/mount2/dir/test.html");
  9228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9229. EXPECT_EQ(StatusCode::OK_200, res->status);
  9230. // "/mount2" must not match part-way through a path segment.
  9231. res = cli.Get("/mount2dir/test.html");
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9234. // A mount point ending in '/' keeps matching every path below it.
  9235. res = cli.Get("/dir/test.html");
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. }
  9239. TEST(MountTest, Redicect) {
  9240. Server svr;
  9241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9242. auto se = detail::scope_exit([&] {
  9243. svr.stop();
  9244. listen_thread.join();
  9245. ASSERT_FALSE(svr.is_running());
  9246. });
  9247. svr.set_mount_point("/", "./www");
  9248. svr.wait_until_ready();
  9249. Client cli("localhost", PORT);
  9250. auto res = cli.Get("/dir/");
  9251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. res = cli.Get("/dir");
  9254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9255. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9256. res = cli.Get("/file");
  9257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9258. EXPECT_EQ(StatusCode::OK_200, res->status);
  9259. res = cli.Get("/file/");
  9260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9262. cli.set_follow_location(true);
  9263. res = cli.Get("/dir");
  9264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9265. EXPECT_EQ(StatusCode::OK_200, res->status);
  9266. }
  9267. TEST(MountTest, MultibytesPathName) {
  9268. Server svr;
  9269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9270. auto se = detail::scope_exit([&] {
  9271. svr.stop();
  9272. listen_thread.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. });
  9275. svr.set_mount_point("/", "./www");
  9276. svr.wait_until_ready();
  9277. Client cli("localhost", PORT);
  9278. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9280. EXPECT_EQ(StatusCode::OK_200, res->status);
  9281. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9282. }
  9283. #ifdef _WIN32
  9284. // Issue #2435: mmap::open() must succeed even when another handle holds
  9285. // the file open for writing (e.g. an active log file).
  9286. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9287. const char *path = "mmap_concurrent_writer_test.txt";
  9288. const char *content = "hello";
  9289. {
  9290. std::ofstream f(path, std::ios::binary);
  9291. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9292. }
  9293. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9294. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9295. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9296. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9297. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9298. detail::mmap m(path);
  9299. ASSERT_TRUE(m.is_open());
  9300. EXPECT_EQ(strlen(content), m.size());
  9301. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9302. }
  9303. #endif
  9304. #ifndef _WIN32
  9305. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9306. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9307. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9308. TEST(MmapTest, FailedMappingIsNotOpen) {
  9309. const char *path = "./mmap_failed_mapping_test_dir";
  9310. ASSERT_EQ(0, ::mkdir(path, 0755));
  9311. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9312. detail::mmap m(path);
  9313. EXPECT_FALSE(m.is_open());
  9314. EXPECT_EQ(0U, m.size());
  9315. EXPECT_NE(static_cast<const void *>(m.data()),
  9316. static_cast<const void *>(MAP_FAILED));
  9317. }
  9318. #endif
  9319. TEST(KeepAliveTest, ReadTimeout) {
  9320. Server svr;
  9321. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9322. std::this_thread::sleep_for(std::chrono::seconds(2));
  9323. res.set_content("a", "text/plain");
  9324. });
  9325. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9326. res.set_content("b", "text/plain");
  9327. });
  9328. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9329. auto se = detail::scope_exit([&] {
  9330. svr.stop();
  9331. listen_thread.join();
  9332. ASSERT_FALSE(svr.is_running());
  9333. });
  9334. svr.wait_until_ready();
  9335. Client cli("localhost", PORT);
  9336. cli.set_keep_alive(true);
  9337. cli.set_read_timeout(std::chrono::seconds(1));
  9338. auto resa = cli.Get("/a");
  9339. ASSERT_FALSE(resa);
  9340. EXPECT_EQ(Error::Read, resa.error());
  9341. auto resb = cli.Get("/b");
  9342. ASSERT_TRUE(resb);
  9343. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9344. EXPECT_EQ("b", resb->body);
  9345. }
  9346. TEST(KeepAliveTest, MaxCount) {
  9347. size_t keep_alive_max_count = 3;
  9348. Server svr;
  9349. svr.set_keep_alive_max_count(keep_alive_max_count);
  9350. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9351. res.set_content("Hello World!", "text/plain");
  9352. });
  9353. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9354. auto se = detail::scope_exit([&] {
  9355. svr.stop();
  9356. listen_thread.join();
  9357. ASSERT_FALSE(svr.is_running());
  9358. });
  9359. svr.wait_until_ready();
  9360. Client cli(HOST, PORT);
  9361. cli.set_keep_alive(true);
  9362. for (size_t i = 0; i < 5; i++) {
  9363. auto result = cli.Get("/hi");
  9364. ASSERT_TRUE(result);
  9365. EXPECT_EQ(StatusCode::OK_200, result->status);
  9366. if (i == keep_alive_max_count - 1) {
  9367. EXPECT_EQ("close", result->get_header_value("Connection"));
  9368. } else {
  9369. EXPECT_FALSE(result->has_header("Connection"));
  9370. }
  9371. }
  9372. }
  9373. TEST(KeepAliveTest, Issue1041) {
  9374. Server svr;
  9375. svr.set_keep_alive_timeout(3);
  9376. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9377. res.set_content("Hello World!", "text/plain");
  9378. });
  9379. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9380. auto se = detail::scope_exit([&] {
  9381. svr.stop();
  9382. listen_thread.join();
  9383. ASSERT_FALSE(svr.is_running());
  9384. });
  9385. svr.wait_until_ready();
  9386. Client cli(HOST, PORT);
  9387. cli.set_keep_alive(true);
  9388. auto result = cli.Get("/hi");
  9389. ASSERT_TRUE(result);
  9390. EXPECT_EQ(StatusCode::OK_200, result->status);
  9391. std::this_thread::sleep_for(std::chrono::seconds(5));
  9392. result = cli.Get("/hi");
  9393. ASSERT_TRUE(result);
  9394. EXPECT_EQ(StatusCode::OK_200, result->status);
  9395. }
  9396. TEST(KeepAliveTest, Issue1959) {
  9397. Server svr;
  9398. svr.set_keep_alive_timeout(5);
  9399. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9400. res.set_content("a", "text/plain");
  9401. });
  9402. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9403. auto se = detail::scope_exit([&] {
  9404. if (!svr.is_running()) return;
  9405. svr.stop();
  9406. listen_thread.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. Client cli("localhost", PORT);
  9411. cli.set_keep_alive(true);
  9412. using namespace std::chrono;
  9413. auto start = steady_clock::now();
  9414. cli.Get("/a");
  9415. svr.stop();
  9416. listen_thread.join();
  9417. auto end = steady_clock::now();
  9418. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9419. EXPECT_LT(elapsed, 5000);
  9420. }
  9421. #ifdef CPPHTTPLIB_SSL_ENABLED
  9422. TEST(KeepAliveTest, SSLClientReconnection) {
  9423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9424. ASSERT_TRUE(svr.is_valid());
  9425. svr.set_keep_alive_timeout(1);
  9426. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9427. res.set_content("Hello World!", "text/plain");
  9428. });
  9429. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9430. auto se = detail::scope_exit([&] {
  9431. svr.stop();
  9432. listen_thread.join();
  9433. ASSERT_FALSE(svr.is_running());
  9434. });
  9435. svr.wait_until_ready();
  9436. SSLClient cli(HOST, PORT);
  9437. cli.enable_server_certificate_verification(false);
  9438. cli.set_keep_alive(true);
  9439. auto result = cli.Get("/hi");
  9440. ASSERT_TRUE(result);
  9441. EXPECT_EQ(StatusCode::OK_200, result->status);
  9442. result = cli.Get("/hi");
  9443. ASSERT_TRUE(result);
  9444. EXPECT_EQ(StatusCode::OK_200, result->status);
  9445. std::this_thread::sleep_for(std::chrono::seconds(2));
  9446. // Recoonect
  9447. result = cli.Get("/hi");
  9448. ASSERT_TRUE(result);
  9449. EXPECT_EQ(StatusCode::OK_200, result->status);
  9450. result = cli.Get("/hi");
  9451. ASSERT_TRUE(result);
  9452. EXPECT_EQ(StatusCode::OK_200, result->status);
  9453. }
  9454. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9456. ASSERT_TRUE(svr.is_valid());
  9457. svr.set_keep_alive_timeout(1);
  9458. std::string content = "reconnect";
  9459. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9460. res.set_content("Hello World!", "text/plain");
  9461. });
  9462. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9463. auto se = detail::scope_exit([&] {
  9464. svr.stop();
  9465. listen_thread.join();
  9466. ASSERT_FALSE(svr.is_running());
  9467. });
  9468. svr.wait_until_ready();
  9469. SSLClient cli(HOST, PORT);
  9470. cli.enable_server_certificate_verification(false);
  9471. cli.set_keep_alive(true);
  9472. auto result = cli.Post(
  9473. "/hi", content.size(),
  9474. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9475. sink.write(content.c_str(), content.size());
  9476. return true;
  9477. },
  9478. "text/plain");
  9479. ASSERT_TRUE(result);
  9480. EXPECT_EQ(200, result->status);
  9481. std::this_thread::sleep_for(std::chrono::seconds(2));
  9482. // Recoonect
  9483. result = cli.Post(
  9484. "/hi", content.size(),
  9485. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9486. sink.write(content.c_str(), content.size());
  9487. return true;
  9488. },
  9489. "text/plain");
  9490. ASSERT_TRUE(result);
  9491. EXPECT_EQ(200, result->status);
  9492. result = cli.Post(
  9493. "/hi", content.size(),
  9494. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9495. sink.write(content.c_str(), content.size());
  9496. return true;
  9497. },
  9498. "text/plain");
  9499. ASSERT_TRUE(result);
  9500. EXPECT_EQ(200, result->status);
  9501. }
  9502. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9503. using namespace httplib::tls;
  9504. {
  9505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9506. ASSERT_TRUE(svr.is_valid());
  9507. svr.Get("/sni", [&](const Request &req, Response &res) {
  9508. std::string expected = req.sni();
  9509. EXPECT_EQ(expected, req.get_param_value("expected"));
  9510. res.set_content("ok", "text/plain");
  9511. });
  9512. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9513. auto se = detail::scope_exit([&] {
  9514. svr.stop();
  9515. listen_thread.join();
  9516. ASSERT_FALSE(svr.is_running());
  9517. });
  9518. svr.wait_until_ready();
  9519. {
  9520. SSLClient cli("localhost", PORT);
  9521. cli.enable_server_certificate_verification(false);
  9522. auto res = cli.Get("/sni?expected=localhost");
  9523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9524. }
  9525. {
  9526. SSLClient cli("::1", PORT);
  9527. cli.enable_server_certificate_verification(false);
  9528. auto res = cli.Get("/sni?expected=");
  9529. // NOTE: This may fail if the server is listening on IPv4 only
  9530. // (e.g., when localhost resolves to 127.0.0.1 only)
  9531. if (res) {
  9532. EXPECT_EQ(StatusCode::OK_200, res->status);
  9533. } else {
  9534. EXPECT_EQ(Error::Connection, res.error());
  9535. }
  9536. }
  9537. }
  9538. }
  9539. #endif
  9540. TEST(ClientProblemDetectionTest, ContentProvider) {
  9541. Server svr;
  9542. size_t content_length = 1024 * 1024;
  9543. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9544. res.set_content_provider(
  9545. content_length, "text/plain",
  9546. [&](size_t offset, size_t length, DataSink &sink) {
  9547. auto out_len = std::min(length, static_cast<size_t>(1024));
  9548. std::string out(out_len, '@');
  9549. sink.write(out.data(), out_len);
  9550. return offset < 4096;
  9551. },
  9552. [](bool success) { ASSERT_FALSE(success); });
  9553. });
  9554. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9555. res.set_content_provider(
  9556. 0, "text/plain",
  9557. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9558. EXPECT_TRUE(false);
  9559. return true;
  9560. },
  9561. [](bool success) { ASSERT_FALSE(success); });
  9562. });
  9563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. listen_thread.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. Client cli("localhost", PORT);
  9571. {
  9572. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9573. size_t /*data_length*/) { return false; });
  9574. ASSERT_FALSE(res);
  9575. }
  9576. {
  9577. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9578. size_t /*data_length*/) { return false; });
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. }
  9581. }
  9582. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9583. // A provider that reports success without writing anything and without
  9584. // calling done() used to be handed the same offset and length again on every
  9585. // pass, so it spun for as long as the peer stayed connected.
  9586. Server svr;
  9587. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9588. res.set_content("ok", "text/plain");
  9589. });
  9590. auto port = svr.bind_to_any_port(HOST);
  9591. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. listen_thread.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. std::atomic<int> call_count{0};
  9599. Client cli(HOST, port);
  9600. auto res = cli.Post(
  9601. "/", 1024,
  9602. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9603. // Give up after enough passes to show the spin, so that losing the
  9604. // check below fails this test instead of hanging it.
  9605. return ++call_count < 100;
  9606. },
  9607. "text/plain");
  9608. ASSERT_FALSE(res);
  9609. EXPECT_EQ(Error::Write, res.error());
  9610. EXPECT_EQ(1, call_count.load());
  9611. }
  9612. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9613. // A writer only has to assign `write`. The other three used to be left as
  9614. // empty std::functions, so a provider calling one threw
  9615. // std::bad_function_call out of the thread running it and took the whole
  9616. // process down.
  9617. DataSink sink;
  9618. std::string written;
  9619. sink.write = [&](const char *data, size_t data_len) {
  9620. written.append(data, data_len);
  9621. return true;
  9622. };
  9623. EXPECT_TRUE(sink.is_writable());
  9624. sink.done();
  9625. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9626. EXPECT_TRUE(written.empty());
  9627. }
  9628. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9629. // A sink that cannot carry trailers still has to finish.
  9630. DataSink sink;
  9631. auto done_count = 0;
  9632. sink.done = [&]() { done_count++; };
  9633. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9634. EXPECT_EQ(1, done_count);
  9635. }
  9636. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9637. Server svr;
  9638. const std::string body(4096, 'x');
  9639. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9640. res.set_content_provider(body.size(), "text/plain",
  9641. [&](size_t offset, size_t length, DataSink &sink) {
  9642. sink.write(body.data() + offset, length);
  9643. sink.done();
  9644. return true;
  9645. });
  9646. });
  9647. auto port = svr.bind_to_any_port(HOST);
  9648. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. listen_thread.join();
  9652. ASSERT_FALSE(svr.is_running());
  9653. });
  9654. svr.wait_until_ready();
  9655. Client cli(HOST, port);
  9656. auto res = cli.Get("/");
  9657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9658. EXPECT_EQ(StatusCode::OK_200, res->status);
  9659. EXPECT_EQ(body, res->body);
  9660. }
  9661. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9662. Server svr;
  9663. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9664. res.set_content_provider(
  9665. 1024, "text/plain",
  9666. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9667. sink.write("hello", 5);
  9668. sink.done(); // short of the 1024 bytes the response promised
  9669. return true;
  9670. });
  9671. });
  9672. auto port = svr.bind_to_any_port(HOST);
  9673. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9674. auto se = detail::scope_exit([&] {
  9675. svr.stop();
  9676. listen_thread.join();
  9677. ASSERT_FALSE(svr.is_running());
  9678. });
  9679. svr.wait_until_ready();
  9680. Client cli(HOST, port);
  9681. cli.set_read_timeout(5, 0);
  9682. // The response is short of its Content-Length, so the client cannot read a
  9683. // complete body. What matters is that this returns at all: a no-op done()
  9684. // would leave the writer looping over a provider that never makes progress.
  9685. auto res = cli.Get("/");
  9686. EXPECT_FALSE(res);
  9687. }
  9688. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9689. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9690. // The compressed path builds the whole body before connecting, so this
  9691. // fails client-side and never reaches a server.
  9692. Client cli(HOST, PORT);
  9693. cli.set_compress(true);
  9694. auto res = cli.Post(
  9695. "/", 1024,
  9696. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9697. sink.write("hello", 5);
  9698. sink.done(); // short of the 1024 bytes the request announced
  9699. return true;
  9700. },
  9701. "text/plain");
  9702. ASSERT_FALSE(res);
  9703. EXPECT_EQ(Error::Write, res.error());
  9704. }
  9705. #endif
  9706. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9707. Server svr;
  9708. svr.set_error_handler([](Request const &, Response &res) -> void {
  9709. res.set_chunked_content_provider(
  9710. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9711. sink.os << "hello";
  9712. sink.os << "world";
  9713. sink.done();
  9714. return true;
  9715. });
  9716. });
  9717. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9718. auto se = detail::scope_exit([&] {
  9719. svr.stop();
  9720. listen_thread.join();
  9721. ASSERT_FALSE(svr.is_running());
  9722. });
  9723. svr.wait_until_ready();
  9724. Client cli("localhost", PORT);
  9725. auto res = cli.Get("/");
  9726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9728. EXPECT_EQ("helloworld", res->body);
  9729. }
  9730. TEST(LongPollingTest, ClientCloseDetection) {
  9731. Server svr;
  9732. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9733. res.set_chunked_content_provider(
  9734. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9735. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9736. sink.os << "hello";
  9737. auto count = 10;
  9738. while (count > 0 && sink.is_writable()) {
  9739. this_thread::sleep_for(chrono::milliseconds(10));
  9740. count--;
  9741. }
  9742. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9743. return true;
  9744. });
  9745. });
  9746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9747. auto se = detail::scope_exit([&] {
  9748. svr.stop();
  9749. listen_thread.join();
  9750. ASSERT_FALSE(svr.is_running());
  9751. });
  9752. svr.wait_until_ready();
  9753. Client cli("localhost", PORT);
  9754. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9755. EXPECT_EQ("hello", string(data, data_length));
  9756. return false; // close the socket immediately.
  9757. });
  9758. ASSERT_FALSE(res);
  9759. }
  9760. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9761. Server svr;
  9762. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9763. res.set_chunked_content_provider(
  9764. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9765. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9766. sink.os << "hello";
  9767. EXPECT_TRUE(sink.os.good());
  9768. // Wait for the client to close the connection
  9769. auto count = 10;
  9770. while (count > 0 && sink.is_writable()) {
  9771. this_thread::sleep_for(chrono::milliseconds(10));
  9772. count--;
  9773. }
  9774. // After client disconnect, write repeatedly until the socket
  9775. // write actually fails (small writes may be absorbed by the
  9776. // kernel buffer)
  9777. std::string chunk(1024, 'x');
  9778. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9779. sink.os << chunk;
  9780. }
  9781. EXPECT_TRUE(sink.os.fail());
  9782. return true;
  9783. });
  9784. });
  9785. auto port = svr.bind_to_any_port("localhost");
  9786. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9787. auto se = detail::scope_exit([&] {
  9788. svr.stop();
  9789. listen_thread.join();
  9790. ASSERT_FALSE(svr.is_running());
  9791. });
  9792. svr.wait_until_ready();
  9793. Client cli("localhost", port);
  9794. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9795. EXPECT_EQ("hello", string(data, data_length));
  9796. return false; // close the socket immediately.
  9797. });
  9798. ASSERT_FALSE(res);
  9799. }
  9800. TEST(GetWithParametersTest, GetWithParameters) {
  9801. Server svr;
  9802. svr.Get("/", [&](const Request &req, Response &) {
  9803. EXPECT_EQ("world", req.get_param_value("hello"));
  9804. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9805. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9806. });
  9807. svr.Get("/params", [&](const Request &req, Response &) {
  9808. EXPECT_EQ("world", req.get_param_value("hello"));
  9809. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9810. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9811. });
  9812. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9813. EXPECT_EQ("resource-id", req.matches[1]);
  9814. EXPECT_EQ("foo", req.get_param_value("param1"));
  9815. EXPECT_EQ("bar", req.get_param_value("param2"));
  9816. });
  9817. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9818. EXPECT_EQ("user-id", req.path_params.at("id"));
  9819. EXPECT_EQ("foo", req.get_param_value("param1"));
  9820. EXPECT_EQ("bar", req.get_param_value("param2"));
  9821. });
  9822. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9823. auto se = detail::scope_exit([&] {
  9824. svr.stop();
  9825. listen_thread.join();
  9826. ASSERT_FALSE(svr.is_running());
  9827. });
  9828. svr.wait_until_ready();
  9829. {
  9830. Client cli(HOST, PORT);
  9831. Params params;
  9832. params.emplace("hello", "world");
  9833. params.emplace("hello2", "world2");
  9834. params.emplace("hello3", "world3");
  9835. auto res = cli.Get("/", params, Headers{});
  9836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9837. EXPECT_EQ(StatusCode::OK_200, res->status);
  9838. }
  9839. {
  9840. Client cli(HOST, PORT);
  9841. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9843. EXPECT_EQ(StatusCode::OK_200, res->status);
  9844. }
  9845. {
  9846. Client cli(HOST, PORT);
  9847. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9849. EXPECT_EQ(StatusCode::OK_200, res->status);
  9850. }
  9851. {
  9852. Client cli(HOST, PORT);
  9853. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9855. EXPECT_EQ(StatusCode::OK_200, res->status);
  9856. }
  9857. }
  9858. TEST(GetWithParametersTest, GetWithParameters2) {
  9859. Server svr;
  9860. svr.Get("/", [&](const Request &req, Response &res) {
  9861. auto text = req.get_param_value("hello");
  9862. res.set_content(text, "text/plain");
  9863. });
  9864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9865. auto se = detail::scope_exit([&] {
  9866. svr.stop();
  9867. listen_thread.join();
  9868. ASSERT_FALSE(svr.is_running());
  9869. });
  9870. svr.wait_until_ready();
  9871. Client cli("localhost", PORT);
  9872. Params params;
  9873. params.emplace("hello", "world");
  9874. std::string body;
  9875. auto res = cli.Get("/", params, Headers{},
  9876. [&](const char *data, size_t data_length) {
  9877. body.append(data, data_length);
  9878. return true;
  9879. });
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. EXPECT_EQ("world", body);
  9883. }
  9884. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9885. Server svr;
  9886. svr.Get("/search", [&](const Request &req, Response &res) {
  9887. auto q = req.get_param_value("q");
  9888. res.set_content(q, "text/plain");
  9889. });
  9890. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9891. auto se = detail::scope_exit([&] {
  9892. svr.stop();
  9893. listen_thread.join();
  9894. ASSERT_FALSE(svr.is_running());
  9895. });
  9896. svr.wait_until_ready();
  9897. Client cli("localhost", PORT);
  9898. // Verify that Get(path, params) works without requiring Headers argument
  9899. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9901. EXPECT_EQ(StatusCode::OK_200, res->status);
  9902. EXPECT_EQ("cpp-httplib", res->body);
  9903. }
  9904. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9905. auto host = "httpbingo.org";
  9906. auto path = std::string{"/range/32"};
  9907. #ifdef CPPHTTPLIB_SSL_ENABLED
  9908. SSLClient cli(host);
  9909. #else
  9910. Client cli(host);
  9911. #endif
  9912. cli.set_default_headers({make_range_header({{1, 10}})});
  9913. cli.set_connection_timeout(5);
  9914. {
  9915. auto res = cli.Get(path);
  9916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9917. EXPECT_EQ("bcdefghijk", res->body);
  9918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9919. }
  9920. {
  9921. auto res = cli.Get(path);
  9922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9923. EXPECT_EQ("bcdefghijk", res->body);
  9924. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9925. }
  9926. }
  9927. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9928. Server svr;
  9929. svr.set_default_headers({{"Hello", "World"}});
  9930. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9931. res.set_content("ok", "text/plain");
  9932. });
  9933. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9934. auto se = detail::scope_exit([&] {
  9935. svr.stop();
  9936. listen_thread.join();
  9937. ASSERT_FALSE(svr.is_running());
  9938. });
  9939. svr.wait_until_ready();
  9940. Client cli("localhost", PORT);
  9941. auto res = cli.Get("/");
  9942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9943. EXPECT_EQ(StatusCode::OK_200, res->status);
  9944. EXPECT_EQ("ok", res->body);
  9945. EXPECT_EQ("World", res->get_header_value("Hello"));
  9946. }
  9947. #ifdef CPPHTTPLIB_SSL_ENABLED
  9948. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9950. ASSERT_TRUE(svr.is_valid());
  9951. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9952. std::this_thread::sleep_for(std::chrono::seconds(2));
  9953. res.set_content("a", "text/plain");
  9954. });
  9955. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9956. res.set_content("b", "text/plain");
  9957. });
  9958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9959. auto se = detail::scope_exit([&] {
  9960. svr.stop();
  9961. listen_thread.join();
  9962. ASSERT_FALSE(svr.is_running());
  9963. });
  9964. svr.wait_until_ready();
  9965. SSLClient cli("localhost", PORT);
  9966. cli.enable_server_certificate_verification(false);
  9967. cli.set_keep_alive(true);
  9968. cli.set_read_timeout(std::chrono::seconds(1));
  9969. auto resa = cli.Get("/a");
  9970. ASSERT_TRUE(!resa);
  9971. EXPECT_EQ(Error::Read, resa.error());
  9972. auto resb = cli.Get("/b");
  9973. ASSERT_TRUE(resb);
  9974. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9975. EXPECT_EQ("b", resb->body);
  9976. }
  9977. #endif
  9978. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9979. protected:
  9980. ServerTestWithAI_PASSIVE()
  9981. : cli_(HOST, PORT)
  9982. #ifdef CPPHTTPLIB_SSL_ENABLED
  9983. ,
  9984. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9985. #endif
  9986. {
  9987. #ifdef CPPHTTPLIB_SSL_ENABLED
  9988. cli_.enable_server_certificate_verification(false);
  9989. #endif
  9990. }
  9991. virtual void SetUp() {
  9992. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9993. res.set_content("Hello World!", "text/plain");
  9994. });
  9995. t_ = thread(
  9996. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9997. svr_.wait_until_ready();
  9998. }
  9999. virtual void TearDown() {
  10000. svr_.stop();
  10001. t_.join();
  10002. }
  10003. #ifdef CPPHTTPLIB_SSL_ENABLED
  10004. SSLClient cli_;
  10005. SSLServer svr_;
  10006. #else
  10007. Client cli_;
  10008. Server svr_;
  10009. #endif
  10010. thread t_;
  10011. };
  10012. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10013. auto res = cli_.Get("/hi");
  10014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10015. EXPECT_EQ(StatusCode::OK_200, res->status);
  10016. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10017. EXPECT_EQ("Hello World!", res->body);
  10018. }
  10019. class ServerUpDownTest : public ::testing::Test {
  10020. protected:
  10021. ServerUpDownTest() : cli_(HOST, PORT) {}
  10022. virtual void SetUp() {
  10023. t_ = thread([&]() {
  10024. svr_.bind_to_any_port(HOST);
  10025. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10026. ASSERT_TRUE(svr_.listen_after_bind());
  10027. });
  10028. svr_.wait_until_ready();
  10029. }
  10030. virtual void TearDown() {
  10031. svr_.stop();
  10032. t_.join();
  10033. }
  10034. Client cli_;
  10035. Server svr_;
  10036. thread t_;
  10037. };
  10038. TEST_F(ServerUpDownTest, QuickStartStop) {
  10039. // Should not crash, especially when run with
  10040. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10041. }
  10042. class PayloadMaxLengthTest : public ::testing::Test {
  10043. protected:
  10044. PayloadMaxLengthTest()
  10045. : cli_(HOST, PORT)
  10046. #ifdef CPPHTTPLIB_SSL_ENABLED
  10047. ,
  10048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10049. #endif
  10050. {
  10051. #ifdef CPPHTTPLIB_SSL_ENABLED
  10052. cli_.enable_server_certificate_verification(false);
  10053. #endif
  10054. }
  10055. virtual void SetUp() {
  10056. svr_.set_payload_max_length(8);
  10057. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10058. res.set_content("test", "text/plain");
  10059. });
  10060. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10061. svr_.wait_until_ready();
  10062. }
  10063. virtual void TearDown() {
  10064. svr_.stop();
  10065. t_.join();
  10066. }
  10067. #ifdef CPPHTTPLIB_SSL_ENABLED
  10068. SSLClient cli_;
  10069. SSLServer svr_;
  10070. #else
  10071. Client cli_;
  10072. Server svr_;
  10073. #endif
  10074. thread t_;
  10075. };
  10076. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10077. auto res = cli_.Post("/test", "123456789", "text/plain");
  10078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10079. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10080. res = cli_.Post("/test", "12345678", "text/plain");
  10081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10082. EXPECT_EQ(StatusCode::OK_200, res->status);
  10083. }
  10084. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10085. // Test chunked encoding with payload exceeding the 8-byte limit
  10086. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10087. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10089. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10090. }
  10091. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10092. // Test chunked encoding with payload within the 8-byte limit
  10093. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10094. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10096. EXPECT_EQ(StatusCode::OK_200, res->status);
  10097. }
  10098. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10099. // Test using send_request to send chunked data exceeding payload limit
  10100. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10101. "Host: " +
  10102. std::string(HOST) + ":" + std::to_string(PORT) +
  10103. "\r\n"
  10104. "Transfer-Encoding: chunked\r\n"
  10105. "Connection: close\r\n"
  10106. "\r\n"
  10107. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10108. "0123456789\r\n"
  10109. "0\r\n" // End chunk
  10110. "\r\n";
  10111. std::string response;
  10112. bool result = send_request(1, chunked_request, &response);
  10113. if (!result) {
  10114. // If send_request fails, it might be because the server closed the
  10115. // connection due to payload limit enforcement, which is acceptable
  10116. SUCCEED()
  10117. << "Server rejected oversized chunked request (connection closed)";
  10118. } else {
  10119. // If we got a response, check if it's an error response or connection was
  10120. // closed early Short response length indicates connection was closed due to
  10121. // payload limit
  10122. if (response.length() <= 10) {
  10123. SUCCEED() << "Server closed connection for oversized chunked request";
  10124. } else {
  10125. // Check for error status codes
  10126. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10127. response.find("Payload Too Large") != std::string::npos ||
  10128. response.find("400") != std::string::npos);
  10129. }
  10130. }
  10131. }
  10132. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10133. // Test request without Content-Length header exceeding payload limit
  10134. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10135. "Host: " +
  10136. std::string(HOST) + ":" +
  10137. std::to_string(PORT) +
  10138. "\r\n"
  10139. "Connection: close\r\n"
  10140. "\r\n";
  10141. // Add payload exceeding the 8-byte limit
  10142. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10143. request_without_content_length += large_payload;
  10144. std::string response;
  10145. bool result = send_request(1, request_without_content_length, &response);
  10146. if (!result) {
  10147. // If send_request fails, server likely closed connection due to payload
  10148. // limit
  10149. SUCCEED() << "Server rejected oversized request without Content-Length "
  10150. "(connection closed)";
  10151. } else {
  10152. // Check if server responded with error or closed connection early
  10153. if (response.length() <= 10) {
  10154. SUCCEED() << "Server closed connection for oversized request without "
  10155. "Content-Length";
  10156. } else {
  10157. // Check for error status codes
  10158. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10159. response.find("Payload Too Large") != std::string::npos ||
  10160. response.find("400") != std::string::npos);
  10161. }
  10162. }
  10163. }
  10164. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10165. // Test request without Content-Length header within payload limit
  10166. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10167. "Host: " +
  10168. std::string(HOST) + ":" +
  10169. std::to_string(PORT) +
  10170. "\r\n"
  10171. "Connection: close\r\n"
  10172. "\r\n";
  10173. // Add payload within the 8-byte limit
  10174. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10175. request_without_content_length += small_payload;
  10176. std::string response;
  10177. bool result = send_request(1, request_without_content_length, &response);
  10178. // For requests without Content-Length, the server may have different behavior
  10179. // The key is that it should not reject due to payload limit for small
  10180. // payloads
  10181. if (result) {
  10182. // Check for any HTTP response (success or error, but not connection closed)
  10183. if (response.length() > 10) {
  10184. SUCCEED()
  10185. << "Server processed request without Content-Length within limit";
  10186. } else {
  10187. // Short response might indicate connection closed, which is acceptable
  10188. SUCCEED() << "Server closed connection for request without "
  10189. "Content-Length (acceptable behavior)";
  10190. }
  10191. } else {
  10192. // Connection failure might be due to protocol requirements
  10193. SUCCEED() << "Connection issue with request without Content-Length "
  10194. "(environment-specific)";
  10195. }
  10196. }
  10197. class LargePayloadMaxLengthTest : public ::testing::Test {
  10198. protected:
  10199. LargePayloadMaxLengthTest()
  10200. : cli_(HOST, PORT)
  10201. #ifdef CPPHTTPLIB_SSL_ENABLED
  10202. ,
  10203. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10204. #endif
  10205. {
  10206. #ifdef CPPHTTPLIB_SSL_ENABLED
  10207. cli_.enable_server_certificate_verification(false);
  10208. #endif
  10209. }
  10210. virtual void SetUp() {
  10211. // Set 10MB payload limit
  10212. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10213. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10214. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10215. res.set_content("Large payload test", "text/plain");
  10216. });
  10217. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10218. svr_.wait_until_ready();
  10219. }
  10220. virtual void TearDown() {
  10221. svr_.stop();
  10222. t_.join();
  10223. }
  10224. #ifdef CPPHTTPLIB_SSL_ENABLED
  10225. SSLClient cli_;
  10226. SSLServer svr_;
  10227. #else
  10228. Client cli_;
  10229. Server svr_;
  10230. #endif
  10231. thread t_;
  10232. };
  10233. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10234. // Test chunked encoding with payload within 10MB limit
  10235. std::string medium_payload(5 * 1024 * 1024,
  10236. 'A'); // 5MB payload, within 10MB limit
  10237. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10239. EXPECT_EQ(StatusCode::OK_200, res->status);
  10240. }
  10241. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10242. // Test chunked encoding with payload exceeding 10MB limit
  10243. std::string large_payload(12 * 1024 * 1024,
  10244. 'B'); // 12MB payload, exceeds 10MB limit
  10245. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10246. // Server may either return 413 or close the connection
  10247. if (res) {
  10248. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10249. } else {
  10250. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10251. }
  10252. }
  10253. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10254. // Test request without Content-Length header within 10MB limit
  10255. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10256. "Host: " +
  10257. std::string(HOST) + ":" +
  10258. std::to_string(PORT) +
  10259. "\r\n"
  10260. "Connection: close\r\n"
  10261. "\r\n";
  10262. // Add 1MB payload (within 10MB limit)
  10263. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10264. request_without_content_length += medium_payload;
  10265. std::string response;
  10266. bool result = send_request(5, request_without_content_length, &response);
  10267. if (result) {
  10268. // Should get a proper HTTP response for payloads within limit
  10269. if (response.length() > 10) {
  10270. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10271. "10MB limit";
  10272. } else {
  10273. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10274. "Content-Length)";
  10275. }
  10276. } else {
  10277. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10278. }
  10279. }
  10280. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10281. // Test request without Content-Length header exceeding 10MB limit
  10282. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10283. "Host: " +
  10284. std::string(HOST) + ":" +
  10285. std::to_string(PORT) +
  10286. "\r\n"
  10287. "Connection: close\r\n"
  10288. "\r\n";
  10289. // Add 12MB payload (exceeds 10MB limit)
  10290. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10291. request_without_content_length += large_payload;
  10292. std::string response;
  10293. bool result = send_request(10, request_without_content_length, &response);
  10294. if (!result) {
  10295. // Server should close connection due to payload limit
  10296. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10297. "(connection closed)";
  10298. } else {
  10299. // Check for error response
  10300. if (response.length() <= 10) {
  10301. SUCCEED()
  10302. << "Server closed connection for 12MB request exceeding 10MB limit";
  10303. } else {
  10304. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10305. response.find("Payload Too Large") != std::string::npos ||
  10306. response.find("400") != std::string::npos);
  10307. }
  10308. }
  10309. }
  10310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10311. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10312. // path.
  10313. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10314. Server svr;
  10315. const size_t LIMIT = 64 * 1024; // 64KB
  10316. svr.set_payload_max_length(LIMIT);
  10317. size_t total = 0;
  10318. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10319. const ContentReader &content_reader) {
  10320. content_reader([&](const char * /*data*/, size_t len) {
  10321. total += len;
  10322. return true;
  10323. });
  10324. res.status = 200;
  10325. res.set_content("stream_ok", "text/plain");
  10326. });
  10327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10328. auto se = detail::scope_exit([&] {
  10329. svr.stop();
  10330. thread.join();
  10331. ASSERT_FALSE(svr.is_running());
  10332. });
  10333. svr.wait_until_ready();
  10334. // Prepare 256KB raw data and gzip-compress it
  10335. std::string raw(256 * 1024, 'A');
  10336. std::string gz;
  10337. {
  10338. z_stream zs{};
  10339. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10340. Z_DEFAULT_STRATEGY);
  10341. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10342. zs.avail_in = static_cast<uInt>(raw.size());
  10343. char outbuf[4096];
  10344. int ret;
  10345. do {
  10346. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10347. zs.avail_out = sizeof(outbuf);
  10348. ret = deflate(&zs, Z_FINISH);
  10349. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10350. } while (ret != Z_STREAM_END);
  10351. deflateEnd(&zs);
  10352. }
  10353. Client cli(HOST, PORT);
  10354. cli.set_connection_timeout(std::chrono::seconds(5));
  10355. Headers headers = {{"Content-Encoding", "gzip"}};
  10356. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10357. "application/octet-stream");
  10358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10359. // Server must reject oversized decompressed payloads with 413.
  10360. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10361. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10362. EXPECT_LE(total, LIMIT);
  10363. }
  10364. #ifndef CPPHTTPLIB_SSL_ENABLED
  10365. // For a request with neither Content-Length nor Transfer-Encoding, the
  10366. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10367. // compressed wire bytes straight to the ContentReader without ever routing
  10368. // them through the decompressor, so payload_max_length_ only bounded the
  10369. // compressed size on the wire, not the decompressed size.
  10370. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10371. Server svr;
  10372. const size_t LIMIT = 64 * 1024; // 64KB
  10373. svr.set_payload_max_length(LIMIT);
  10374. size_t total = 0;
  10375. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10376. const ContentReader &content_reader) {
  10377. content_reader([&](const char * /*data*/, size_t len) {
  10378. total += len;
  10379. return true;
  10380. });
  10381. res.status = 200;
  10382. res.set_content("stream_ok", "text/plain");
  10383. });
  10384. auto port = svr.bind_to_any_port(HOST);
  10385. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10386. auto se = detail::scope_exit([&] {
  10387. svr.stop();
  10388. thread.join();
  10389. ASSERT_FALSE(svr.is_running());
  10390. });
  10391. svr.wait_until_ready();
  10392. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10393. // StreamingGzipDecompression test above.
  10394. std::string raw(256 * 1024, 'A');
  10395. std::string gz;
  10396. {
  10397. httplib::detail::gzip_compressor compressor;
  10398. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10399. [&](const char *chunk, size_t len) {
  10400. gz.append(chunk, len);
  10401. return true;
  10402. });
  10403. ASSERT_TRUE(result);
  10404. }
  10405. // Send the gzip body over raw TCP with neither Content-Length nor
  10406. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10407. // kicks in.
  10408. std::string req = "POST /stream HTTP/1.1\r\n"
  10409. "Host: " +
  10410. std::string(HOST) + ":" + std::to_string(port) +
  10411. "\r\n"
  10412. "Content-Encoding: gzip\r\n"
  10413. "Connection: close\r\n"
  10414. "\r\n" +
  10415. gz;
  10416. std::string response;
  10417. ASSERT_TRUE(send_request(5, req, &response, port));
  10418. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10419. EXPECT_LE(total, LIMIT);
  10420. }
  10421. #endif
  10422. #endif
  10423. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10424. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10425. // the payload must be passed through untouched instead of being rejected.
  10426. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10427. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10428. Server svr;
  10429. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10430. res.set_content(body, "image/jpeg");
  10431. res.set_header("Content-Encoding", "UTF-8");
  10432. });
  10433. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10434. res.set_content(body, "image/jpeg");
  10435. res.set_header("Content-Encoding", "identity");
  10436. });
  10437. svr.Post("/echo", [](const Request &req, Response &res) {
  10438. res.set_content(req.body, "image/jpeg");
  10439. });
  10440. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. t.join();
  10444. ASSERT_FALSE(svr.is_running());
  10445. });
  10446. svr.wait_until_ready();
  10447. Client cli(HOST, PORT);
  10448. {
  10449. auto res = cli.Get("/image");
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::OK_200, res->status);
  10452. EXPECT_EQ(body, res->body);
  10453. }
  10454. {
  10455. auto res = cli.Get("/identity");
  10456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10457. EXPECT_EQ(StatusCode::OK_200, res->status);
  10458. EXPECT_EQ(body, res->body);
  10459. }
  10460. {
  10461. // The same applies to a request body reaching the server.
  10462. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10463. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10465. EXPECT_EQ(StatusCode::OK_200, res->status);
  10466. EXPECT_EQ(body, res->body);
  10467. }
  10468. }
  10469. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10470. // gzip-encoded response even when the build has no zlib support.
  10471. static const char GZIPPED_HELLO_WORLD[] = {
  10472. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10473. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10474. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10475. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10476. // A content coding is a whole token, not something the field value merely
  10477. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10478. // as "fibre" look like Brotli, and turned a multi-coding value like
  10479. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10480. // it was never meant to see.
  10481. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10482. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10483. Server svr;
  10484. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10485. res.set_content(body, "image/jpeg");
  10486. res.set_header("Content-Encoding", "fibre");
  10487. });
  10488. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10489. res.set_content(body, "image/jpeg");
  10490. res.set_header("Content-Encoding", "gzip, br");
  10491. });
  10492. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10493. res.set_content(body, "image/jpeg");
  10494. res.set_header("Content-Encoding", "x-zstd-ish");
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. thread t = thread([&]() { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. t.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. Client cli(HOST, port);
  10505. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10506. auto res = cli.Get(path);
  10507. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10508. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10509. // Not a coding we recognize, so the payload comes back untouched
  10510. EXPECT_EQ(body, res->body) << path;
  10511. }
  10512. }
  10513. // A content coding cpp-httplib recognizes but was not built with must be
  10514. // reported as such. Handing the still-compressed payload back to the caller
  10515. // would silently corrupt it.
  10516. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10517. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10518. Server svr;
  10519. // "image/jpeg" keeps the server from applying a content coding of its own,
  10520. // so the hand-crafted Content-Encoding below survives.
  10521. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10522. res.set_content(gzipped, "image/jpeg");
  10523. res.set_header("Content-Encoding", "gzip");
  10524. });
  10525. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10526. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10527. res.set_content(gzipped, "image/jpeg");
  10528. res.set_header("Content-Encoding", "GZIP");
  10529. });
  10530. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10531. auto se = detail::scope_exit([&] {
  10532. svr.stop();
  10533. t.join();
  10534. ASSERT_FALSE(svr.is_running());
  10535. });
  10536. svr.wait_until_ready();
  10537. Client cli(HOST, PORT);
  10538. {
  10539. auto res = cli.Get("/gzipped");
  10540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_EQ("Hello World!", res->body);
  10543. #else
  10544. ASSERT_FALSE(res);
  10545. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10546. #endif
  10547. }
  10548. {
  10549. // open_stream() must behave the same way.
  10550. auto handle = cli.open_stream("GET", "/gzipped");
  10551. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10552. ASSERT_TRUE(handle.is_valid());
  10553. std::string received;
  10554. char buf[256];
  10555. ssize_t n;
  10556. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10557. received.append(buf, static_cast<size_t>(n));
  10558. }
  10559. EXPECT_EQ("Hello World!", received);
  10560. #else
  10561. EXPECT_FALSE(handle.is_valid());
  10562. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10563. #endif
  10564. }
  10565. {
  10566. // A differently-cased coding must not be mistaken for an unknown one, or
  10567. // the body would be handed back still compressed.
  10568. auto res = cli.Get("/gzipped-uppercase");
  10569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10571. EXPECT_EQ("Hello World!", res->body);
  10572. #else
  10573. ASSERT_FALSE(res);
  10574. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10575. #endif
  10576. }
  10577. }
  10578. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10579. // the same message as the comma-joined one, so both have to be read the same
  10580. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10581. // single gzip coding, and a body the sender says was encoded twice was handed
  10582. // back after one pass, still compressed but presented as decoded.
  10583. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10584. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10585. Server svr;
  10586. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10587. res.set_content(body, "image/jpeg");
  10588. res.headers.emplace("Content-Encoding", "gzip");
  10589. res.headers.emplace("Content-Encoding", "gzip");
  10590. });
  10591. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10592. res.set_content(body, "image/jpeg");
  10593. res.set_header("Content-Encoding", "gzip, gzip");
  10594. });
  10595. auto port = svr.bind_to_any_port(HOST);
  10596. thread t = thread([&]() { svr.listen_after_bind(); });
  10597. auto se = detail::scope_exit([&] {
  10598. svr.stop();
  10599. t.join();
  10600. ASSERT_FALSE(svr.is_running());
  10601. });
  10602. svr.wait_until_ready();
  10603. Client cli(HOST, port);
  10604. // Two codings is not something cpp-httplib decodes, so both representations
  10605. // take the pass-through path rather than one of them being gunzipped once.
  10606. for (const char *path : {"/split", "/joined"}) {
  10607. auto res = cli.Get(path);
  10608. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10609. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10610. EXPECT_EQ(body, res->body) << path;
  10611. }
  10612. }
  10613. // Regression test for DoS vulnerability: a malicious server sending a response
  10614. // without Content-Length header must not cause unbounded memory consumption on
  10615. // the client side. The client should stop reading after a reasonable limit,
  10616. // similar to the server-side set_payload_max_length protection.
  10617. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10618. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10619. #ifndef _WIN32
  10620. signal(SIGPIPE, SIG_IGN);
  10621. #endif
  10622. auto server_thread = std::thread([] {
  10623. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10624. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10625. default_socket_options(srv);
  10626. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10627. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10628. sockaddr_in addr{};
  10629. addr.sin_family = AF_INET;
  10630. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10631. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10632. int opt = 1;
  10633. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10634. #ifdef _WIN32
  10635. reinterpret_cast<const char *>(&opt),
  10636. #else
  10637. &opt,
  10638. #endif
  10639. sizeof(opt));
  10640. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10641. ::listen(srv, 1);
  10642. sockaddr_in cli_addr{};
  10643. socklen_t cli_len = sizeof(cli_addr);
  10644. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10645. if (cli != INVALID_SOCKET) {
  10646. char buf[4096];
  10647. ::recv(cli, buf, sizeof(buf), 0);
  10648. // Malicious response: no Content-Length, no chunked encoding
  10649. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10650. "Connection: close\r\n"
  10651. "\r\n";
  10652. ::send(cli,
  10653. #ifdef _WIN32
  10654. static_cast<const char *>(response_header.c_str()),
  10655. static_cast<int>(response_header.size()),
  10656. #else
  10657. response_header.c_str(), response_header.size(),
  10658. #endif
  10659. 0);
  10660. // Send 10MB of data
  10661. std::string chunk(64 * 1024, 'A');
  10662. size_t total_sent = 0;
  10663. while (total_sent < MALICIOUS_DATA_SIZE) {
  10664. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10665. auto sent = ::send(cli,
  10666. #ifdef _WIN32
  10667. static_cast<const char *>(chunk.c_str()),
  10668. static_cast<int>(to_send),
  10669. #else
  10670. chunk.c_str(), to_send,
  10671. #endif
  10672. 0);
  10673. if (sent <= 0) break;
  10674. total_sent += static_cast<size_t>(sent);
  10675. }
  10676. detail::close_socket(cli);
  10677. }
  10678. detail::close_socket(srv);
  10679. });
  10680. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10681. size_t total_read = 0;
  10682. {
  10683. Client cli("127.0.0.1", PORT + 2);
  10684. cli.set_read_timeout(5, 0);
  10685. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10686. auto stream = cli.open_stream("GET", "/malicious");
  10687. ASSERT_TRUE(stream.is_valid());
  10688. char buffer[64 * 1024];
  10689. ssize_t n;
  10690. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10691. total_read += static_cast<size_t>(n);
  10692. }
  10693. } // StreamHandle and Client destroyed here, closing the socket
  10694. server_thread.join();
  10695. // With set_payload_max_length, the client must stop reading before consuming
  10696. // all 10MB. The read loop should be cut off at or near the configured limit.
  10697. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10698. << "Client read " << total_read << " bytes, exceeding the configured "
  10699. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10700. }
  10701. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10702. // the entire response body without truncation.
  10703. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10704. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10705. #ifndef _WIN32
  10706. signal(SIGPIPE, SIG_IGN);
  10707. #endif
  10708. auto server_thread = std::thread([] {
  10709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10710. default_socket_options(srv);
  10711. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10712. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10713. sockaddr_in addr{};
  10714. addr.sin_family = AF_INET;
  10715. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10716. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10717. int opt = 1;
  10718. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10719. #ifdef _WIN32
  10720. reinterpret_cast<const char *>(&opt),
  10721. #else
  10722. &opt,
  10723. #endif
  10724. sizeof(opt));
  10725. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10726. ::listen(srv, 1);
  10727. sockaddr_in cli_addr{};
  10728. socklen_t cli_len = sizeof(cli_addr);
  10729. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10730. if (cli != INVALID_SOCKET) {
  10731. char buf[4096];
  10732. ::recv(cli, buf, sizeof(buf), 0);
  10733. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10734. "Connection: close\r\n"
  10735. "\r\n";
  10736. ::send(cli,
  10737. #ifdef _WIN32
  10738. static_cast<const char *>(response_header.c_str()),
  10739. static_cast<int>(response_header.size()),
  10740. #else
  10741. response_header.c_str(), response_header.size(),
  10742. #endif
  10743. 0);
  10744. std::string chunk(64 * 1024, 'A');
  10745. size_t total_sent = 0;
  10746. while (total_sent < DATA_SIZE) {
  10747. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10748. auto sent = ::send(cli,
  10749. #ifdef _WIN32
  10750. static_cast<const char *>(chunk.c_str()),
  10751. static_cast<int>(to_send),
  10752. #else
  10753. chunk.c_str(), to_send,
  10754. #endif
  10755. 0);
  10756. if (sent <= 0) break;
  10757. total_sent += static_cast<size_t>(sent);
  10758. }
  10759. #ifdef _WIN32
  10760. ::shutdown(cli, SD_SEND);
  10761. #else
  10762. ::shutdown(cli, SHUT_WR);
  10763. #endif
  10764. // Drain until the client closes its end, ensuring all data is delivered
  10765. char drain[1024];
  10766. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10767. detail::close_socket(cli);
  10768. }
  10769. detail::close_socket(srv);
  10770. });
  10771. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10772. size_t total_read = 0;
  10773. {
  10774. Client cli("127.0.0.1", PORT + 2);
  10775. cli.set_read_timeout(5, 0);
  10776. cli.set_payload_max_length(0); // 0 means no limit
  10777. auto stream = cli.open_stream("GET", "/data");
  10778. ASSERT_TRUE(stream.is_valid());
  10779. char buffer[64 * 1024];
  10780. ssize_t n;
  10781. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10782. total_read += static_cast<size_t>(n);
  10783. }
  10784. }
  10785. server_thread.join();
  10786. EXPECT_EQ(total_read, DATA_SIZE)
  10787. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10788. << " bytes without truncation, but only read " << total_read << " bytes.";
  10789. }
  10790. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10791. // enormous Content-Length must not cause the client to pre-allocate a huge
  10792. // response body buffer. The reservation is capped at payload_max_length_, and
  10793. // the read itself fails when the body exceeds the limit.
  10794. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10795. #ifndef _WIN32
  10796. signal(SIGPIPE, SIG_IGN);
  10797. #endif
  10798. auto server_thread = std::thread([] {
  10799. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10800. default_socket_options(srv);
  10801. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10803. sockaddr_in addr{};
  10804. addr.sin_family = AF_INET;
  10805. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10806. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10807. int opt = 1;
  10808. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10809. #ifdef _WIN32
  10810. reinterpret_cast<const char *>(&opt),
  10811. #else
  10812. &opt,
  10813. #endif
  10814. sizeof(opt));
  10815. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10816. ::listen(srv, 1);
  10817. sockaddr_in cli_addr{};
  10818. socklen_t cli_len = sizeof(cli_addr);
  10819. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10820. if (cli != INVALID_SOCKET) {
  10821. char buf[4096];
  10822. ::recv(cli, buf, sizeof(buf), 0);
  10823. // Malicious response: claim a 20GB body but send only a tiny payload.
  10824. std::string response = "HTTP/1.1 200 OK\r\n"
  10825. "Content-Length: 20000000000\r\n"
  10826. "\r\n"
  10827. "abc";
  10828. ::send(cli,
  10829. #ifdef _WIN32
  10830. static_cast<const char *>(response.c_str()),
  10831. static_cast<int>(response.size()),
  10832. #else
  10833. response.c_str(), response.size(),
  10834. #endif
  10835. 0);
  10836. detail::close_socket(cli);
  10837. }
  10838. detail::close_socket(srv);
  10839. });
  10840. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10841. {
  10842. Client cli("127.0.0.1", PORT + 2);
  10843. cli.set_read_timeout(5, 0);
  10844. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10845. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10846. // (server claims more bytes than payload_max_length permits), but it must
  10847. // not exhaust memory before getting there.
  10848. auto res = cli.Get("/malicious");
  10849. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10850. }
  10851. server_thread.join();
  10852. }
  10853. // Verify that content_receiver bypasses the default payload_max_length,
  10854. // allowing streaming downloads larger than 100MB without requiring an explicit
  10855. // set_payload_max_length call.
  10856. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10857. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10858. #ifndef _WIN32
  10859. signal(SIGPIPE, SIG_IGN);
  10860. #endif
  10861. auto server_thread = std::thread([] {
  10862. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10863. default_socket_options(srv);
  10864. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10866. sockaddr_in addr{};
  10867. addr.sin_family = AF_INET;
  10868. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10869. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10870. int opt = 1;
  10871. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10872. #ifdef _WIN32
  10873. reinterpret_cast<const char *>(&opt),
  10874. #else
  10875. &opt,
  10876. #endif
  10877. sizeof(opt));
  10878. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10879. ::listen(srv, 1);
  10880. sockaddr_in cli_addr{};
  10881. socklen_t cli_len = sizeof(cli_addr);
  10882. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10883. if (cli != INVALID_SOCKET) {
  10884. char buf[4096];
  10885. ::recv(cli, buf, sizeof(buf), 0);
  10886. // Response with Content-Length larger than default 100MB limit
  10887. auto content_length = std::to_string(DATA_SIZE);
  10888. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10889. "Content-Length: " +
  10890. content_length +
  10891. "\r\n"
  10892. "Connection: close\r\n"
  10893. "\r\n";
  10894. ::send(cli,
  10895. #ifdef _WIN32
  10896. static_cast<const char *>(response_header.c_str()),
  10897. static_cast<int>(response_header.size()),
  10898. #else
  10899. response_header.c_str(), response_header.size(),
  10900. #endif
  10901. 0);
  10902. std::string chunk(64 * 1024, 'A');
  10903. size_t total_sent = 0;
  10904. while (total_sent < DATA_SIZE) {
  10905. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10906. auto sent = ::send(cli,
  10907. #ifdef _WIN32
  10908. static_cast<const char *>(chunk.c_str()),
  10909. static_cast<int>(to_send),
  10910. #else
  10911. chunk.c_str(), to_send,
  10912. #endif
  10913. 0);
  10914. if (sent <= 0) break;
  10915. total_sent += static_cast<size_t>(sent);
  10916. }
  10917. detail::close_socket(cli);
  10918. }
  10919. detail::close_socket(srv);
  10920. });
  10921. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10922. size_t total_received = 0;
  10923. {
  10924. Client cli("127.0.0.1", PORT + 2);
  10925. cli.set_read_timeout(10, 0);
  10926. // Do NOT call set_payload_max_length — use the default 100MB limit
  10927. auto res =
  10928. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10929. total_received += data_length;
  10930. return true;
  10931. });
  10932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10933. EXPECT_EQ(StatusCode::OK_200, res->status);
  10934. }
  10935. server_thread.join();
  10936. EXPECT_EQ(total_received, DATA_SIZE)
  10937. << "With content_receiver, the client should read all " << DATA_SIZE
  10938. << " bytes despite the default 100MB payload_max_length, but only read "
  10939. << total_received << " bytes.";
  10940. }
  10941. // Verify that an explicit set_payload_max_length smaller than the response is
  10942. // enforced even when a content_receiver is used.
  10943. TEST(ClientVulnerabilityTest,
  10944. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10945. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10946. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10947. #ifndef _WIN32
  10948. signal(SIGPIPE, SIG_IGN);
  10949. #endif
  10950. auto server_thread = std::thread([] {
  10951. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10952. default_socket_options(srv);
  10953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10955. sockaddr_in addr{};
  10956. addr.sin_family = AF_INET;
  10957. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10958. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10959. int opt = 1;
  10960. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10961. #ifdef _WIN32
  10962. reinterpret_cast<const char *>(&opt),
  10963. #else
  10964. &opt,
  10965. #endif
  10966. sizeof(opt));
  10967. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10968. ::listen(srv, 1);
  10969. sockaddr_in cli_addr{};
  10970. socklen_t cli_len = sizeof(cli_addr);
  10971. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10972. if (cli != INVALID_SOCKET) {
  10973. char buf[4096];
  10974. ::recv(cli, buf, sizeof(buf), 0);
  10975. auto content_length = std::to_string(DATA_SIZE);
  10976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10977. "Content-Length: " +
  10978. content_length +
  10979. "\r\n"
  10980. "Connection: close\r\n"
  10981. "\r\n";
  10982. ::send(cli,
  10983. #ifdef _WIN32
  10984. static_cast<const char *>(response_header.c_str()),
  10985. static_cast<int>(response_header.size()),
  10986. #else
  10987. response_header.c_str(), response_header.size(),
  10988. #endif
  10989. 0);
  10990. std::string chunk(64 * 1024, 'A');
  10991. size_t total_sent = 0;
  10992. while (total_sent < DATA_SIZE) {
  10993. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10994. auto sent = ::send(cli,
  10995. #ifdef _WIN32
  10996. static_cast<const char *>(chunk.c_str()),
  10997. static_cast<int>(to_send),
  10998. #else
  10999. chunk.c_str(), to_send,
  11000. #endif
  11001. 0);
  11002. if (sent <= 0) break;
  11003. total_sent += static_cast<size_t>(sent);
  11004. }
  11005. detail::close_socket(cli);
  11006. }
  11007. detail::close_socket(srv);
  11008. });
  11009. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11010. size_t total_received = 0;
  11011. {
  11012. Client cli("127.0.0.1", PORT + 2);
  11013. cli.set_read_timeout(10, 0);
  11014. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11015. auto res =
  11016. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11017. total_received += data_length;
  11018. return true;
  11019. });
  11020. // Should fail because 200MB exceeds the explicit 150MB limit
  11021. EXPECT_FALSE(res);
  11022. }
  11023. server_thread.join();
  11024. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11025. << "Client with content_receiver should respect the explicit "
  11026. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11027. << total_received << " bytes.";
  11028. }
  11029. // Verify that an explicit set_payload_max_length larger than the response
  11030. // allows the content_receiver to read all data successfully.
  11031. TEST(ClientVulnerabilityTest,
  11032. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11033. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11034. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11035. #ifndef _WIN32
  11036. signal(SIGPIPE, SIG_IGN);
  11037. #endif
  11038. auto server_thread = std::thread([] {
  11039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11040. default_socket_options(srv);
  11041. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11042. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11043. sockaddr_in addr{};
  11044. addr.sin_family = AF_INET;
  11045. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11046. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11047. int opt = 1;
  11048. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11049. #ifdef _WIN32
  11050. reinterpret_cast<const char *>(&opt),
  11051. #else
  11052. &opt,
  11053. #endif
  11054. sizeof(opt));
  11055. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11056. ::listen(srv, 1);
  11057. sockaddr_in cli_addr{};
  11058. socklen_t cli_len = sizeof(cli_addr);
  11059. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11060. if (cli != INVALID_SOCKET) {
  11061. char buf[4096];
  11062. ::recv(cli, buf, sizeof(buf), 0);
  11063. auto content_length = std::to_string(DATA_SIZE);
  11064. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11065. "Content-Length: " +
  11066. content_length +
  11067. "\r\n"
  11068. "Connection: close\r\n"
  11069. "\r\n";
  11070. ::send(cli,
  11071. #ifdef _WIN32
  11072. static_cast<const char *>(response_header.c_str()),
  11073. static_cast<int>(response_header.size()),
  11074. #else
  11075. response_header.c_str(), response_header.size(),
  11076. #endif
  11077. 0);
  11078. std::string chunk(64 * 1024, 'A');
  11079. size_t total_sent = 0;
  11080. while (total_sent < DATA_SIZE) {
  11081. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11082. auto sent = ::send(cli,
  11083. #ifdef _WIN32
  11084. static_cast<const char *>(chunk.c_str()),
  11085. static_cast<int>(to_send),
  11086. #else
  11087. chunk.c_str(), to_send,
  11088. #endif
  11089. 0);
  11090. if (sent <= 0) break;
  11091. total_sent += static_cast<size_t>(sent);
  11092. }
  11093. #ifdef _WIN32
  11094. ::shutdown(cli, SD_SEND);
  11095. #else
  11096. ::shutdown(cli, SHUT_WR);
  11097. #endif
  11098. char drain[1024];
  11099. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11100. detail::close_socket(cli);
  11101. }
  11102. detail::close_socket(srv);
  11103. });
  11104. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11105. size_t total_received = 0;
  11106. {
  11107. Client cli("127.0.0.1", PORT + 2);
  11108. cli.set_read_timeout(10, 0);
  11109. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11110. auto res =
  11111. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11112. total_received += data_length;
  11113. return true;
  11114. });
  11115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11116. EXPECT_EQ(StatusCode::OK_200, res->status);
  11117. }
  11118. server_thread.join();
  11119. EXPECT_EQ(total_received, DATA_SIZE)
  11120. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11121. << " bytes (larger than " << DATA_SIZE
  11122. << " bytes response), content_receiver should read all data, but only "
  11123. "read "
  11124. << total_received << " bytes.";
  11125. }
  11126. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11127. // Regression test for "zip bomb" attack on the client side: a malicious server
  11128. // sends a small gzip-compressed response that decompresses to a huge payload.
  11129. // The client must enforce payload_max_length on the decompressed size.
  11130. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11131. constexpr size_t DECOMPRESSED_SIZE =
  11132. 10 * 1024 * 1024; // 10MB after decompression
  11133. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11134. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11135. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11136. std::string compressed;
  11137. {
  11138. httplib::detail::gzip_compressor compressor;
  11139. bool ok =
  11140. compressor.compress(uncompressed.data(), uncompressed.size(),
  11141. /*last=*/true, [&](const char *buf, size_t len) {
  11142. compressed.append(buf, len);
  11143. return true;
  11144. });
  11145. ASSERT_TRUE(ok);
  11146. }
  11147. // Sanity: compressed data should be much smaller than the decompressed size
  11148. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11149. #ifndef _WIN32
  11150. signal(SIGPIPE, SIG_IGN);
  11151. #endif
  11152. // Set up the listening socket in the main thread so the server is guaranteed
  11153. // to be ready before the client connects (eliminates race condition).
  11154. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11155. default_socket_options(srv);
  11156. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11157. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11158. sockaddr_in addr{};
  11159. addr.sin_family = AF_INET;
  11160. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11161. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11162. int opt = 1;
  11163. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11164. #ifdef _WIN32
  11165. reinterpret_cast<const char *>(&opt),
  11166. #else
  11167. &opt,
  11168. #endif
  11169. sizeof(opt));
  11170. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11171. ASSERT_EQ(0, ::listen(srv, 1));
  11172. auto server_thread = std::thread([&compressed, srv] {
  11173. sockaddr_in cli_addr{};
  11174. socklen_t cli_len = sizeof(cli_addr);
  11175. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11176. if (cli != INVALID_SOCKET) {
  11177. // Read the full HTTP request (until \r\n\r\n)
  11178. char buf[4096];
  11179. size_t total = 0;
  11180. while (total < sizeof(buf)) {
  11181. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11182. if (n <= 0) break;
  11183. total += static_cast<size_t>(n);
  11184. // Check for end of headers
  11185. if (total >= 4) {
  11186. std::string req(buf, total);
  11187. if (req.find("\r\n\r\n") != std::string::npos) break;
  11188. }
  11189. }
  11190. // Malicious response: gzip-compressed body, no Content-Length
  11191. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11192. "Content-Encoding: gzip\r\n"
  11193. "Connection: close\r\n"
  11194. "\r\n";
  11195. ::send(cli,
  11196. #ifdef _WIN32
  11197. static_cast<const char *>(response_header.c_str()),
  11198. static_cast<int>(response_header.size()),
  11199. #else
  11200. response_header.c_str(), response_header.size(),
  11201. #endif
  11202. 0);
  11203. // Send the compressed payload (small on the wire, huge when decompressed)
  11204. size_t total_sent = 0;
  11205. while (total_sent < compressed.size()) {
  11206. auto to_send = std::min(compressed.size() - total_sent,
  11207. static_cast<size_t>(64 * 1024));
  11208. auto sent =
  11209. ::send(cli,
  11210. #ifdef _WIN32
  11211. static_cast<const char *>(compressed.c_str() + total_sent),
  11212. static_cast<int>(to_send),
  11213. #else
  11214. compressed.c_str() + total_sent, to_send,
  11215. #endif
  11216. 0);
  11217. if (sent <= 0) break;
  11218. total_sent += static_cast<size_t>(sent);
  11219. }
  11220. detail::close_socket(cli);
  11221. }
  11222. });
  11223. auto se = detail::scope_exit([&] {
  11224. detail::close_socket(srv);
  11225. server_thread.join();
  11226. });
  11227. size_t total_decompressed = 0;
  11228. {
  11229. Client cli("127.0.0.1", PORT + 3);
  11230. cli.set_read_timeout(5, 0);
  11231. cli.set_decompress(true);
  11232. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11233. auto stream = cli.open_stream("GET", "/zipbomb");
  11234. ASSERT_TRUE(stream.is_valid());
  11235. char buffer[64 * 1024];
  11236. ssize_t n;
  11237. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11238. total_decompressed += static_cast<size_t>(n);
  11239. }
  11240. }
  11241. // The decompressed size must be capped by payload_max_length. Without
  11242. // protection, the client would decompress the full 10MB from a tiny
  11243. // compressed payload, enabling a zip bomb DoS attack.
  11244. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11245. << "Client decompressed " << total_decompressed
  11246. << " bytes from a gzip response. The decompressed size should be "
  11247. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11248. }
  11249. #endif
  11250. TEST(HostAndPortPropertiesTest, NoSSL) {
  11251. httplib::Client cli("www.google.com", 1234);
  11252. ASSERT_EQ("www.google.com", cli.host());
  11253. ASSERT_EQ(1234, cli.port());
  11254. }
  11255. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11256. httplib::Client cli("www.google.com:1234");
  11257. ASSERT_EQ("www.google.com", cli.host());
  11258. ASSERT_EQ(1234, cli.port());
  11259. }
  11260. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11261. // Port number that overflows int — should not crash, client becomes invalid
  11262. httplib::Client cli("http://www.google.com:99999999999999999999");
  11263. ASSERT_FALSE(cli.is_valid());
  11264. }
  11265. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11266. // Port 99999 exceeds valid range (1-65535) — should not crash
  11267. httplib::Client cli("http://www.google.com:99999");
  11268. ASSERT_FALSE(cli.is_valid());
  11269. }
  11270. #ifdef CPPHTTPLIB_SSL_ENABLED
  11271. TEST(HostAndPortPropertiesTest, SSL) {
  11272. httplib::SSLClient cli("www.google.com");
  11273. ASSERT_EQ("www.google.com", cli.host());
  11274. ASSERT_EQ(443, cli.port());
  11275. }
  11276. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11277. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11278. std::string cert;
  11279. read_file(CA_CERT_FILE, cert);
  11280. httplib::SSLClient httplib_client("www.google.com");
  11281. // Load CA store first time
  11282. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11283. // Load CA store second time (update)
  11284. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11285. // Verify client is still valid and can make connections
  11286. httplib_client.enable_server_certificate_verification(true);
  11287. auto res = httplib_client.Get("/");
  11288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11289. // Google may return 200 or 301 depending on various factors
  11290. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11291. res->status == StatusCode::MovedPermanently_301);
  11292. }
  11293. TEST(SSLClientTest, ServerNameIndication_Online) {
  11294. auto host = "httpbingo.org";
  11295. auto path = std::string{"/get"};
  11296. SSLClient cli(host, 443);
  11297. auto res = cli.Get(path);
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. ASSERT_EQ(StatusCode::OK_200, res->status);
  11300. }
  11301. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11302. // Use a site that will cause SSL verification failure due to self-signed cert
  11303. SSLClient cli("self-signed.badssl.com", 443);
  11304. cli.enable_server_certificate_verification(true);
  11305. auto res = cli.Get("/");
  11306. ASSERT_TRUE(!res);
  11307. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11308. // Verify backend error is captured for SSLServerVerification
  11309. // This occurs when certificate verification fails
  11310. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11311. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11312. EXPECT_NE(0UL, res.ssl_backend_error());
  11313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11314. // For OpenSSL, ssl_error is 0 for verification errors
  11315. EXPECT_EQ(0, res.ssl_error());
  11316. #if !defined(_WIN32) || \
  11317. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11318. // On non-Windows or when Windows Schannel is disabled, the error comes
  11319. // from OpenSSL's verification
  11320. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11321. res.ssl_backend_error());
  11322. #endif
  11323. #endif
  11324. }
  11325. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11326. // Use a site where hostname doesn't match the certificate
  11327. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11328. SSLClient cli("wrong.host.badssl.com", 443);
  11329. cli.enable_server_certificate_verification(true);
  11330. cli.enable_server_hostname_verification(true);
  11331. auto res = cli.Get("/");
  11332. ASSERT_TRUE(!res);
  11333. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11334. // Verify backend error is captured for hostname verification failure
  11335. EXPECT_NE(0UL, res.ssl_backend_error());
  11336. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11337. // For OpenSSL, ssl_error is 0 for verification errors
  11338. EXPECT_EQ(0, res.ssl_error());
  11339. #if !defined(_WIN32) || \
  11340. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11341. // On non-Windows or when Windows Schannel is disabled, the error comes
  11342. // from OpenSSL's hostname verification
  11343. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11344. res.ssl_backend_error());
  11345. #endif
  11346. #endif
  11347. }
  11348. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11349. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11350. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11351. SSLClient cli("www.google.com", 443);
  11352. cli.enable_server_certificate_verification(true);
  11353. auto res = cli.Get("/");
  11354. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11355. }
  11356. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11357. SSLClient cli("www.google.com", 443);
  11358. cli.enable_server_certificate_verification(true);
  11359. cli.enable_windows_certificate_verification(false);
  11360. auto res = cli.Get("/");
  11361. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11362. }
  11363. #endif
  11364. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11365. Client cli("https://google.com");
  11366. auto res = cli.Get("/");
  11367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11368. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11369. }
  11370. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11371. SSLClient cli("google.com");
  11372. cli.set_ca_cert_path(CA_CERT_FILE);
  11373. auto res = cli.Get("/");
  11374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11375. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11376. }
  11377. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11378. SSLClient cli("google.com");
  11379. cli.enable_server_certificate_verification(true);
  11380. cli.set_ca_cert_path("hello");
  11381. auto res = cli.Get("/");
  11382. ASSERT_TRUE(!res);
  11383. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11384. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11385. // should be set
  11386. EXPECT_EQ(0, res.ssl_error());
  11387. // Verify backend error is captured for SSLLoadingCerts
  11388. // This error occurs when loading CA certificates fails
  11389. EXPECT_NE(0UL, res.ssl_backend_error());
  11390. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11391. // OpenSSL specific error codes:
  11392. // > openssl errstr 0x80000002
  11393. // error:80000002:system library::No such file or directory
  11394. // > openssl errstr 0xA000126
  11395. // error:0A000126:SSL routines::unexpected eof while reading
  11396. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11397. res.ssl_backend_error() == 0xA000126);
  11398. #endif
  11399. }
  11400. TEST(SSLClientTest, ServerCertificateVerification4) {
  11401. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11402. ASSERT_TRUE(svr.is_valid());
  11403. svr.Get("/test", [&](const Request &, Response &res) {
  11404. res.set_content("test", "text/plain");
  11405. svr.stop();
  11406. ASSERT_TRUE(true);
  11407. });
  11408. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11409. auto se = detail::scope_exit([&] {
  11410. t.join();
  11411. ASSERT_FALSE(svr.is_running());
  11412. });
  11413. svr.wait_until_ready();
  11414. SSLClient cli("127.0.0.1", PORT);
  11415. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11416. cli.enable_server_certificate_verification(true);
  11417. cli.set_connection_timeout(30);
  11418. auto res = cli.Get("/test");
  11419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11420. ASSERT_EQ(StatusCode::OK_200, res->status);
  11421. }
  11422. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11423. std::string cert;
  11424. read_file(CA_CERT_FILE, cert);
  11425. SSLClient cli("google.com");
  11426. cli.load_ca_cert_store(cert.data(), cert.size());
  11427. const auto res = cli.Get("/");
  11428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11429. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11430. }
  11431. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11432. // clang-format off
  11433. static constexpr char cert[] =
  11434. "GlobalSign Root CA\n"
  11435. "==================\n"
  11436. "-----BEGIN CERTIFICATE-----\n"
  11437. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11438. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11439. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11440. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11441. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11442. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11443. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11444. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11445. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11446. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11447. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11448. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11449. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11450. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11451. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11452. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11453. "-----END CERTIFICATE-----\n";
  11454. // clang-format on
  11455. SSLClient cli("google.com");
  11456. cli.load_ca_cert_store(cert, sizeof(cert));
  11457. const auto res = cli.Get("/");
  11458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11459. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11460. }
  11461. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11462. SSLClient cli("www.youtube.com");
  11463. cli.set_ca_cert_path(CA_CERT_FILE);
  11464. cli.enable_server_certificate_verification(true);
  11465. cli.set_follow_location(true);
  11466. auto res = cli.Get("/");
  11467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11468. ASSERT_EQ(StatusCode::OK_200, res->status);
  11469. }
  11470. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11471. SSLClient cli("wWw.YouTube.Com");
  11472. cli.set_ca_cert_path(CA_CERT_FILE);
  11473. cli.enable_server_certificate_verification(true);
  11474. cli.enable_server_hostname_verification(true);
  11475. cli.set_follow_location(true);
  11476. auto res = cli.Get("/");
  11477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11478. ASSERT_EQ(StatusCode::OK_200, res->status);
  11479. }
  11480. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11481. SSLClient cli("gOoGlE.COm");
  11482. cli.enable_server_certificate_verification(true);
  11483. cli.enable_server_hostname_verification(true);
  11484. cli.set_follow_location(true);
  11485. auto res = cli.Get("/");
  11486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11487. ASSERT_EQ(StatusCode::OK_200, res->status);
  11488. }
  11489. TEST(SSLClientTest, Issue2004_Online) {
  11490. Client client("https://google.com");
  11491. client.set_follow_location(true);
  11492. auto res = client.Get("/");
  11493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11494. ASSERT_EQ(StatusCode::OK_200, res->status);
  11495. auto body = res->body;
  11496. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11497. }
  11498. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11499. // Create SSLClient with invalid cert/key to make is_valid() return false
  11500. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11501. "nonexistent_key.pem");
  11502. // is_valid() should be false due to cert loading failure
  11503. ASSERT_FALSE(cli.is_valid());
  11504. auto res = cli.Get("/");
  11505. ASSERT_FALSE(res);
  11506. EXPECT_EQ(Error::SSLConnection, res.error());
  11507. }
  11508. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11509. // Test for Issue #2251: SSL error not properly reported when client cert
  11510. // and key paths are swapped or mismatched
  11511. // This simulates the scenario where user accidentally swaps the cert and key
  11512. // files
  11513. // Using client cert file as private key and vice versa (completely wrong)
  11514. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11515. // Should fail validation due to cert/key mismatch
  11516. ASSERT_FALSE(cli.is_valid());
  11517. // Attempt to make a request should fail with proper error
  11518. auto res = cli.Get("/");
  11519. ASSERT_FALSE(res);
  11520. EXPECT_EQ(Error::SSLConnection, res.error());
  11521. // SSL error should be recorded in the Result object (this is the key fix for
  11522. // Issue #2251)
  11523. auto backend_error = res.ssl_backend_error();
  11524. EXPECT_NE(0u, backend_error);
  11525. }
  11526. // Tests cert/key mismatch detection at the TLS context level
  11527. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11528. // Test that using mismatched cert/key causes connection failure.
  11529. // We verify this at the SSLClient level rather than through internal
  11530. // TLS API functions.
  11531. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11532. cli.enable_server_certificate_verification(false);
  11533. cli.set_connection_timeout(2);
  11534. // The mismatch should cause a connection or handshake error
  11535. auto res = cli.Get("/test");
  11536. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11537. // Either way, the request should fail
  11538. EXPECT_FALSE(res);
  11539. }
  11540. #endif
  11541. #if 0
  11542. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11543. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11544. ASSERT_TRUE(cli != nullptr);
  11545. cli->set_address_family(AF_INET6);
  11546. cli->set_interface("en0");
  11547. auto res = cli->Get("/get");
  11548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11549. ASSERT_EQ(StatusCode::OK_200, res->status);
  11550. }
  11551. #endif
  11552. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11553. #ifdef CPPHTTPLIB_SSL_ENABLED
  11554. void ClientCertPresent(
  11555. const std::string &client_cert_file,
  11556. const std::string &client_private_key_file,
  11557. const std::string &client_encrypted_private_key_pass = std::string()) {
  11558. using namespace httplib::tls;
  11559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11560. CLIENT_CA_CERT_DIR);
  11561. ASSERT_TRUE(svr.is_valid());
  11562. svr.Get("/test", [&](const Request &req, Response &res) {
  11563. res.set_content("test", "text/plain");
  11564. auto cert = req.peer_cert();
  11565. ASSERT_TRUE(static_cast<bool>(cert));
  11566. std::string common_name = cert.subject_cn();
  11567. EXPECT_EQ("Common Name", common_name);
  11568. });
  11569. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11577. client_encrypted_private_key_pass);
  11578. cli.enable_server_certificate_verification(false);
  11579. cli.set_connection_timeout(30);
  11580. auto res = cli.Get("/test");
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. ASSERT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. TEST(SSLClientServerTest, ClientCertPresent) {
  11585. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11586. }
  11587. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11588. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11589. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11590. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11591. }
  11592. // PEM memory-based constructor tests (works with all TLS backends)
  11593. void PemMemoryClientCertPresent(
  11594. const std::string &client_cert_file,
  11595. const std::string &client_private_key_file,
  11596. const std::string &client_encrypted_private_key_pass = std::string()) {
  11597. // Read PEM files into memory
  11598. std::string server_cert_pem, server_key_pem;
  11599. std::string client_ca_pem;
  11600. std::string client_cert_pem, client_key_pem;
  11601. read_file(SERVER_CERT_FILE, server_cert_pem);
  11602. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11603. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11604. read_file(client_cert_file, client_cert_pem);
  11605. read_file(client_private_key_file, client_key_pem);
  11606. // Create server with PEM memory
  11607. SSLServer::PemMemory server_pem = {
  11608. server_cert_pem.c_str(),
  11609. server_cert_pem.size(),
  11610. server_key_pem.c_str(),
  11611. server_key_pem.size(),
  11612. client_ca_pem.c_str(),
  11613. client_ca_pem.size(),
  11614. nullptr // no password for server key
  11615. };
  11616. SSLServer svr(server_pem);
  11617. ASSERT_TRUE(svr.is_valid());
  11618. svr.Get("/test", [&](const Request &, Response &res) {
  11619. res.set_content("test", "text/plain");
  11620. });
  11621. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11622. auto se = detail::scope_exit([&] {
  11623. svr.stop();
  11624. t.join();
  11625. ASSERT_FALSE(svr.is_running());
  11626. });
  11627. svr.wait_until_ready();
  11628. // Create client with PEM memory
  11629. const char *password = client_encrypted_private_key_pass.empty()
  11630. ? nullptr
  11631. : client_encrypted_private_key_pass.c_str();
  11632. SSLClient::PemMemory client_pem = {
  11633. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11634. client_key_pem.size(), password};
  11635. SSLClient cli(HOST, PORT, client_pem);
  11636. cli.enable_server_certificate_verification(false);
  11637. cli.set_connection_timeout(30);
  11638. auto res = cli.Get("/test");
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. ASSERT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11643. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11644. }
  11645. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11646. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11647. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11648. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11649. }
  11650. TEST(SSLClientServerTest, ClientCertMissing) {
  11651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11652. CLIENT_CA_CERT_DIR);
  11653. ASSERT_TRUE(svr.is_valid());
  11654. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11655. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11656. auto se = detail::scope_exit([&] {
  11657. svr.stop();
  11658. t.join();
  11659. ASSERT_FALSE(svr.is_running());
  11660. });
  11661. svr.wait_until_ready();
  11662. SSLClient cli(HOST, PORT);
  11663. cli.set_connection_timeout(30);
  11664. auto res = cli.Get("/test");
  11665. ASSERT_TRUE(!res);
  11666. // When client cert is missing and server requires it, connection fails
  11667. // Error type depends on backend implementation
  11668. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11669. res.error() == Error::SSLConnection);
  11670. // Verify backend error is captured
  11671. // Note: This test may have different error codes depending on the exact
  11672. // verification failure
  11673. EXPECT_NE(0UL, res.ssl_backend_error());
  11674. }
  11675. TEST(SSLClientServerTest, TrustDirOptional) {
  11676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11677. ASSERT_TRUE(svr.is_valid());
  11678. svr.Get("/test", [&](const Request &, Response &res) {
  11679. res.set_content("test", "text/plain");
  11680. });
  11681. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. t.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11689. cli.enable_server_certificate_verification(false);
  11690. cli.set_connection_timeout(30);
  11691. auto res = cli.Get("/test");
  11692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11693. ASSERT_EQ(StatusCode::OK_200, res->status);
  11694. }
  11695. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11696. class NoListenSSLServer : public SSLServer {
  11697. public:
  11698. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11699. const char *client_ca_cert_file_path,
  11700. const char *client_ca_cert_dir_path = nullptr)
  11701. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11702. client_ca_cert_dir_path),
  11703. stop_(false) {}
  11704. std::atomic_bool stop_;
  11705. private:
  11706. bool process_and_close_socket(socket_t /*sock*/) override {
  11707. // Don't create SSL context
  11708. while (!stop_.load()) {
  11709. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11710. }
  11711. return true;
  11712. }
  11713. };
  11714. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11715. CLIENT_CA_CERT_FILE);
  11716. ASSERT_TRUE(svr.is_valid());
  11717. svr.Get("/test", [&](const Request &, Response &res) {
  11718. res.set_content("test", "text/plain");
  11719. });
  11720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop_ = true;
  11723. svr.stop();
  11724. t.join();
  11725. ASSERT_FALSE(svr.is_running());
  11726. });
  11727. svr.wait_until_ready();
  11728. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11729. cli.enable_server_certificate_verification(false);
  11730. cli.set_connection_timeout(1);
  11731. auto res = cli.Get("/test");
  11732. ASSERT_TRUE(!res);
  11733. EXPECT_EQ(Error::SSLConnection, res.error());
  11734. // Timeout results in WantRead error code (maps to backend-specific value)
  11735. EXPECT_NE(0, res.ssl_error());
  11736. }
  11737. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11738. // Test SSLServer with client certificate verification using the standard
  11739. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11741. CLIENT_CA_CERT_DIR);
  11742. ASSERT_TRUE(svr.is_valid());
  11743. svr.Get("/test", [&](const Request &req, Response &res) {
  11744. res.set_content("test", "text/plain");
  11745. auto cert = req.peer_cert();
  11746. ASSERT_TRUE(static_cast<bool>(cert));
  11747. auto common_name = cert.subject_cn();
  11748. EXPECT_EQ("Common Name", common_name);
  11749. });
  11750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11751. auto se = detail::scope_exit([&] {
  11752. svr.stop();
  11753. t.join();
  11754. ASSERT_FALSE(svr.is_running());
  11755. });
  11756. svr.wait_until_ready();
  11757. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11758. cli.enable_server_certificate_verification(false);
  11759. cli.set_connection_timeout(30);
  11760. auto res = cli.Get("/test");
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. ASSERT_EQ(StatusCode::OK_200, res->status);
  11763. }
  11764. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11765. // Verifies that wildcard matching and exact matching work consistently
  11766. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11767. using namespace httplib::tls;
  11768. // We need a running server to test against
  11769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11770. ASSERT_TRUE(svr.is_valid());
  11771. svr.Get("/test", [](const Request &, Response &res) {
  11772. res.set_content("ok", "text/plain");
  11773. });
  11774. thread t([&]() { svr.listen(HOST, PORT); });
  11775. auto se = detail::scope_exit([&] {
  11776. svr.stop();
  11777. t.join();
  11778. });
  11779. svr.wait_until_ready();
  11780. bool verify_callback_called = false;
  11781. bool verify_result_wrong = false;
  11782. SSLClient cli(HOST, PORT);
  11783. cli.enable_server_certificate_verification(true);
  11784. cli.set_ca_cert_path(CA_CERT_FILE);
  11785. cli.set_connection_timeout(5);
  11786. // Note: Test certificate has CN="Common Name", not "localhost"
  11787. bool verify_result_cn = false;
  11788. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11789. verify_callback_called = true;
  11790. if (!ctx.cert) return false;
  11791. // Test 1: "Common Name" should match (our test server cert CN)
  11792. verify_result_cn = ctx.check_hostname("Common Name");
  11793. // Test 2: wrong hostname should not match
  11794. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11795. return true; // Accept for the purpose of this test
  11796. });
  11797. auto res = cli.Get("/test");
  11798. // The request may succeed or fail depending on cert configuration
  11799. // but the callback should have been called
  11800. ASSERT_TRUE(verify_callback_called)
  11801. << "Verify callback should have been called";
  11802. // CN="Common Name" should match our test certificate
  11803. //
  11804. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11805. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11806. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11807. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11808. // <openssl/base.h>, which is included transitively when
  11809. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11810. #if defined(OPENSSL_IS_BORINGSSL)
  11811. EXPECT_FALSE(verify_result_cn)
  11812. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11813. #else
  11814. EXPECT_TRUE(verify_result_cn)
  11815. << "verify_hostname should match 'Common Name' (certificate CN)";
  11816. #endif
  11817. // Wrong hostname should not match
  11818. EXPECT_FALSE(verify_result_wrong)
  11819. << "verify_hostname should not match 'wronghost.example.com'";
  11820. }
  11821. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11822. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11823. // X509_check_ip behavior and must hold for every backend.
  11824. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11825. using namespace httplib::tls;
  11826. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11827. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11828. ASSERT_TRUE(svr.is_valid());
  11829. svr.Get("/test", [](const Request &, Response &res) {
  11830. res.set_content("ok", "text/plain");
  11831. });
  11832. thread t([&]() { svr.listen(HOST, PORT); });
  11833. auto se = detail::scope_exit([&] {
  11834. svr.stop();
  11835. t.join();
  11836. });
  11837. svr.wait_until_ready();
  11838. bool verify_callback_called = false;
  11839. bool ip_matched_via_cn = true;
  11840. SSLClient cli(HOST, PORT);
  11841. cli.enable_server_certificate_verification(true);
  11842. cli.set_ca_cert_path(CA_CERT_FILE);
  11843. cli.set_connection_timeout(5);
  11844. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11845. verify_callback_called = true;
  11846. if (!ctx.cert) return false;
  11847. // The IP appears only in the CN, so it must NOT be accepted.
  11848. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11849. return true; // Accept for the purpose of this test
  11850. });
  11851. cli.Get("/test");
  11852. ASSERT_TRUE(verify_callback_called)
  11853. << "Verify callback should have been called";
  11854. EXPECT_FALSE(ip_matched_via_cn)
  11855. << "An IP host must not be authenticated via the certificate CN";
  11856. }
  11857. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11858. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11859. using namespace httplib::tls;
  11860. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11861. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11862. ASSERT_TRUE(svr.is_valid());
  11863. svr.Get("/test", [](const Request &, Response &res) {
  11864. res.set_content("ok", "text/plain");
  11865. });
  11866. thread t([&]() { svr.listen(HOST, PORT); });
  11867. auto se = detail::scope_exit([&] {
  11868. svr.stop();
  11869. t.join();
  11870. });
  11871. svr.wait_until_ready();
  11872. bool verify_callback_called = false;
  11873. bool san_matched = false;
  11874. bool wrong_ipv6_matched = true;
  11875. bool cn_ipv6_matched = true;
  11876. SSLClient cli(HOST, PORT);
  11877. cli.enable_server_certificate_verification(true);
  11878. cli.set_ca_cert_path(CA_CERT_FILE);
  11879. cli.set_connection_timeout(5);
  11880. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11881. verify_callback_called = true;
  11882. if (!ctx.cert) return false;
  11883. // Matches the IPv6 iPAddress SAN.
  11884. san_matched = ctx.check_hostname("2001:db8::1");
  11885. // A different IPv6 address must not match.
  11886. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11887. // "::1" lives only in the CN, so it must not be accepted.
  11888. cn_ipv6_matched = ctx.check_hostname("::1");
  11889. return true; // Accept for the purpose of this test
  11890. });
  11891. cli.Get("/test");
  11892. ASSERT_TRUE(verify_callback_called)
  11893. << "Verify callback should have been called";
  11894. EXPECT_TRUE(san_matched)
  11895. << "verify_hostname should match an IPv6 iPAddress SAN";
  11896. EXPECT_FALSE(wrong_ipv6_matched)
  11897. << "verify_hostname should not match a non-matching IPv6 address";
  11898. EXPECT_FALSE(cn_ipv6_matched)
  11899. << "An IPv6 host must not be authenticated via the certificate CN";
  11900. }
  11901. #endif
  11902. // mbedTLS-specific callback constructor test
  11903. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11904. #ifdef CPPHTTPLIB_SSL_ENABLED
  11905. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11907. ASSERT_TRUE(svr.is_valid());
  11908. // Set up a handler to verify client certificate is present
  11909. bool client_cert_verified = false;
  11910. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11911. // Verify that client certificate was provided
  11912. client_cert_verified = true;
  11913. res.set_content("success", "text/plain");
  11914. });
  11915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11916. auto se = detail::scope_exit([&] {
  11917. svr.stop();
  11918. t.join();
  11919. ASSERT_FALSE(svr.is_running());
  11920. });
  11921. svr.wait_until_ready();
  11922. // Client with certificate
  11923. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11924. cli.enable_server_certificate_verification(false);
  11925. cli.set_connection_timeout(30);
  11926. auto res = cli.Get("/test");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. ASSERT_EQ(StatusCode::OK_200, res->status);
  11929. ASSERT_TRUE(client_cert_verified);
  11930. EXPECT_EQ("success", res->body);
  11931. }
  11932. #endif
  11933. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11934. // backends
  11935. #ifdef CPPHTTPLIB_SSL_ENABLED
  11936. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11937. using namespace httplib::tls;
  11938. // Test that when client CA cert file is provided,
  11939. // the server properly requests and validates client certificates
  11940. // Create a server with client authentication
  11941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11942. ASSERT_TRUE(svr.is_valid());
  11943. bool handler_called = false;
  11944. svr.Get("/test", [&](const Request &req, Response &res) {
  11945. handler_called = true;
  11946. // Verify that a client certificate was provided
  11947. auto cert = req.peer_cert();
  11948. ASSERT_TRUE(static_cast<bool>(cert));
  11949. // Get the issuer name
  11950. std::string issuer_str = cert.issuer_name();
  11951. ASSERT_FALSE(issuer_str.empty());
  11952. // The client certificate should be issued by our test CA
  11953. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11954. res.set_content("authenticated", "text/plain");
  11955. });
  11956. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11957. auto se = detail::scope_exit([&] {
  11958. svr.stop();
  11959. t.join();
  11960. ASSERT_FALSE(svr.is_running());
  11961. });
  11962. svr.wait_until_ready();
  11963. // Connect with a client certificate issued by the CA
  11964. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11965. cli.enable_server_certificate_verification(false);
  11966. cli.set_connection_timeout(30);
  11967. auto res = cli.Get("/test");
  11968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11969. ASSERT_EQ(StatusCode::OK_200, res->status);
  11970. ASSERT_TRUE(handler_called);
  11971. EXPECT_EQ("authenticated", res->body);
  11972. }
  11973. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11974. using namespace httplib::tls;
  11975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11976. ASSERT_TRUE(svr.is_valid());
  11977. svr.Get("/test", [](const Request &, Response &res) {
  11978. res.set_content("ok", "text/plain");
  11979. });
  11980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. t.join();
  11984. });
  11985. svr.wait_until_ready();
  11986. SSLClient cli(HOST, PORT);
  11987. cli.enable_server_certificate_verification(false);
  11988. cli.set_connection_timeout(30);
  11989. bool cert_checked = false;
  11990. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11991. if (ctx.cert) {
  11992. auto sans = ctx.sans();
  11993. // Test certificate may or may not have SANs - just verify the API
  11994. // works If SANs exist, verify the types are valid
  11995. for (const auto &san : sans) {
  11996. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11997. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11998. san.type == SanType::OTHER);
  11999. EXPECT_FALSE(san.value.empty());
  12000. }
  12001. cert_checked = true;
  12002. }
  12003. return true;
  12004. });
  12005. auto res = cli.Get("/test");
  12006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12007. EXPECT_TRUE(cert_checked);
  12008. }
  12009. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12010. using namespace httplib::tls;
  12011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12012. ASSERT_TRUE(svr.is_valid());
  12013. svr.Get("/test", [](const Request &, Response &res) {
  12014. res.set_content("ok", "text/plain");
  12015. });
  12016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12017. auto se = detail::scope_exit([&] {
  12018. svr.stop();
  12019. t.join();
  12020. });
  12021. svr.wait_until_ready();
  12022. SSLClient cli(HOST, PORT);
  12023. cli.enable_server_certificate_verification(false);
  12024. cli.set_connection_timeout(30);
  12025. bool validity_checked = false;
  12026. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12027. if (ctx.cert) {
  12028. time_t not_before = 0, not_after = 0;
  12029. bool result = ctx.validity(not_before, not_after);
  12030. EXPECT_TRUE(result);
  12031. // Verify that not_before < now < not_after for a valid cert
  12032. time_t now = time(nullptr);
  12033. EXPECT_LT(not_before, now);
  12034. EXPECT_GT(not_after, now);
  12035. validity_checked = true;
  12036. }
  12037. return true;
  12038. });
  12039. auto res = cli.Get("/test");
  12040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12041. EXPECT_TRUE(validity_checked);
  12042. }
  12043. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12044. using namespace httplib::tls;
  12045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12046. ASSERT_TRUE(svr.is_valid());
  12047. svr.Get("/test", [](const Request &, Response &res) {
  12048. res.set_content("ok", "text/plain");
  12049. });
  12050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12051. auto se = detail::scope_exit([&] {
  12052. svr.stop();
  12053. t.join();
  12054. });
  12055. svr.wait_until_ready();
  12056. SSLClient cli(HOST, PORT);
  12057. cli.enable_server_certificate_verification(false);
  12058. cli.set_connection_timeout(30);
  12059. bool serial_checked = false;
  12060. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12061. if (ctx.cert) {
  12062. std::string serial = ctx.serial();
  12063. EXPECT_FALSE(serial.empty());
  12064. // Serial should be a hex string
  12065. for (char c : serial) {
  12066. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12067. (c >= 'a' && c <= 'f'));
  12068. }
  12069. serial_checked = true;
  12070. }
  12071. return true;
  12072. });
  12073. auto res = cli.Get("/test");
  12074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12075. EXPECT_TRUE(serial_checked);
  12076. }
  12077. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12078. // Test 1: Valid CA file - no error should be recorded
  12079. {
  12080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12081. CLIENT_CA_CERT_FILE);
  12082. ASSERT_TRUE(svr.is_valid());
  12083. // With valid setup, last_ssl_error should be 0
  12084. EXPECT_EQ(0, svr.ssl_last_error());
  12085. }
  12086. // Test 2: Invalid CA file content
  12087. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12088. {
  12089. // Create a temporary file with completely invalid content
  12090. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12091. {
  12092. std::ofstream ofs(temp_invalid_ca);
  12093. ofs << "This is not a certificate file at all\n";
  12094. ofs << "Just plain text content\n";
  12095. }
  12096. // Create server with invalid CA file
  12097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12098. // Clean up temporary file
  12099. std::remove(temp_invalid_ca);
  12100. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12101. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12102. // Note: SSL_CTX_load_verify_locations typically fails first,
  12103. // but our error handling code path is still exercised
  12104. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12105. }
  12106. }
  12107. TEST(VerifyCallbackTest, VerifyContextFields) {
  12108. using namespace httplib::tls;
  12109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12110. ASSERT_TRUE(svr.is_valid());
  12111. svr.Get("/test", [](const Request &, Response &res) {
  12112. res.set_content("ok", "text/plain");
  12113. });
  12114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12115. auto se = detail::scope_exit([&] {
  12116. svr.stop();
  12117. t.join();
  12118. });
  12119. svr.wait_until_ready();
  12120. SSLClient cli(HOST, PORT);
  12121. cli.enable_server_certificate_verification(false);
  12122. cli.set_connection_timeout(30);
  12123. int callback_count = 0;
  12124. bool saw_leaf_cert = false;
  12125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12126. if (ctx.cert) {
  12127. callback_count++;
  12128. // We should see at least one certificate (the leaf)
  12129. std::string cn = ctx.subject_cn();
  12130. if (!cn.empty()) { saw_leaf_cert = true; }
  12131. // Verify context fields are populated
  12132. EXPECT_NE(ctx.session, nullptr);
  12133. EXPECT_GE(ctx.depth, 0);
  12134. }
  12135. return true;
  12136. });
  12137. auto res = cli.Get("/test");
  12138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12139. EXPECT_GT(callback_count, 0);
  12140. EXPECT_TRUE(saw_leaf_cert);
  12141. }
  12142. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12143. using httplib::tls::TlsError;
  12144. // Test that verify_error_to_string returns empty for success
  12145. std::string success_str = TlsError::verify_error_to_string(0);
  12146. EXPECT_TRUE(success_str.empty());
  12147. // Test that verify_error_to_string returns non-empty for error codes
  12148. // Using a common error code (certificate expired)
  12149. std::string error_str =
  12150. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12151. EXPECT_FALSE(error_str.empty());
  12152. }
  12153. TEST(SessionVerifierTest, CertificateAccepted) {
  12154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12155. ASSERT_TRUE(svr.is_valid());
  12156. svr.Get("/test", [](const Request &, Response &res) {
  12157. res.set_content("ok", "text/plain");
  12158. });
  12159. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. });
  12164. svr.wait_until_ready();
  12165. SSLClient cli(HOST, PORT);
  12166. cli.enable_server_certificate_verification(false);
  12167. cli.set_connection_timeout(30);
  12168. bool callback_called = false;
  12169. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12170. EXPECT_NE(session, nullptr);
  12171. callback_called = true;
  12172. return SSLVerifierResponse::CertificateAccepted;
  12173. });
  12174. auto res = cli.Get("/test");
  12175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12176. EXPECT_EQ(200, res->status);
  12177. EXPECT_TRUE(callback_called);
  12178. }
  12179. TEST(SessionVerifierTest, CertificateRejected) {
  12180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12181. ASSERT_TRUE(svr.is_valid());
  12182. svr.Get("/test", [](const Request &, Response &res) {
  12183. res.set_content("ok", "text/plain");
  12184. });
  12185. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12186. auto se = detail::scope_exit([&] {
  12187. svr.stop();
  12188. t.join();
  12189. });
  12190. svr.wait_until_ready();
  12191. SSLClient cli(HOST, PORT);
  12192. cli.enable_server_certificate_verification(false);
  12193. cli.set_connection_timeout(30);
  12194. bool callback_called = false;
  12195. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12196. EXPECT_NE(session, nullptr);
  12197. callback_called = true;
  12198. return SSLVerifierResponse::CertificateRejected;
  12199. });
  12200. auto res = cli.Get("/test");
  12201. EXPECT_FALSE(res);
  12202. EXPECT_TRUE(callback_called);
  12203. }
  12204. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12206. ASSERT_TRUE(svr.is_valid());
  12207. svr.Get("/test", [](const Request &, Response &res) {
  12208. res.set_content("ok", "text/plain");
  12209. });
  12210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. t.join();
  12214. });
  12215. svr.wait_until_ready();
  12216. // NoDecisionMade with verification disabled should succeed (no default check)
  12217. SSLClient cli(HOST, PORT);
  12218. cli.enable_server_certificate_verification(false);
  12219. cli.set_connection_timeout(30);
  12220. bool callback_called = false;
  12221. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12222. EXPECT_NE(session, nullptr);
  12223. callback_called = true;
  12224. return SSLVerifierResponse::NoDecisionMade;
  12225. });
  12226. auto res = cli.Get("/test");
  12227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12228. EXPECT_EQ(200, res->status);
  12229. EXPECT_TRUE(callback_called);
  12230. }
  12231. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12233. ASSERT_TRUE(svr.is_valid());
  12234. svr.Get("/test", [](const Request &, Response &res) {
  12235. res.set_content("ok", "text/plain");
  12236. });
  12237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. });
  12242. svr.wait_until_ready();
  12243. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12244. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12245. // so we only check that the request fails, not whether the callback was
  12246. // called.
  12247. SSLClient cli(HOST, PORT);
  12248. cli.enable_server_certificate_verification(true);
  12249. cli.set_connection_timeout(30);
  12250. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12251. EXPECT_NE(session, nullptr);
  12252. return SSLVerifierResponse::NoDecisionMade;
  12253. });
  12254. auto res = cli.Get("/test");
  12255. EXPECT_FALSE(res);
  12256. }
  12257. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12258. // Test SSL server using PemMemory constructor with client CA certificates
  12259. // Read PEM files
  12260. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12261. read_file(SERVER_CERT_FILE, server_cert_pem);
  12262. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12263. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12264. // Create SSLServer with PemMemory constructor including client CA
  12265. SSLServer::PemMemory server_pem = {
  12266. server_cert_pem.c_str(),
  12267. server_cert_pem.size(),
  12268. server_key_pem.c_str(),
  12269. server_key_pem.size(),
  12270. client_ca_pem.c_str(),
  12271. client_ca_pem.size(),
  12272. nullptr // no password for server key
  12273. };
  12274. SSLServer svr(server_pem);
  12275. ASSERT_TRUE(svr.is_valid());
  12276. // No SSL error should be recorded for valid setup
  12277. EXPECT_EQ(0, svr.ssl_last_error());
  12278. // Set up server endpoints
  12279. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12280. res.set_content("ok", "text/plain");
  12281. });
  12282. // Start server in a thread
  12283. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12284. svr.wait_until_ready();
  12285. // Connect with client certificate (using constructor with paths)
  12286. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12287. cli.enable_server_certificate_verification(false);
  12288. auto res = cli.Get("/test-pem-ca");
  12289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12290. EXPECT_EQ(200, res->status);
  12291. EXPECT_EQ("ok", res->body);
  12292. svr.stop();
  12293. server_thread.join();
  12294. }
  12295. #endif
  12296. #ifdef _WIN32
  12297. TEST(CleanupTest, WSACleanup) {
  12298. int ret = WSACleanup();
  12299. ASSERT_EQ(0, ret);
  12300. }
  12301. #endif
  12302. #ifndef CPPHTTPLIB_SSL_ENABLED
  12303. TEST(NoSSLSupport, SimpleInterface) {
  12304. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12305. }
  12306. #endif
  12307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12308. TEST(InvalidScheme, SimpleInterface) {
  12309. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12310. }
  12311. #endif
  12312. TEST(NoScheme, SimpleInterface) {
  12313. Client cli("yahoo.com:80");
  12314. ASSERT_TRUE(cli.is_valid());
  12315. }
  12316. TEST(SendAPI, SimpleInterface_Online) {
  12317. Client cli("http://yahoo.com");
  12318. Request req;
  12319. req.method = "GET";
  12320. req.path = "/";
  12321. auto res = cli.send(req);
  12322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12323. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12324. }
  12325. TEST(SendAPI, WithParamsInRequest) {
  12326. Server svr;
  12327. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12328. EXPECT_TRUE(req.has_param("test"));
  12329. EXPECT_EQ("test_value", req.get_param_value("test"));
  12330. });
  12331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12332. auto se = detail::scope_exit([&] {
  12333. svr.stop();
  12334. t.join();
  12335. ASSERT_FALSE(svr.is_running());
  12336. });
  12337. svr.wait_until_ready();
  12338. Client cli(HOST, PORT);
  12339. {
  12340. Request req;
  12341. req.method = "GET";
  12342. req.path = "/";
  12343. req.params.emplace("test", "test_value");
  12344. auto res = cli.send(req);
  12345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12346. }
  12347. {
  12348. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. }
  12351. }
  12352. TEST(ClientImplMethods, GetSocketTest) {
  12353. httplib::Server svr;
  12354. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12355. res.status = StatusCode::OK_200;
  12356. });
  12357. auto port = svr.bind_to_any_port("127.0.0.1");
  12358. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12359. auto se = detail::scope_exit([&] {
  12360. svr.stop();
  12361. thread.join();
  12362. ASSERT_FALSE(svr.is_running());
  12363. });
  12364. svr.wait_until_ready();
  12365. {
  12366. httplib::Client cli("127.0.0.1", port);
  12367. cli.set_keep_alive(true);
  12368. // Use the behavior of cpp-httplib of opening the connection
  12369. // only when the first request happens. If that changes,
  12370. // this test would be obsolete.
  12371. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12372. // This also implicitly tests the server. But other tests would fail much
  12373. // earlier than this one to be considered.
  12374. auto res = cli.Get("/");
  12375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12376. EXPECT_EQ(StatusCode::OK_200, res->status);
  12377. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12378. }
  12379. }
  12380. #ifdef CPPHTTPLIB_SSL_ENABLED
  12381. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12382. Client cli("http://yahoo.com");
  12383. auto res = cli.Get("/");
  12384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12385. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12386. cli.set_follow_location(true);
  12387. res = cli.Get("/");
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. EXPECT_EQ(StatusCode::OK_200, res->status);
  12390. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12391. }
  12392. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12393. Client cli("https://yahoo.com");
  12394. auto res = cli.Get("/");
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12397. cli.set_follow_location(true);
  12398. res = cli.Get("/");
  12399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12400. EXPECT_EQ(StatusCode::OK_200, res->status);
  12401. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12402. }
  12403. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12404. Client cli("https://yahoo.com");
  12405. auto res = cli.Get("/");
  12406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12407. ASSERT_FALSE(!res);
  12408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12409. ASSERT_FALSE(res == nullptr);
  12410. ASSERT_TRUE(res != nullptr);
  12411. EXPECT_EQ(Error::Success, res.error());
  12412. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12413. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12414. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12415. cli.set_follow_location(true);
  12416. res = cli.Get("/");
  12417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12418. EXPECT_EQ(Error::Success, res.error());
  12419. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12420. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12421. EXPECT_EQ(StatusCode::OK_200, res->status);
  12422. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12423. }
  12424. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12425. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12426. Client cli("https://cdnjs.cloudflare.com");
  12427. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12428. Headers{{"Accept-Encoding", "br"}});
  12429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12430. EXPECT_EQ(StatusCode::OK_200, res->status);
  12431. EXPECT_EQ(287630U, res->body.size());
  12432. EXPECT_EQ("application/javascript; charset=utf-8",
  12433. res->get_header_value("Content-Type"));
  12434. }
  12435. #endif
  12436. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12437. #undef REDIR_HOST // Silence compiler warning
  12438. #define REDIR_HOST "https://httpbingo.org"
  12439. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12440. Client cli(REDIR_HOST);
  12441. cli.set_follow_location(true);
  12442. auto res =
  12443. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12445. EXPECT_EQ(StatusCode::OK_200, res->status);
  12446. }
  12447. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12448. Client cli(REDIR_HOST);
  12449. cli.set_follow_location(true);
  12450. Params params;
  12451. params.emplace("url", "http://example.com");
  12452. params.emplace("status_code", "302");
  12453. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12455. EXPECT_EQ(StatusCode::OK_200, res->status);
  12456. }
  12457. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12458. Client cli(REDIR_HOST);
  12459. cli.set_follow_location(true);
  12460. Params params;
  12461. params.emplace("url", "http://example.com");
  12462. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12464. EXPECT_EQ(StatusCode::OK_200, res->status);
  12465. }
  12466. TEST(HttpToHttpsRedirectTest, CertFile) {
  12467. auto ssl_port = PORT + 1;
  12468. Server svr;
  12469. ASSERT_TRUE(svr.is_valid());
  12470. svr.Get("/index", [&](const Request &, Response &res) {
  12471. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12472. "/index");
  12473. svr.stop();
  12474. });
  12475. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12476. ASSERT_TRUE(ssl_svr.is_valid());
  12477. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12478. res.set_content("test", "text/plain");
  12479. ssl_svr.stop();
  12480. });
  12481. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12482. thread t2 =
  12483. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12484. auto se = detail::scope_exit([&] {
  12485. t2.join();
  12486. t.join();
  12487. ASSERT_FALSE(svr.is_running());
  12488. });
  12489. svr.wait_until_ready();
  12490. ssl_svr.wait_until_ready();
  12491. Client cli("127.0.0.1", PORT);
  12492. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12493. cli.enable_server_certificate_verification(true);
  12494. cli.set_follow_location(true);
  12495. cli.set_connection_timeout(30);
  12496. auto res = cli.Get("/index");
  12497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12498. ASSERT_EQ(StatusCode::OK_200, res->status);
  12499. }
  12500. TEST(SSLClientRedirectTest, CertFile) {
  12501. auto ssl_port = PORT + 1;
  12502. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12503. ASSERT_TRUE(ssl_svr1.is_valid());
  12504. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12505. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12506. "/index");
  12507. ssl_svr1.stop();
  12508. });
  12509. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12510. ASSERT_TRUE(ssl_svr2.is_valid());
  12511. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12512. res.set_content("test", "text/plain");
  12513. ssl_svr2.stop();
  12514. });
  12515. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12516. thread t2 =
  12517. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12518. auto se = detail::scope_exit([&] {
  12519. t2.join();
  12520. t.join();
  12521. ASSERT_FALSE(ssl_svr1.is_running());
  12522. });
  12523. ssl_svr1.wait_until_ready();
  12524. ssl_svr2.wait_until_ready();
  12525. SSLClient cli("127.0.0.1", PORT);
  12526. std::string cert;
  12527. read_file(SERVER_CERT2_FILE, cert);
  12528. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12529. cli.enable_server_certificate_verification(true);
  12530. cli.set_follow_location(true);
  12531. cli.set_connection_timeout(30);
  12532. auto res = cli.Get("/index");
  12533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12534. ASSERT_EQ(StatusCode::OK_200, res->status);
  12535. }
  12536. #endif
  12537. #ifdef CPPHTTPLIB_SSL_ENABLED
  12538. // Test that set_ca_cert_store() skips system certs (consistent with
  12539. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12540. // should be trusted - system certs should NOT be loaded.
  12541. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12542. // Load a specific cert that is NOT a system CA cert
  12543. std::string cert;
  12544. read_file(SERVER_CERT2_FILE, cert);
  12545. SSLClient cli("google.com");
  12546. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12547. cli.enable_server_certificate_verification(true);
  12548. // This should FAIL because:
  12549. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12550. // 2. System certs should NOT be loaded when custom store is set
  12551. // If system certs WERE loaded, this would succeed
  12552. auto res = cli.Get("/");
  12553. ASSERT_FALSE(res);
  12554. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12555. }
  12556. // Same as above, but through the native store handle path. Regression test:
  12557. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12558. // merged system certs into the user-provided store.
  12559. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12560. std::string cert;
  12561. read_file(SERVER_CERT2_FILE, cert);
  12562. SSLClient cli("google.com");
  12563. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12564. cli.enable_server_certificate_verification(true);
  12565. auto res = cli.Get("/");
  12566. ASSERT_FALSE(res);
  12567. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12568. }
  12569. // A custom store set via the native handle must still verify a server whose
  12570. // cert it does contain.
  12571. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12572. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12573. ASSERT_TRUE(svr.is_valid());
  12574. svr.Get("/test", [&](const Request &, Response &res) {
  12575. res.set_content("test", "text/plain");
  12576. });
  12577. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12578. auto se = detail::scope_exit([&] {
  12579. svr.stop();
  12580. t.join();
  12581. ASSERT_FALSE(svr.is_running());
  12582. });
  12583. svr.wait_until_ready();
  12584. SSLClient cli("127.0.0.1", PORT);
  12585. std::string cert;
  12586. read_file(SERVER_CERT2_FILE, cert);
  12587. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12588. cli.enable_server_certificate_verification(true);
  12589. cli.set_connection_timeout(30);
  12590. auto res = cli.Get("/test");
  12591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12592. ASSERT_EQ(StatusCode::OK_200, res->status);
  12593. }
  12594. // CA certs loaded through the universal Client must be transferred to the
  12595. // client created internally for following an HTTPS redirect. Regression test:
  12596. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12597. // the CA data for redirect transfer.
  12598. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12599. auto ssl_port = PORT + 1;
  12600. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12601. ASSERT_TRUE(ssl_svr1.is_valid());
  12602. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12603. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12604. "/index");
  12605. });
  12606. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12607. ASSERT_TRUE(ssl_svr2.is_valid());
  12608. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12609. res.set_content("test", "text/plain");
  12610. });
  12611. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12612. thread t2 =
  12613. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12614. auto se = detail::scope_exit([&] {
  12615. ssl_svr2.stop();
  12616. ssl_svr1.stop();
  12617. t2.join();
  12618. t.join();
  12619. ASSERT_FALSE(ssl_svr1.is_running());
  12620. });
  12621. ssl_svr1.wait_until_ready();
  12622. ssl_svr2.wait_until_ready();
  12623. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12624. std::string cert;
  12625. read_file(SERVER_CERT2_FILE, cert);
  12626. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12627. cli.enable_server_certificate_verification(true);
  12628. cli.set_follow_location(true);
  12629. cli.set_connection_timeout(30);
  12630. auto res = cli.Get("/index");
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. ASSERT_EQ(StatusCode::OK_200, res->status);
  12633. }
  12634. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12635. // so a host signed by a system CA verifies even though a custom CA is set
  12636. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12637. std::string cert;
  12638. read_file(SERVER_CERT2_FILE, cert);
  12639. SSLClient cli("google.com");
  12640. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12641. cli.enable_system_ca(true);
  12642. cli.enable_server_certificate_verification(true);
  12643. auto res = cli.Get("/");
  12644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12645. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12646. }
  12647. // The custom CA remains effective when combined with the system CA
  12648. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12649. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12650. ASSERT_TRUE(svr.is_valid());
  12651. svr.Get("/test", [&](const Request &, Response &res) {
  12652. res.set_content("test", "text/plain");
  12653. });
  12654. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12655. auto se = detail::scope_exit([&] {
  12656. svr.stop();
  12657. t.join();
  12658. ASSERT_FALSE(svr.is_running());
  12659. });
  12660. svr.wait_until_ready();
  12661. SSLClient cli("127.0.0.1", PORT);
  12662. std::string cert;
  12663. read_file(SERVER_CERT2_FILE, cert);
  12664. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12665. cli.enable_system_ca(true);
  12666. cli.enable_server_certificate_verification(true);
  12667. cli.set_connection_timeout(30);
  12668. auto res = cli.Get("/test");
  12669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12670. ASSERT_EQ(StatusCode::OK_200, res->status);
  12671. }
  12672. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12673. // skip chain verification entirely (only the certificate identity was
  12674. // checked), so a server presenting an untrusted certificate with a matching
  12675. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12676. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12678. ASSERT_TRUE(svr.is_valid());
  12679. svr.Get("/test", [&](const Request &, Response &res) {
  12680. res.set_content("test", "text/plain");
  12681. });
  12682. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12683. auto se = detail::scope_exit([&] {
  12684. svr.stop();
  12685. t.join();
  12686. ASSERT_FALSE(svr.is_running());
  12687. });
  12688. svr.wait_until_ready();
  12689. SSLClient cli("127.0.0.1", PORT);
  12690. std::string cert;
  12691. // A trusted CA that did not sign the server certificate. The server cert
  12692. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12693. // this connection.
  12694. read_file(CLIENT_CA_CERT_FILE, cert);
  12695. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12696. cli.enable_server_certificate_verification(true);
  12697. cli.set_connection_timeout(30);
  12698. auto res = cli.Get("/test");
  12699. ASSERT_FALSE(res);
  12700. }
  12701. // enable_system_ca(false) prevents system CA loading entirely
  12702. TEST(SSLClientTest, DisableSystemCa_Online) {
  12703. SSLClient cli("google.com");
  12704. cli.enable_system_ca(false);
  12705. cli.enable_server_certificate_verification(true);
  12706. auto res = cli.Get("/");
  12707. ASSERT_FALSE(res);
  12708. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12709. // itself when the CA chain is empty
  12710. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12711. res.error() == Error::SSLConnection);
  12712. }
  12713. // The universal Client forwards enable_system_ca()
  12714. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12715. std::string cert;
  12716. read_file(SERVER_CERT2_FILE, cert);
  12717. Client cli("https://google.com");
  12718. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12719. cli.enable_system_ca(true);
  12720. cli.enable_server_certificate_verification(true);
  12721. auto res = cli.Get("/");
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12724. }
  12725. // The system CA policy must carry over to the client created internally for
  12726. // following a cross-host HTTPS redirect
  12727. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12728. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12729. ASSERT_TRUE(svr.is_valid());
  12730. svr.Get("/index", [&](const Request &, Response &res) {
  12731. res.set_redirect("https://www.google.com/");
  12732. });
  12733. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12734. auto se = detail::scope_exit([&] {
  12735. svr.stop();
  12736. t.join();
  12737. ASSERT_FALSE(svr.is_running());
  12738. });
  12739. svr.wait_until_ready();
  12740. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12741. std::string cert;
  12742. read_file(SERVER_CERT2_FILE, cert);
  12743. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12744. cli.enable_system_ca(true);
  12745. cli.enable_server_certificate_verification(true);
  12746. cli.set_follow_location(true);
  12747. cli.set_connection_timeout(30);
  12748. // Receiving any response proves the redirect client completed the TLS
  12749. // handshake with a system-CA-signed host
  12750. auto res = cli.Get("/index");
  12751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12752. }
  12753. TEST(MultipartFormDataTest, LargeData) {
  12754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12755. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12756. const ContentReader &content_reader) {
  12757. if (req.is_multipart_form_data()) {
  12758. std::vector<FormData> items;
  12759. content_reader(
  12760. [&](const FormData &file) {
  12761. items.push_back(file);
  12762. return true;
  12763. },
  12764. [&](const char *data, size_t data_length) {
  12765. items.back().content.append(data, data_length);
  12766. return true;
  12767. });
  12768. EXPECT_TRUE(std::string(items[0].name) == "document");
  12769. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12770. EXPECT_TRUE(items[0].filename == "2MB_data");
  12771. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12772. EXPECT_TRUE(items[1].name == "hello");
  12773. EXPECT_TRUE(items[1].content == "world");
  12774. EXPECT_TRUE(items[1].filename == "");
  12775. EXPECT_TRUE(items[1].content_type == "");
  12776. } else {
  12777. std::string body;
  12778. content_reader([&](const char *data, size_t data_length) {
  12779. body.append(data, data_length);
  12780. return true;
  12781. });
  12782. }
  12783. });
  12784. auto port = svr.bind_to_any_port(HOST);
  12785. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12786. auto se = detail::scope_exit([&] {
  12787. svr.stop();
  12788. t.join();
  12789. ASSERT_FALSE(svr.is_running());
  12790. });
  12791. svr.wait_until_ready();
  12792. {
  12793. std::string data(1024 * 1024 * 2, '.');
  12794. std::stringstream buffer;
  12795. buffer << data;
  12796. SSLClient cli(HOST, port);
  12797. cli.enable_server_certificate_verification(false);
  12798. UploadFormDataItems items{
  12799. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12800. {"hello", "world", "", ""},
  12801. };
  12802. auto res = cli.Post("/post", items);
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. ASSERT_EQ(StatusCode::OK_200, res->status);
  12805. }
  12806. }
  12807. TEST(MultipartFormDataTest, DataProviderItems) {
  12808. std::random_device seed_gen;
  12809. std::mt19937 random(seed_gen());
  12810. std::string rand1;
  12811. rand1.resize(1000);
  12812. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12813. std::string rand2;
  12814. rand2.resize(3000);
  12815. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12818. const ContentReader &content_reader) {
  12819. ASSERT_FALSE(req.is_multipart_form_data());
  12820. std::string body;
  12821. content_reader([&](const char *data, size_t data_length) {
  12822. body.append(data, data_length);
  12823. return true;
  12824. });
  12825. EXPECT_EQ(body, "");
  12826. });
  12827. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12828. const ContentReader &content_reader) {
  12829. ASSERT_TRUE(req.is_multipart_form_data());
  12830. std::vector<FormData> items;
  12831. content_reader(
  12832. [&](const FormData &file) {
  12833. items.push_back(file);
  12834. return true;
  12835. },
  12836. [&](const char *data, size_t data_length) {
  12837. items.back().content.append(data, data_length);
  12838. return true;
  12839. });
  12840. ASSERT_TRUE(items.size() == 2);
  12841. EXPECT_EQ(std::string(items[0].name), "name1");
  12842. EXPECT_EQ(items[0].content, "Testing123");
  12843. EXPECT_EQ(items[0].filename, "filename1");
  12844. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12845. EXPECT_EQ(items[1].name, "name2");
  12846. EXPECT_EQ(items[1].content, "Testing456");
  12847. EXPECT_EQ(items[1].filename, "");
  12848. EXPECT_EQ(items[1].content_type, "");
  12849. });
  12850. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12851. const ContentReader &content_reader) {
  12852. ASSERT_TRUE(req.is_multipart_form_data());
  12853. std::vector<FormData> items;
  12854. content_reader(
  12855. [&](const FormData &file) {
  12856. items.push_back(file);
  12857. return true;
  12858. },
  12859. [&](const char *data, size_t data_length) {
  12860. items.back().content.append(data, data_length);
  12861. return true;
  12862. });
  12863. ASSERT_TRUE(items.size() == 2);
  12864. EXPECT_EQ(items[0].name, "name3");
  12865. EXPECT_EQ(items[0].content, rand1);
  12866. EXPECT_EQ(items[0].filename, "filename3");
  12867. EXPECT_EQ(items[0].content_type, "");
  12868. EXPECT_EQ(items[1].name, "name4");
  12869. EXPECT_EQ(items[1].content, rand2);
  12870. EXPECT_EQ(items[1].filename, "filename4");
  12871. EXPECT_EQ(items[1].content_type, "");
  12872. });
  12873. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12874. const ContentReader &content_reader) {
  12875. ASSERT_TRUE(req.is_multipart_form_data());
  12876. std::vector<FormData> items;
  12877. content_reader(
  12878. [&](const FormData &file) {
  12879. items.push_back(file);
  12880. return true;
  12881. },
  12882. [&](const char *data, size_t data_length) {
  12883. items.back().content.append(data, data_length);
  12884. return true;
  12885. });
  12886. ASSERT_TRUE(items.size() == 4);
  12887. EXPECT_EQ(std::string(items[0].name), "name1");
  12888. EXPECT_EQ(items[0].content, "Testing123");
  12889. EXPECT_EQ(items[0].filename, "filename1");
  12890. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12891. EXPECT_EQ(items[1].name, "name2");
  12892. EXPECT_EQ(items[1].content, "Testing456");
  12893. EXPECT_EQ(items[1].filename, "");
  12894. EXPECT_EQ(items[1].content_type, "");
  12895. EXPECT_EQ(items[2].name, "name3");
  12896. EXPECT_EQ(items[2].content, rand1);
  12897. EXPECT_EQ(items[2].filename, "filename3");
  12898. EXPECT_EQ(items[2].content_type, "");
  12899. EXPECT_EQ(items[3].name, "name4");
  12900. EXPECT_EQ(items[3].content, rand2);
  12901. EXPECT_EQ(items[3].filename, "filename4");
  12902. EXPECT_EQ(items[3].content_type, "");
  12903. });
  12904. auto port = svr.bind_to_any_port("localhost");
  12905. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12906. auto se = detail::scope_exit([&] {
  12907. svr.stop();
  12908. t.join();
  12909. ASSERT_FALSE(svr.is_running());
  12910. });
  12911. svr.wait_until_ready();
  12912. {
  12913. SSLClient cli("localhost", port);
  12914. cli.enable_server_certificate_verification(false);
  12915. UploadFormDataItems items{
  12916. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12917. {"name2", "Testing456", "", ""}, // not a file
  12918. };
  12919. {
  12920. auto res = cli.Post("/post-none", {}, {}, {});
  12921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12922. ASSERT_EQ(StatusCode::OK_200, res->status);
  12923. }
  12924. FormDataProviderItems providers;
  12925. {
  12926. auto res =
  12927. cli.Post("/post-items", {}, items, providers); // empty providers
  12928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12929. ASSERT_EQ(StatusCode::OK_200, res->status);
  12930. }
  12931. providers.push_back({"name3",
  12932. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12933. // test the offset is given correctly at each step
  12934. if (!offset)
  12935. sink.os.write(rand1.data(), 30);
  12936. else if (offset == 30)
  12937. sink.os.write(rand1.data() + 30, 300);
  12938. else if (offset == 330)
  12939. sink.os.write(rand1.data() + 330, 670);
  12940. else if (offset == rand1.size())
  12941. sink.done();
  12942. return true;
  12943. },
  12944. "filename3",
  12945. {}});
  12946. providers.push_back({"name4",
  12947. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12948. // test the offset is given correctly at each step
  12949. if (!offset)
  12950. sink.os.write(rand2.data(), 2000);
  12951. else if (offset == 2000)
  12952. sink.os.write(rand2.data() + 2000, 1);
  12953. else if (offset == 2001)
  12954. sink.os.write(rand2.data() + 2001, 999);
  12955. else if (offset == rand2.size())
  12956. sink.done();
  12957. return true;
  12958. },
  12959. "filename4",
  12960. {}});
  12961. {
  12962. auto res = cli.Post("/post-providers", {}, {}, providers);
  12963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12964. ASSERT_EQ(StatusCode::OK_200, res->status);
  12965. }
  12966. {
  12967. auto res = cli.Post("/post-both", {}, items, providers);
  12968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12969. ASSERT_EQ(StatusCode::OK_200, res->status);
  12970. }
  12971. }
  12972. }
  12973. TEST(MultipartFormDataTest, BadHeader) {
  12974. Server svr;
  12975. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12976. res.set_content("ok", "text/plain");
  12977. });
  12978. thread t = thread([&] { svr.listen(HOST, PORT); });
  12979. auto se = detail::scope_exit([&] {
  12980. svr.stop();
  12981. t.join();
  12982. ASSERT_FALSE(svr.is_running());
  12983. });
  12984. svr.wait_until_ready();
  12985. const std::string body =
  12986. "This is the preamble. It is to be ignored, though it\r\n"
  12987. "is a handy place for composition agents to include an\r\n"
  12988. "explanatory note to non-MIME conformant readers.\r\n"
  12989. "\r\n"
  12990. "\r\n"
  12991. "--simple boundary\r\n"
  12992. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12993. ": BAD...\r\n"
  12994. "\r\n"
  12995. "value1\r\n"
  12996. "--simple boundary\r\n"
  12997. "Content-Disposition: form-data; name=\"field2\"; "
  12998. "filename=\"example.txt\"\r\n"
  12999. "\r\n"
  13000. "value2\r\n"
  13001. "--simple boundary--\r\n"
  13002. "This is the epilogue. It is also to be ignored.\r\n";
  13003. std::string content_type =
  13004. R"(multipart/form-data; boundary="simple boundary")";
  13005. Client cli(HOST, PORT);
  13006. auto res = cli.Post("/post", body, content_type.c_str());
  13007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13008. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13009. }
  13010. TEST(MultipartFormDataTest, WithPreamble) {
  13011. Server svr;
  13012. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13013. res.set_content("ok", "text/plain");
  13014. });
  13015. thread t = thread([&] { svr.listen(HOST, PORT); });
  13016. auto se = detail::scope_exit([&] {
  13017. svr.stop();
  13018. t.join();
  13019. ASSERT_FALSE(svr.is_running());
  13020. });
  13021. svr.wait_until_ready();
  13022. const std::string body =
  13023. "This is the preamble. It is to be ignored, though it\r\n"
  13024. "is a handy place for composition agents to include an\r\n"
  13025. "explanatory note to non-MIME conformant readers.\r\n"
  13026. "\r\n"
  13027. "\r\n"
  13028. "--simple boundary\r\n"
  13029. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13030. "\r\n"
  13031. "value1\r\n"
  13032. "--simple boundary\r\n"
  13033. "Content-Disposition: form-data; name=\"field2\"; "
  13034. "filename=\"example.txt\"\r\n"
  13035. "\r\n"
  13036. "value2\r\n"
  13037. "--simple boundary--\r\n"
  13038. "This is the epilogue. It is also to be ignored.\r\n";
  13039. std::string content_type =
  13040. R"(multipart/form-data; boundary="simple boundary")";
  13041. Client cli(HOST, PORT);
  13042. auto res = cli.Post("/post", body, content_type.c_str());
  13043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13044. EXPECT_EQ(StatusCode::OK_200, res->status);
  13045. }
  13046. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13048. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13049. const ContentReader &content_reader) {
  13050. if (req.is_multipart_form_data()) {
  13051. std::vector<FormData> items;
  13052. content_reader(
  13053. [&](const FormData &file) {
  13054. items.push_back(file);
  13055. return true;
  13056. },
  13057. [&](const char *data, size_t data_length) {
  13058. items.back().content.append(data, data_length);
  13059. return true;
  13060. });
  13061. EXPECT_TRUE(std::string(items[0].name) == "document");
  13062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13063. EXPECT_TRUE(items[0].filename == "2MB_data");
  13064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13065. EXPECT_TRUE(items[1].name == "hello");
  13066. EXPECT_TRUE(items[1].content == "world");
  13067. EXPECT_TRUE(items[1].filename == "");
  13068. EXPECT_TRUE(items[1].content_type == "");
  13069. } else {
  13070. std::string body;
  13071. content_reader([&](const char *data, size_t data_length) {
  13072. body.append(data, data_length);
  13073. return true;
  13074. });
  13075. }
  13076. });
  13077. auto port = svr.bind_to_any_port("localhost");
  13078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13079. auto se = detail::scope_exit([&] {
  13080. svr.stop();
  13081. t.join();
  13082. ASSERT_FALSE(svr.is_running());
  13083. });
  13084. svr.wait_until_ready();
  13085. {
  13086. std::string data(1024 * 1024 * 2, '.');
  13087. std::stringstream buffer;
  13088. buffer << data;
  13089. SSLClient cli("localhost", port);
  13090. cli.enable_server_certificate_verification(false);
  13091. UploadFormDataItems items{
  13092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13093. {"hello", "world", "", ""},
  13094. };
  13095. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13097. ASSERT_EQ(StatusCode::OK_200, res->status);
  13098. }
  13099. }
  13100. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13101. std::string data(1024 * 1024 * 2, '&');
  13102. std::stringstream buffer;
  13103. buffer << data;
  13104. Client cli("https://localhost:8080");
  13105. UploadFormDataItems items{
  13106. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13107. {"hello", "world", "", ""},
  13108. };
  13109. for (const char &c : " \t\r\n") {
  13110. auto res =
  13111. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13112. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13113. ASSERT_FALSE(res);
  13114. }
  13115. }
  13116. TEST(MultipartFormDataTest, PutFormData) {
  13117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13118. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13119. const ContentReader &content_reader) {
  13120. if (req.is_multipart_form_data()) {
  13121. std::vector<FormData> items;
  13122. content_reader(
  13123. [&](const FormData &file) {
  13124. items.push_back(file);
  13125. return true;
  13126. },
  13127. [&](const char *data, size_t data_length) {
  13128. items.back().content.append(data, data_length);
  13129. return true;
  13130. });
  13131. EXPECT_TRUE(std::string(items[0].name) == "document");
  13132. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13133. EXPECT_TRUE(items[0].filename == "2MB_data");
  13134. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13135. EXPECT_TRUE(items[1].name == "hello");
  13136. EXPECT_TRUE(items[1].content == "world");
  13137. EXPECT_TRUE(items[1].filename == "");
  13138. EXPECT_TRUE(items[1].content_type == "");
  13139. } else {
  13140. std::string body;
  13141. content_reader([&](const char *data, size_t data_length) {
  13142. body.append(data, data_length);
  13143. return true;
  13144. });
  13145. }
  13146. });
  13147. auto port = svr.bind_to_any_port("localhost");
  13148. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13149. auto se = detail::scope_exit([&] {
  13150. svr.stop();
  13151. t.join();
  13152. ASSERT_FALSE(svr.is_running());
  13153. });
  13154. svr.wait_until_ready();
  13155. {
  13156. std::string data(1024 * 1024 * 2, '&');
  13157. std::stringstream buffer;
  13158. buffer << data;
  13159. SSLClient cli("localhost", port);
  13160. cli.enable_server_certificate_verification(false);
  13161. UploadFormDataItems items{
  13162. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13163. {"hello", "world", "", ""},
  13164. };
  13165. auto res = cli.Put("/put", items);
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. ASSERT_EQ(StatusCode::OK_200, res->status);
  13168. }
  13169. }
  13170. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13172. svr.Put("/put_customboundary",
  13173. [&](const Request &req, const Response & /*res*/,
  13174. const ContentReader &content_reader) {
  13175. if (req.is_multipart_form_data()) {
  13176. std::vector<FormData> items;
  13177. content_reader(
  13178. [&](const FormData &file) {
  13179. items.push_back(file);
  13180. return true;
  13181. },
  13182. [&](const char *data, size_t data_length) {
  13183. items.back().content.append(data, data_length);
  13184. return true;
  13185. });
  13186. EXPECT_TRUE(std::string(items[0].name) == "document");
  13187. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13188. EXPECT_TRUE(items[0].filename == "2MB_data");
  13189. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13190. EXPECT_TRUE(items[1].name == "hello");
  13191. EXPECT_TRUE(items[1].content == "world");
  13192. EXPECT_TRUE(items[1].filename == "");
  13193. EXPECT_TRUE(items[1].content_type == "");
  13194. } else {
  13195. std::string body;
  13196. content_reader([&](const char *data, size_t data_length) {
  13197. body.append(data, data_length);
  13198. return true;
  13199. });
  13200. }
  13201. });
  13202. auto port = svr.bind_to_any_port("localhost");
  13203. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13204. auto se = detail::scope_exit([&] {
  13205. svr.stop();
  13206. t.join();
  13207. ASSERT_FALSE(svr.is_running());
  13208. });
  13209. svr.wait_until_ready();
  13210. {
  13211. std::string data(1024 * 1024 * 2, '&');
  13212. std::stringstream buffer;
  13213. buffer << data;
  13214. SSLClient cli("localhost", port);
  13215. cli.enable_server_certificate_verification(false);
  13216. UploadFormDataItems items{
  13217. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13218. {"hello", "world", "", ""},
  13219. };
  13220. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13222. ASSERT_EQ(StatusCode::OK_200, res->status);
  13223. }
  13224. }
  13225. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13226. std::string data(1024 * 1024 * 2, '&');
  13227. std::stringstream buffer;
  13228. buffer << data;
  13229. Client cli("https://localhost:8080");
  13230. cli.enable_server_certificate_verification(false);
  13231. UploadFormDataItems items{
  13232. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13233. {"hello", "world", "", ""},
  13234. };
  13235. for (const char &c : " \t\r\n") {
  13236. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13237. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13238. ASSERT_FALSE(res);
  13239. }
  13240. }
  13241. TEST(MultipartFormDataTest, AlternateFilename) {
  13242. auto handled = false;
  13243. Server svr;
  13244. svr.Post("/test", [&](const Request &req, Response &res) {
  13245. ASSERT_EQ(2u, req.form.files.size());
  13246. ASSERT_EQ(1u, req.form.fields.size());
  13247. // Test files
  13248. const auto &file1 = req.form.get_file("file1");
  13249. ASSERT_EQ("file1", file1.name);
  13250. ASSERT_EQ("A.txt", file1.filename);
  13251. ASSERT_EQ("text/plain", file1.content_type);
  13252. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13253. const auto &file2 = req.form.get_file("file2");
  13254. ASSERT_EQ("file2", file2.name);
  13255. ASSERT_EQ("a.html", file2.filename);
  13256. ASSERT_EQ("text/html", file2.content_type);
  13257. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13258. file2.content);
  13259. // Test text field
  13260. const auto &text = req.form.get_field("text");
  13261. ASSERT_EQ("text default", text);
  13262. res.set_content("ok", "text/plain");
  13263. handled = true;
  13264. });
  13265. thread t = thread([&] { svr.listen(HOST, PORT); });
  13266. auto se = detail::scope_exit([&] {
  13267. svr.stop();
  13268. t.join();
  13269. ASSERT_FALSE(svr.is_running());
  13270. ASSERT_TRUE(handled);
  13271. });
  13272. svr.wait_until_ready();
  13273. auto req = "POST /test HTTP/1.1\r\n"
  13274. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13275. "Content-Length: 399\r\n"
  13276. "\r\n"
  13277. "----------\r\n"
  13278. "Content-Disposition: form-data; name=\"text\"\r\n"
  13279. "\r\n"
  13280. "text default\r\n"
  13281. "----------\r\n"
  13282. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13283. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13284. "Content-Type: text/plain\r\n"
  13285. "\r\n"
  13286. "Content of a.txt.\r\n"
  13287. "\r\n"
  13288. "----------\r\n"
  13289. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13290. "\"a.html\"\r\n"
  13291. "Content-Type: text/html\r\n"
  13292. "\r\n"
  13293. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13294. "\r\n"
  13295. "------------\r\n";
  13296. ASSERT_TRUE(send_request(1, req));
  13297. }
  13298. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13299. auto handled = false;
  13300. Server svr;
  13301. svr.Post("/test", [&](const Request &req, Response &res) {
  13302. // Case-insensitive "utf-8''" prefix with a long value
  13303. const auto &file = req.form.get_file("file1");
  13304. ASSERT_EQ("file1", file.name);
  13305. // 8000 chars exercises both the Content-Disposition parser and the
  13306. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13307. // Prior to the fix, std::regex_match on this header would cause O(N)
  13308. // stack recursion in libstdc++, leading to SIGSEGV.
  13309. std::string expected_filename(8000, 'A');
  13310. ASSERT_EQ(expected_filename, file.filename);
  13311. res.set_content("ok", "text/plain");
  13312. handled = true;
  13313. });
  13314. thread t = thread([&] { svr.listen(HOST, PORT); });
  13315. auto se = detail::scope_exit([&] {
  13316. svr.stop();
  13317. t.join();
  13318. ASSERT_FALSE(svr.is_running());
  13319. ASSERT_TRUE(handled);
  13320. });
  13321. svr.wait_until_ready();
  13322. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13323. // Regression test for GHSA-qq6v-r583-3h69
  13324. std::string long_filename(8000, 'A');
  13325. std::string body = "----------\r\n"
  13326. "Content-Disposition: form-data; name=\"file1\"; "
  13327. "filename*=\"Utf-8''" +
  13328. long_filename +
  13329. "\"\r\n"
  13330. "\r\n"
  13331. "hello\r\n"
  13332. "------------\r\n";
  13333. auto req = "POST /test HTTP/1.1\r\n"
  13334. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13335. "Content-Length: " +
  13336. std::to_string(body.size()) + "\r\n\r\n" + body;
  13337. ASSERT_TRUE(send_request(1, req));
  13338. }
  13339. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13340. auto handled = false;
  13341. Server svr;
  13342. svr.Post("/test", [&](const Request &req, Response &) {
  13343. ASSERT_EQ(2u, req.form.fields.size());
  13344. const auto &text1 = req.form.get_field("text1");
  13345. ASSERT_EQ("text1", text1);
  13346. const auto &text2 = req.form.get_field("text2");
  13347. ASSERT_EQ("text2", text2);
  13348. handled = true;
  13349. });
  13350. thread t = thread([&] { svr.listen(HOST, PORT); });
  13351. auto se = detail::scope_exit([&] {
  13352. svr.stop();
  13353. t.join();
  13354. ASSERT_FALSE(svr.is_running());
  13355. ASSERT_TRUE(handled);
  13356. });
  13357. svr.wait_until_ready();
  13358. auto req = "POST /test HTTP/1.1\r\n"
  13359. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13360. "Content-Length: 146\r\n"
  13361. "\r\n----------\r\n"
  13362. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13363. "\r\n"
  13364. "text1"
  13365. "\r\n----------\r\n"
  13366. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13367. "\r\n"
  13368. "text2"
  13369. "\r\n------------";
  13370. std::string response;
  13371. ASSERT_TRUE(send_request(1, req, &response));
  13372. ASSERT_EQ("200", response.substr(9, 3));
  13373. }
  13374. TEST(MultipartFormDataTest, ContentLength) {
  13375. auto handled = false;
  13376. Server svr;
  13377. svr.Post("/test", [&](const Request &req, Response &) {
  13378. ASSERT_EQ(2u, req.form.fields.size());
  13379. const auto &text1 = req.form.get_field("text1");
  13380. ASSERT_EQ("text1", text1);
  13381. const auto &text2 = req.form.get_field("text2");
  13382. ASSERT_EQ("text2", text2);
  13383. handled = true;
  13384. });
  13385. thread t = thread([&] { svr.listen(HOST, PORT); });
  13386. auto se = detail::scope_exit([&] {
  13387. svr.stop();
  13388. t.join();
  13389. ASSERT_FALSE(svr.is_running());
  13390. ASSERT_TRUE(handled);
  13391. });
  13392. svr.wait_until_ready();
  13393. auto req = "POST /test HTTP/1.1\r\n"
  13394. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13395. "Content-Length: 167\r\n"
  13396. "\r\n----------\r\n"
  13397. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13398. "Content-Length: 5\r\n"
  13399. "\r\n"
  13400. "text1"
  13401. "\r\n----------\r\n"
  13402. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13403. "\r\n"
  13404. "text2"
  13405. "\r\n------------\r\n";
  13406. std::string response;
  13407. ASSERT_TRUE(send_request(1, req, &response));
  13408. ASSERT_EQ("200", response.substr(9, 3));
  13409. }
  13410. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13411. auto handled = false;
  13412. Server svr;
  13413. svr.Post("/test", [&](const Request &req, Response &) {
  13414. ASSERT_EQ(2u, req.form.fields.size());
  13415. const auto &text1 = req.form.get_field("text1");
  13416. ASSERT_EQ("text1", text1);
  13417. // TODO: Add header access for text fields if needed
  13418. const auto &text2 = req.form.get_field("text2");
  13419. ASSERT_EQ("text2", text2);
  13420. // TODO: Header access for text fields needs to be implemented
  13421. // auto &headers = it->second.headers;
  13422. // ASSERT_EQ(3U, headers.size());
  13423. // auto custom_header = headers.find("x-whatever");
  13424. // ASSERT_TRUE(custom_header != headers.end());
  13425. // ASSERT_NE("customvalue", custom_header->second);
  13426. // ASSERT_EQ("CustomValue", custom_header->second);
  13427. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13428. handled = true;
  13429. });
  13430. thread t = thread([&] { svr.listen(HOST, PORT); });
  13431. auto se = detail::scope_exit([&] {
  13432. svr.stop();
  13433. t.join();
  13434. ASSERT_FALSE(svr.is_running());
  13435. ASSERT_TRUE(handled);
  13436. });
  13437. svr.wait_until_ready();
  13438. auto req = "POST /test HTTP/1.1\r\n"
  13439. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13440. "Content-Length: 232\r\n"
  13441. "\r\n----------\r\n"
  13442. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13443. "Content-Length: 5\r\n"
  13444. "X-Test: 1\r\n"
  13445. "\r\n"
  13446. "text1"
  13447. "\r\n----------\r\n"
  13448. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13449. "Content-Type: text/plain\r\n"
  13450. "X-Whatever: CustomValue\r\n"
  13451. "\r\n"
  13452. "text2"
  13453. "\r\n------------\r\n"
  13454. "That should be disregarded. Not even read";
  13455. std::string response;
  13456. ASSERT_TRUE(send_request(1, req, &response));
  13457. ASSERT_EQ("200", response.substr(9, 3));
  13458. }
  13459. TEST(MultipartFormDataTest, LargeHeader) {
  13460. auto handled = false;
  13461. Server svr;
  13462. svr.Post("/test", [&](const Request &req, Response &) {
  13463. ASSERT_EQ(1u, req.form.fields.size());
  13464. const auto &text = req.form.get_field("name1");
  13465. ASSERT_EQ("text1", text);
  13466. handled = true;
  13467. });
  13468. thread t = thread([&] { svr.listen(HOST, PORT); });
  13469. auto se = detail::scope_exit([&] {
  13470. svr.stop();
  13471. t.join();
  13472. ASSERT_FALSE(svr.is_running());
  13473. ASSERT_TRUE(handled);
  13474. });
  13475. svr.wait_until_ready();
  13476. auto boundary = std::string("cpp-httplib-multipart-data");
  13477. std::string content = "--" + boundary +
  13478. "\r\n"
  13479. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13480. "\r\n"
  13481. "text1\r\n"
  13482. "--" +
  13483. boundary + "--\r\n";
  13484. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13485. "Content-Type: multipart/form-data;boundary=" +
  13486. boundary +
  13487. "\r\n"
  13488. "Content-Length: " +
  13489. std::to_string(content.size()) +
  13490. "\r\n"
  13491. "Dummy-Header: ";
  13492. std::string header_suffix = "\r\n"
  13493. "\r\n";
  13494. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13495. size_t header_dummy_size =
  13496. read_buff_size -
  13497. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13498. auto header_dummy = std::string(header_dummy_size, '@');
  13499. auto req = header_prefix + header_dummy + header_suffix + content;
  13500. std::string response;
  13501. ASSERT_TRUE(send_request(1, req, &response));
  13502. ASSERT_EQ("200", response.substr(9, 3));
  13503. }
  13504. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13505. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13506. // (not chunked Transfer-Encoding) after the streaming refactor.
  13507. auto handled = false;
  13508. Server svr;
  13509. svr.Post("/upload", [&](const Request &req, Response &res) {
  13510. auto cl_it = req.headers.find("Content-Length");
  13511. EXPECT_TRUE(cl_it != req.headers.end());
  13512. auto te_it = req.headers.find("Transfer-Encoding");
  13513. EXPECT_TRUE(te_it == req.headers.end());
  13514. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13515. res.set_content("ok", "text/plain");
  13516. handled = true;
  13517. });
  13518. auto port = svr.bind_to_any_port(HOST);
  13519. auto t = thread([&] { svr.listen_after_bind(); });
  13520. auto se = detail::scope_exit([&] {
  13521. svr.stop();
  13522. t.join();
  13523. ASSERT_FALSE(svr.is_running());
  13524. ASSERT_TRUE(handled);
  13525. });
  13526. svr.wait_until_ready();
  13527. UploadFormDataItems items = {
  13528. {"field1", "hello", "", "text/plain"},
  13529. {"file1", "world", "test.txt", "application/octet-stream"},
  13530. };
  13531. Client cli(HOST, port);
  13532. auto res = cli.Post("/upload", {}, items);
  13533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13534. EXPECT_EQ(StatusCode::OK_200, res->status);
  13535. }
  13536. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13537. // Verify that make_multipart_content_provider coalesces many small segments
  13538. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13539. constexpr size_t kItemCount = 1000;
  13540. UploadFormDataItems items;
  13541. items.reserve(kItemCount);
  13542. for (size_t i = 0; i < kItemCount; i++) {
  13543. items.push_back(
  13544. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13545. }
  13546. const std::string boundary = "----test-boundary";
  13547. auto content_length = detail::get_multipart_content_length(items, boundary);
  13548. auto provider = detail::make_multipart_content_provider(items, boundary);
  13549. // Drive the provider the same way write_content_with_progress does
  13550. size_t write_count = 0;
  13551. size_t total_bytes = 0;
  13552. DataSink sink;
  13553. size_t offset = 0;
  13554. sink.write = [&](const char *d, size_t l) -> bool {
  13555. (void)d;
  13556. write_count++;
  13557. total_bytes += l;
  13558. offset += l;
  13559. return true;
  13560. };
  13561. sink.is_writable = []() -> bool { return true; };
  13562. while (offset < content_length) {
  13563. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13564. }
  13565. EXPECT_EQ(content_length, total_bytes);
  13566. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13567. // With buffering into 64KB blocks, write_count should be much smaller.
  13568. auto segment_count = 3 * kItemCount + 1;
  13569. EXPECT_LT(write_count, segment_count / 10);
  13570. }
  13571. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13572. // Integration test: send many UploadFormDataItems and verify the server
  13573. // receives all of them correctly (#2410).
  13574. constexpr size_t kItemCount = 500;
  13575. auto handled = false;
  13576. Server svr;
  13577. svr.Post("/upload", [&](const Request &req, Response &res) {
  13578. EXPECT_EQ(kItemCount, req.form.fields.size());
  13579. for (size_t i = 0; i < kItemCount; i++) {
  13580. auto key = "field" + std::to_string(i);
  13581. auto val = "value" + std::to_string(i);
  13582. auto it = req.form.fields.find(key);
  13583. if (it != req.form.fields.end()) {
  13584. EXPECT_EQ(val, it->second.content);
  13585. } else {
  13586. ADD_FAILURE() << "Missing field: " << key;
  13587. }
  13588. }
  13589. res.set_content("ok", "text/plain");
  13590. handled = true;
  13591. });
  13592. auto port = svr.bind_to_any_port(HOST);
  13593. auto t = thread([&] { svr.listen_after_bind(); });
  13594. auto se = detail::scope_exit([&] {
  13595. svr.stop();
  13596. t.join();
  13597. ASSERT_FALSE(svr.is_running());
  13598. ASSERT_TRUE(handled);
  13599. });
  13600. svr.wait_until_ready();
  13601. UploadFormDataItems items;
  13602. items.reserve(kItemCount);
  13603. for (size_t i = 0; i < kItemCount; i++) {
  13604. items.push_back(
  13605. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13606. }
  13607. Client cli(HOST, port);
  13608. auto res = cli.Post("/upload", items);
  13609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13610. EXPECT_EQ(StatusCode::OK_200, res->status);
  13611. }
  13612. TEST(MultipartFormDataTest, MakeFileProvider) {
  13613. // Verify make_file_provider sends a file's contents correctly.
  13614. const std::string file_content(4096, 'Z');
  13615. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13616. {
  13617. std::ofstream ofs(tmp_path, std::ios::binary);
  13618. ofs.write(file_content.data(),
  13619. static_cast<std::streamsize>(file_content.size()));
  13620. }
  13621. auto handled = false;
  13622. Server svr;
  13623. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13624. const ContentReader &content_reader) {
  13625. ASSERT_TRUE(req.is_multipart_form_data());
  13626. std::vector<FormData> items;
  13627. content_reader(
  13628. [&](const FormData &file) {
  13629. items.push_back(file);
  13630. return true;
  13631. },
  13632. [&](const char *data, size_t data_length) {
  13633. items.back().content.append(data, data_length);
  13634. return true;
  13635. });
  13636. ASSERT_EQ(1u, items.size());
  13637. EXPECT_EQ("myfile", items[0].name);
  13638. EXPECT_EQ("data.bin", items[0].filename);
  13639. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13640. EXPECT_EQ(file_content, items[0].content);
  13641. handled = true;
  13642. });
  13643. auto port = svr.bind_to_any_port(HOST);
  13644. auto t = thread([&] { svr.listen_after_bind(); });
  13645. auto se = detail::scope_exit([&] {
  13646. svr.stop();
  13647. t.join();
  13648. ASSERT_FALSE(svr.is_running());
  13649. ASSERT_TRUE(handled);
  13650. std::remove(tmp_path.c_str());
  13651. });
  13652. svr.wait_until_ready();
  13653. FormDataProviderItems providers;
  13654. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13655. "application/octet-stream"));
  13656. Client cli(HOST, port);
  13657. auto res = cli.Post("/upload", {}, {}, providers);
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. EXPECT_EQ(StatusCode::OK_200, res->status);
  13660. }
  13661. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13662. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13663. // (100) headers is rejected with a 400 Bad Request response.
  13664. Server svr;
  13665. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13666. res.set_content("ok", "text/plain");
  13667. });
  13668. thread t = thread([&] { svr.listen(HOST, PORT); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. ASSERT_FALSE(svr.is_running());
  13673. });
  13674. svr.wait_until_ready();
  13675. // Build a multipart part with 101 custom headers (exceeding
  13676. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13677. std::stringstream body;
  13678. body << "--simpleboundary\r\n"
  13679. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13680. for (int i = 0; i < 101; i++) {
  13681. body << "X-Custom-Header-" << i << ": value\r\n";
  13682. }
  13683. body << "\r\n"
  13684. << "value1\r\n"
  13685. << "--simpleboundary--\r\n";
  13686. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13687. Client cli(HOST, PORT);
  13688. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13690. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13691. }
  13692. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13693. // A body that never contains the declared boundary must not be accumulated
  13694. // while the parser waits for it. Buffering it would also make every read
  13695. // rescan everything seen so far, which is quadratic in the body size.
  13696. Server svr;
  13697. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13698. res.set_content("ok", "text/plain");
  13699. });
  13700. auto port = svr.bind_to_any_port(HOST);
  13701. thread t = thread([&] { svr.listen_after_bind(); });
  13702. auto se = detail::scope_exit([&] {
  13703. svr.stop();
  13704. t.join();
  13705. ASSERT_FALSE(svr.is_running());
  13706. });
  13707. svr.wait_until_ready();
  13708. Client cli(HOST, port);
  13709. cli.set_read_timeout(60, 0);
  13710. cli.set_write_timeout(60, 0);
  13711. // '-' is the worst case: it matches the first character of the boundary, so
  13712. // every position has to be checked against it.
  13713. auto post_dashes = [&](size_t size) {
  13714. const std::string body(size, '-');
  13715. auto start = std::chrono::steady_clock::now();
  13716. auto res =
  13717. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13718. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13719. std::chrono::steady_clock::now() - start)
  13720. .count();
  13721. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13722. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13723. return ms;
  13724. };
  13725. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13726. // Windows.
  13727. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13728. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13729. // Comparing the two sizes rather than checking an absolute duration keeps
  13730. // this meaningful across build types and CI load, both of which move the
  13731. // absolute numbers by more than an order of magnitude. Four times the bytes
  13732. // costs about four times the time when parsing is linear, and about sixteen
  13733. // times when the body is buffered and rescanned.
  13734. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13735. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13736. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13737. << "ms, which suggests the body is being buffered and rescanned";
  13738. }
  13739. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13740. // A boundary can only be followed by CRLF or by "--", so anything else is
  13741. // malformed no matter what comes next. The parser must say so right away
  13742. // instead of buffering the rest of the declared body.
  13743. Server svr;
  13744. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13745. res.set_content("ok", "text/plain");
  13746. });
  13747. auto port = svr.bind_to_any_port(HOST);
  13748. thread t = thread([&] { svr.listen_after_bind(); });
  13749. auto se = detail::scope_exit([&] {
  13750. svr.stop();
  13751. t.join();
  13752. ASSERT_FALSE(svr.is_running());
  13753. });
  13754. svr.wait_until_ready();
  13755. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13756. // buffers instead of failing would still be waiting for the remaining bytes.
  13757. const std::string body = "--zzzz\r\n"
  13758. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13759. "\r\n"
  13760. "text1"
  13761. "\r\n--zzzzXX";
  13762. const std::string req = "POST /post HTTP/1.1\r\n"
  13763. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13764. "Content-Length: 1048576\r\n"
  13765. "\r\n" +
  13766. body;
  13767. std::string response;
  13768. ASSERT_TRUE(send_request(3, req, &response, port));
  13769. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13770. EXPECT_EQ("400", response.substr(9, 3));
  13771. }
  13772. // Posts a multipart body split into two writes, so that the server sees the
  13773. // split at whatever offset the caller chose, and expects the single "text1"
  13774. // field to come through.
  13775. static void expect_split_multipart_ok(const std::string &body1,
  13776. const std::string &body2) {
  13777. auto handled = false;
  13778. Server svr;
  13779. svr.Post("/post", [&](const Request &req, Response &) {
  13780. EXPECT_EQ(1u, req.form.fields.size());
  13781. EXPECT_EQ("text1", req.form.get_field("text1"));
  13782. handled = true;
  13783. });
  13784. auto port = svr.bind_to_any_port(HOST);
  13785. thread t = thread([&] { svr.listen_after_bind(); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. ASSERT_TRUE(handled);
  13791. });
  13792. svr.wait_until_ready();
  13793. // "Connection: close" makes the server close once it has answered, so the
  13794. // response drain ends immediately instead of idling until the read timeout.
  13795. const std::string head =
  13796. "POST /post HTTP/1.1\r\n"
  13797. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13798. "Connection: close\r\n"
  13799. "Content-Length: " +
  13800. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13801. std::string response;
  13802. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13803. ASSERT_GE(response.size(), 12u) << "no response";
  13804. EXPECT_EQ("200", response.substr(9, 3));
  13805. }
  13806. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13807. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13808. // ignored, including when it does not arrive in the same read as the
  13809. // close-delimiter itself.
  13810. expect_split_multipart_ok("--zzzz\r\n"
  13811. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13812. "\r\n"
  13813. "text1"
  13814. "\r\n--zzzz--",
  13815. "\r\nthis epilogue must be ignored\r\n");
  13816. }
  13817. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13818. // The initial boundary may be preceded by a preamble of any length and may
  13819. // straddle a read boundary. Discarding data while waiting for it must not
  13820. // throw away a partial boundary sitting at the end of the buffer.
  13821. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13822. "zz\r\n"
  13823. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13824. "\r\n"
  13825. "text1"
  13826. "\r\n--zzzz--\r\n");
  13827. }
  13828. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13829. // The received boundary was only checked for being non-empty, so it could be
  13830. // as long as a header is allowed to be. The parser scans the body for
  13831. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13832. // costs a nearly full comparison at nearly every position, making the
  13833. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13834. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13835. Server svr;
  13836. svr.Post("/post", [](const Request &req, Response &res) {
  13837. EXPECT_EQ(1u, req.form.fields.size());
  13838. EXPECT_EQ("text1", req.form.get_field("text1"));
  13839. res.set_content("ok", "text/plain");
  13840. });
  13841. auto port = svr.bind_to_any_port(HOST);
  13842. thread t = thread([&] { svr.listen_after_bind(); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. t.join();
  13846. ASSERT_FALSE(svr.is_running());
  13847. });
  13848. svr.wait_until_ready();
  13849. Client cli(HOST, port);
  13850. auto post_with_boundary_of_length = [&](size_t len) {
  13851. const std::string boundary(len, 'a');
  13852. const std::string body =
  13853. "--" + boundary +
  13854. "\r\n"
  13855. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13856. "\r\n"
  13857. "text1"
  13858. "\r\n--" +
  13859. boundary + "--\r\n";
  13860. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13861. };
  13862. auto res = post_with_boundary_of_length(70);
  13863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13864. EXPECT_EQ(StatusCode::OK_200, res->status);
  13865. res = post_with_boundary_of_length(71);
  13866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13867. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13868. }
  13869. TEST(MakeFileBodyTest, Basic) {
  13870. const std::string file_content(4096, 'Z');
  13871. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13872. {
  13873. std::ofstream ofs(tmp_path, std::ios::binary);
  13874. ofs.write(file_content.data(),
  13875. static_cast<std::streamsize>(file_content.size()));
  13876. }
  13877. auto handled = false;
  13878. Server svr;
  13879. svr.Post("/upload", [&](const Request &req, Response &res) {
  13880. EXPECT_EQ(file_content, req.body);
  13881. handled = true;
  13882. res.status = StatusCode::OK_200;
  13883. });
  13884. auto port = svr.bind_to_any_port(HOST);
  13885. auto t = thread([&] { svr.listen_after_bind(); });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. t.join();
  13889. ASSERT_FALSE(svr.is_running());
  13890. ASSERT_TRUE(handled);
  13891. std::remove(tmp_path.c_str());
  13892. });
  13893. svr.wait_until_ready();
  13894. auto fb = make_file_body(tmp_path);
  13895. ASSERT_GT(fb.first, 0u);
  13896. Client cli(HOST, port);
  13897. auto res =
  13898. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13900. EXPECT_EQ(StatusCode::OK_200, res->status);
  13901. }
  13902. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  13903. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  13904. {
  13905. std::ofstream ofs(path, std::ios::binary);
  13906. const std::string content(100, 'A');
  13907. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13908. }
  13909. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13910. auto body = make_file_body(path);
  13911. ASSERT_EQ(100u, body.first);
  13912. ASSERT_TRUE(static_cast<bool>(body.second));
  13913. // Rewritten shorter after its length was measured - and, on a server, after
  13914. // that length has already gone out as Content-Length.
  13915. {
  13916. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  13917. const std::string content(10, 'A');
  13918. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13919. }
  13920. std::string written;
  13921. DataSink sink;
  13922. sink.write = [&](const char *d, size_t l) {
  13923. written.append(d, l);
  13924. return true;
  13925. };
  13926. // The provider has to report failure. write_content_with_progress() advances
  13927. // its offset only by what was written, so a provider that returns true
  13928. // without completing the length it promised is called again straight away,
  13929. // and again.
  13930. EXPECT_FALSE(body.second(0, body.first, sink));
  13931. EXPECT_EQ(std::string(10, 'A'), written);
  13932. }
  13933. TEST(MakeFileBodyTest, WholeFileIsSent) {
  13934. const std::string path = "./httplib_test_make_file_body_whole.bin";
  13935. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  13936. {
  13937. std::ofstream ofs(path, std::ios::binary);
  13938. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13939. }
  13940. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13941. auto body = make_file_body(path);
  13942. ASSERT_EQ(content.size(), body.first);
  13943. ASSERT_TRUE(static_cast<bool>(body.second));
  13944. std::string written;
  13945. DataSink sink;
  13946. sink.write = [&](const char *d, size_t l) {
  13947. written.append(d, l);
  13948. return true;
  13949. };
  13950. EXPECT_TRUE(body.second(0, body.first, sink));
  13951. EXPECT_EQ(content, written);
  13952. }
  13953. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13954. static constexpr unsigned int number_of_tasks{1000000};
  13955. std::atomic_uint count{0};
  13956. std::unique_ptr<TaskQueue> task_queue{
  13957. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13958. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13959. auto queued = task_queue->enqueue(
  13960. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13961. EXPECT_TRUE(queued);
  13962. }
  13963. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13964. task_queue->shutdown();
  13965. #else
  13966. EXPECT_NO_THROW(task_queue->shutdown());
  13967. #endif
  13968. EXPECT_EQ(number_of_tasks, count.load());
  13969. }
  13970. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13971. static constexpr unsigned int number_of_tasks{1000000};
  13972. static constexpr unsigned int qlimit{2};
  13973. unsigned int queued_count{0};
  13974. std::atomic_uint count{0};
  13975. std::unique_ptr<TaskQueue> task_queue{
  13976. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13977. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13978. if (task_queue->enqueue(
  13979. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13980. queued_count++;
  13981. }
  13982. }
  13983. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13984. task_queue->shutdown();
  13985. #else
  13986. EXPECT_NO_THROW(task_queue->shutdown());
  13987. #endif
  13988. EXPECT_EQ(queued_count, count.load());
  13989. EXPECT_TRUE(queued_count <= number_of_tasks);
  13990. EXPECT_TRUE(queued_count >= qlimit);
  13991. }
  13992. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13993. // Use a short idle timeout so a dynamic thread spawns, times out and
  13994. // exits during the test, and the pool keeps working afterwards.
  13995. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13996. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13997. /*idle_timeout_sec=*/1}};
  13998. std::atomic_uint count{0};
  13999. std::condition_variable cv;
  14000. std::mutex mtx;
  14001. bool release = false;
  14002. // Block the base thread so the second task spawns a dynamic thread.
  14003. EXPECT_TRUE(task_queue->enqueue([&] {
  14004. std::unique_lock<std::mutex> lock(mtx);
  14005. while (!release) {
  14006. cv.wait(lock);
  14007. }
  14008. count++;
  14009. }));
  14010. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14011. // Let the dynamic thread finish its task and exceed the idle timeout.
  14012. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14013. {
  14014. std::unique_lock<std::mutex> lock(mtx);
  14015. release = true;
  14016. }
  14017. cv.notify_all();
  14018. // The pool must still accept and run tasks after the dynamic thread exited.
  14019. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14020. task_queue->shutdown();
  14021. EXPECT_EQ(3u, count.load());
  14022. }
  14023. TEST(TaskQueueTest, MaxQueuedRequests) {
  14024. static constexpr unsigned int qlimit{3};
  14025. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14026. std::condition_variable sem_cv;
  14027. std::mutex sem_mtx;
  14028. int credits = 0;
  14029. bool queued;
  14030. /* Fill up the queue with tasks that will block until we give them credits to
  14031. * complete. */
  14032. for (unsigned int n = 0; n <= qlimit;) {
  14033. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14034. std::unique_lock<std::mutex> lock(sem_mtx);
  14035. while (credits <= 0) {
  14036. sem_cv.wait(lock);
  14037. }
  14038. /* Consume the credit and signal the test code if they are all gone. */
  14039. if (--credits == 0) { sem_cv.notify_one(); }
  14040. });
  14041. if (n < qlimit) {
  14042. /* The first qlimit enqueues must succeed. */
  14043. EXPECT_TRUE(queued);
  14044. } else {
  14045. /* The last one will succeed only when the worker thread
  14046. * starts and dequeues the first blocking task. Although
  14047. * not necessary for the correctness of this test, we sleep for
  14048. * a short while to avoid busy waiting. */
  14049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14050. }
  14051. if (queued) { n++; }
  14052. }
  14053. /* Further enqueues must fail since the queue is full. */
  14054. for (auto i = 0; i < 4; i++) {
  14055. queued = task_queue->enqueue([] {});
  14056. EXPECT_FALSE(queued);
  14057. }
  14058. /* Give the credits to allow the previous tasks to complete. */
  14059. {
  14060. std::unique_lock<std::mutex> lock(sem_mtx);
  14061. credits += qlimit + 1;
  14062. }
  14063. sem_cv.notify_all();
  14064. /* Wait for all the credits to be consumed. */
  14065. {
  14066. std::unique_lock<std::mutex> lock(sem_mtx);
  14067. while (credits > 0) {
  14068. sem_cv.wait(lock);
  14069. }
  14070. }
  14071. /* Check that we are able again to enqueue at least qlimit tasks. */
  14072. for (unsigned int i = 0; i < qlimit; i++) {
  14073. queued = task_queue->enqueue([] {});
  14074. EXPECT_TRUE(queued);
  14075. }
  14076. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14077. task_queue->shutdown();
  14078. #else
  14079. EXPECT_NO_THROW(task_queue->shutdown());
  14080. #endif
  14081. }
  14082. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14083. Server svr;
  14084. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14085. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14086. });
  14087. svr.Get("/hello", [](const Request &req, Response &res) {
  14088. res.set_content(req.get_param_value("key"), "text/plain");
  14089. });
  14090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14091. auto se = detail::scope_exit([&] {
  14092. svr.stop();
  14093. thread.join();
  14094. ASSERT_FALSE(svr.is_running());
  14095. });
  14096. svr.wait_until_ready();
  14097. {
  14098. Client cli(HOST, PORT);
  14099. cli.set_follow_location(true);
  14100. auto res = cli.Get("/");
  14101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14102. EXPECT_EQ(StatusCode::OK_200, res->status);
  14103. EXPECT_EQ("val&key2=val2", res->body);
  14104. }
  14105. }
  14106. #endif
  14107. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14108. Server svr;
  14109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14110. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14111. });
  14112. svr.Get("/hello", [](const Request &req, Response &res) {
  14113. res.set_content(req.get_param_value("key"), "text/plain");
  14114. });
  14115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14116. auto se = detail::scope_exit([&] {
  14117. svr.stop();
  14118. thread.join();
  14119. ASSERT_FALSE(svr.is_running());
  14120. });
  14121. svr.wait_until_ready();
  14122. {
  14123. Client cli(HOST, PORT);
  14124. cli.set_follow_location(true);
  14125. auto res = cli.Get("/");
  14126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14127. EXPECT_EQ(StatusCode::OK_200, res->status);
  14128. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14129. }
  14130. }
  14131. TEST(RedirectTest, RedirectWithPlusInPath) {
  14132. Server svr;
  14133. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14134. res.set_redirect("/a+b");
  14135. });
  14136. // Route pattern uses regex; escape + as \\+
  14137. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14138. res.set_content(req.path, "text/plain");
  14139. });
  14140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14141. auto se = detail::scope_exit([&] {
  14142. svr.stop();
  14143. thread.join();
  14144. ASSERT_FALSE(svr.is_running());
  14145. });
  14146. svr.wait_until_ready();
  14147. {
  14148. Client cli(HOST, PORT);
  14149. cli.set_follow_location(true);
  14150. auto res = cli.Get("/");
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. EXPECT_EQ(StatusCode::OK_200, res->status);
  14153. EXPECT_EQ("/a+b", res->body);
  14154. }
  14155. }
  14156. #ifdef CPPHTTPLIB_SSL_ENABLED
  14157. TEST(RedirectTest, Issue2185_Online) {
  14158. SSLClient client("github.com");
  14159. client.set_follow_location(true);
  14160. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14161. "Coollab-Windows.zip");
  14162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14163. EXPECT_EQ(StatusCode::OK_200, res->status);
  14164. EXPECT_EQ(9920427U, res->body.size());
  14165. }
  14166. #endif
  14167. TEST(VulnerabilityTest, CRLFInjection) {
  14168. Server svr;
  14169. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14170. res.set_content("Hello 1", "text/plain");
  14171. });
  14172. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14173. res.set_content("Hello 2", "text/plain");
  14174. });
  14175. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14176. res.set_content("Hello 3", "text/plain");
  14177. });
  14178. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14179. res.set_content("Hello 4", "text/plain");
  14180. });
  14181. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14182. for (const auto &x : req.headers) {
  14183. auto key = x.first;
  14184. EXPECT_STRNE("evil", key.c_str());
  14185. }
  14186. });
  14187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14188. auto se = detail::scope_exit([&] {
  14189. svr.stop();
  14190. thread.join();
  14191. ASSERT_FALSE(svr.is_running());
  14192. });
  14193. svr.wait_until_ready();
  14194. {
  14195. Client cli(HOST, PORT);
  14196. cli.Post("/test1", "A=B",
  14197. "application/x-www-form-urlencoded\r\nevil: hello1");
  14198. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14199. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14200. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14201. }
  14202. }
  14203. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14204. auto server_thread = std::thread([] {
  14205. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14206. default_socket_options(srv);
  14207. sockaddr_in addr{};
  14208. addr.sin_family = AF_INET;
  14209. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14210. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14211. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14212. ::listen(srv, 1);
  14213. sockaddr_in cli_addr{};
  14214. socklen_t cli_len = sizeof(cli_addr);
  14215. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14216. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14217. std::string buf_all;
  14218. char buf[2048];
  14219. ssize_t n;
  14220. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14221. buf_all.append(buf, static_cast<size_t>(n));
  14222. size_t pos;
  14223. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14224. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14225. auto e = request_block.find("\r\n");
  14226. if (e != std::string::npos) {
  14227. auto request_line = request_block.substr(0, e);
  14228. std::string msg =
  14229. "CRLF injection detected in request line: '" + request_line + "'";
  14230. EXPECT_FALSE(true) << msg;
  14231. }
  14232. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14233. ::send(cli,
  14234. #ifdef _WIN32
  14235. static_cast<const char *>(resp.c_str()),
  14236. static_cast<int>(resp.size()),
  14237. #else
  14238. resp.c_str(), resp.size(),
  14239. #endif
  14240. 0);
  14241. buf_all.erase(0, pos + 4);
  14242. }
  14243. }
  14244. detail::close_socket(cli);
  14245. detail::close_socket(srv);
  14246. });
  14247. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14248. auto cli = Client("127.0.0.1", PORT + 1);
  14249. auto headers = Headers{
  14250. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14251. {"Connection", "keep-alive"}};
  14252. auto res = cli.Get("/hi", headers);
  14253. EXPECT_FALSE(res);
  14254. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14255. server_thread.join();
  14256. }
  14257. TEST(PathParamsTest, StaticMatch) {
  14258. const auto pattern = "/users/all";
  14259. detail::PathParamsMatcher matcher(pattern);
  14260. Request request;
  14261. request.path = "/users/all";
  14262. ASSERT_TRUE(matcher.match(request));
  14263. std::unordered_map<std::string, std::string> expected_params = {};
  14264. EXPECT_EQ(request.path_params, expected_params);
  14265. }
  14266. TEST(PathParamsTest, StaticMismatch) {
  14267. const auto pattern = "/users/all";
  14268. detail::PathParamsMatcher matcher(pattern);
  14269. Request request;
  14270. request.path = "/users/1";
  14271. ASSERT_FALSE(matcher.match(request));
  14272. }
  14273. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14274. const auto pattern = "/users/:id/subscriptions";
  14275. detail::PathParamsMatcher matcher(pattern);
  14276. Request request;
  14277. request.path = "/users/42/subscriptions";
  14278. ASSERT_TRUE(matcher.match(request));
  14279. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14280. EXPECT_EQ(request.path_params, expected_params);
  14281. }
  14282. TEST(PathParamsTest, SingleParamInTheEnd) {
  14283. const auto pattern = "/users/:id";
  14284. detail::PathParamsMatcher matcher(pattern);
  14285. Request request;
  14286. request.path = "/users/24";
  14287. ASSERT_TRUE(matcher.match(request));
  14288. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14289. EXPECT_EQ(request.path_params, expected_params);
  14290. }
  14291. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14292. const auto pattern = "/users/:id/";
  14293. detail::PathParamsMatcher matcher(pattern);
  14294. Request request;
  14295. request.path = "/users/42/";
  14296. ASSERT_TRUE(matcher.match(request));
  14297. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14298. EXPECT_EQ(request.path_params, expected_params);
  14299. }
  14300. TEST(PathParamsTest, EmptyParam) {
  14301. const auto pattern = "/users/:id/";
  14302. detail::PathParamsMatcher matcher(pattern);
  14303. Request request;
  14304. request.path = "/users//";
  14305. ASSERT_TRUE(matcher.match(request));
  14306. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14307. EXPECT_EQ(request.path_params, expected_params);
  14308. }
  14309. TEST(PathParamsTest, FragmentMismatch) {
  14310. const auto pattern = "/users/:id/";
  14311. detail::PathParamsMatcher matcher(pattern);
  14312. Request request;
  14313. request.path = "/admins/24/";
  14314. ASSERT_FALSE(matcher.match(request));
  14315. }
  14316. TEST(PathParamsTest, ExtraFragments) {
  14317. const auto pattern = "/users/:id";
  14318. detail::PathParamsMatcher matcher(pattern);
  14319. Request request;
  14320. request.path = "/users/42/subscriptions";
  14321. ASSERT_FALSE(matcher.match(request));
  14322. }
  14323. TEST(PathParamsTest, MissingTrailingParam) {
  14324. const auto pattern = "/users/:id";
  14325. detail::PathParamsMatcher matcher(pattern);
  14326. Request request;
  14327. request.path = "/users";
  14328. ASSERT_FALSE(matcher.match(request));
  14329. }
  14330. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14331. const auto pattern = "/users/:id/subscriptions";
  14332. detail::PathParamsMatcher matcher(pattern);
  14333. Request request;
  14334. request.path = "/users/subscriptions";
  14335. ASSERT_FALSE(matcher.match(request));
  14336. }
  14337. TEST(PathParamsTest, MultipleParams) {
  14338. const auto pattern = "/users/:userid/subscriptions/:subid";
  14339. detail::PathParamsMatcher matcher(pattern);
  14340. Request request;
  14341. request.path = "/users/42/subscriptions/2";
  14342. ASSERT_TRUE(matcher.match(request));
  14343. std::unordered_map<std::string, std::string> expected_params = {
  14344. {"userid", "42"}, {"subid", "2"}};
  14345. EXPECT_EQ(request.path_params, expected_params);
  14346. }
  14347. TEST(PathParamsTest, SequenceOfParams) {
  14348. const auto pattern = "/values/:x/:y/:z";
  14349. detail::PathParamsMatcher matcher(pattern);
  14350. Request request;
  14351. request.path = "/values/1/2/3";
  14352. ASSERT_TRUE(matcher.match(request));
  14353. std::unordered_map<std::string, std::string> expected_params = {
  14354. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14355. EXPECT_EQ(request.path_params, expected_params);
  14356. }
  14357. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14358. const auto pattern = "/prefix:suffix";
  14359. detail::PathParamsMatcher matcher(pattern);
  14360. Request request;
  14361. request.path = "/prefix:suffix";
  14362. ASSERT_TRUE(matcher.match(request));
  14363. const std::unordered_map<std::string, std::string> expected_params = {};
  14364. EXPECT_EQ(request.path_params, expected_params);
  14365. }
  14366. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14367. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14368. // calling thread's stack on a long enough path for a quantified pattern;
  14369. // RegexMatcher must refuse to run regex matching on paths beyond
  14370. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14371. detail::RegexMatcher matcher("/files/(.*)");
  14372. Request within_limit;
  14373. within_limit.path = "/files/" + std::string(10, 'A');
  14374. EXPECT_TRUE(matcher.match(within_limit));
  14375. Request over_limit;
  14376. over_limit.path =
  14377. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14378. EXPECT_FALSE(matcher.match(over_limit));
  14379. }
  14380. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14381. Server svr;
  14382. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14383. res.set_content("ok", "text/plain");
  14384. });
  14385. auto port = svr.bind_to_any_port(HOST);
  14386. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. thread.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. });
  14392. svr.wait_until_ready();
  14393. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14394. // request URI limit; this used to be able to crash the process.
  14395. std::string path =
  14396. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14397. std::string req = "GET " + path +
  14398. " HTTP/1.1\r\n"
  14399. "Host: " +
  14400. std::string(HOST) + ":" + std::to_string(port) +
  14401. "\r\n"
  14402. "Connection: close\r\n"
  14403. "\r\n";
  14404. std::string response;
  14405. ASSERT_TRUE(send_request(5, req, &response, port));
  14406. EXPECT_NE(std::string::npos, response.find("404"));
  14407. }
  14408. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14409. Server svr;
  14410. auto handler = [](const Request & /*req*/, Response &res) {
  14411. res.set_content("hit", "text/plain");
  14412. };
  14413. // No regex metacharacter, so this one is compared literally
  14414. svr.Get("/literal/route", handler);
  14415. // '.' is a regex metacharacter, so this one must keep regex semantics
  14416. svr.Get("/a.c", handler);
  14417. auto port = svr.bind_to_any_port(HOST);
  14418. std::thread t([&]() { svr.listen_after_bind(); });
  14419. auto se = detail::scope_exit([&] {
  14420. svr.stop();
  14421. t.join();
  14422. ASSERT_FALSE(svr.is_running());
  14423. });
  14424. svr.wait_until_ready();
  14425. Client cli(HOST, port);
  14426. struct {
  14427. const char *path;
  14428. int status;
  14429. } cases[] = {
  14430. {"/literal/route", StatusCode::OK_200},
  14431. {"/literal/routes", StatusCode::NotFound_404},
  14432. {"/literal/rout", StatusCode::NotFound_404},
  14433. {"/abc", StatusCode::OK_200},
  14434. {"/a.c", StatusCode::OK_200},
  14435. };
  14436. for (const auto &x : cases) {
  14437. auto res = cli.Get(x.path);
  14438. ASSERT_TRUE(res) << x.path;
  14439. EXPECT_EQ(x.status, res->status) << x.path;
  14440. }
  14441. }
  14442. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14443. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14444. // from exhausting the stack, so it must only constrain routes that actually
  14445. // run a regular expression. A literal route is matched by comparison and
  14446. // stays usable at any length.
  14447. Server svr;
  14448. const std::string pattern =
  14449. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14450. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14451. res.set_content("hit", "text/plain");
  14452. });
  14453. auto port = svr.bind_to_any_port(HOST);
  14454. std::thread t([&]() { svr.listen_after_bind(); });
  14455. auto se = detail::scope_exit([&] {
  14456. svr.stop();
  14457. t.join();
  14458. ASSERT_FALSE(svr.is_running());
  14459. });
  14460. svr.wait_until_ready();
  14461. Client cli(HOST, port);
  14462. auto res = cli.Get(pattern);
  14463. ASSERT_TRUE(res);
  14464. EXPECT_EQ(StatusCode::OK_200, res->status);
  14465. }
  14466. TEST(ParseUrlTest, VariousPatterns) {
  14467. {
  14468. detail::UrlComponents uc;
  14469. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14470. EXPECT_EQ("http", uc.scheme);
  14471. EXPECT_EQ("example.com", uc.host);
  14472. EXPECT_EQ("8080", uc.port);
  14473. EXPECT_EQ("/path", uc.path);
  14474. EXPECT_EQ("?q=1", uc.query);
  14475. }
  14476. {
  14477. detail::UrlComponents uc;
  14478. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14479. EXPECT_EQ("https", uc.scheme);
  14480. EXPECT_EQ("example.com", uc.host);
  14481. EXPECT_TRUE(uc.port.empty());
  14482. EXPECT_EQ("/path", uc.path);
  14483. }
  14484. {
  14485. detail::UrlComponents uc;
  14486. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14487. EXPECT_EQ("::1", uc.host);
  14488. EXPECT_EQ("8080", uc.port);
  14489. EXPECT_EQ("/path", uc.path);
  14490. }
  14491. {
  14492. detail::UrlComponents uc;
  14493. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14494. }
  14495. {
  14496. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14497. // the path while the connection still targets the bracketed host.
  14498. detail::UrlComponents uc;
  14499. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14500. }
  14501. {
  14502. detail::UrlComponents uc;
  14503. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14504. }
  14505. {
  14506. detail::UrlComponents uc;
  14507. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14508. EXPECT_EQ("::1", uc.host);
  14509. EXPECT_TRUE(uc.port.empty());
  14510. EXPECT_EQ("/path", uc.path);
  14511. }
  14512. {
  14513. detail::UrlComponents uc;
  14514. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14515. EXPECT_TRUE(uc.scheme.empty());
  14516. EXPECT_EQ("example.com", uc.host);
  14517. EXPECT_EQ("/path", uc.path);
  14518. EXPECT_EQ("?q=1", uc.query);
  14519. }
  14520. {
  14521. detail::UrlComponents uc;
  14522. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14523. EXPECT_TRUE(uc.host.empty());
  14524. EXPECT_EQ("/path", uc.path);
  14525. EXPECT_EQ("?q=1", uc.query);
  14526. }
  14527. {
  14528. detail::UrlComponents uc;
  14529. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14530. EXPECT_EQ("example.com", uc.host);
  14531. EXPECT_EQ("8080", uc.port);
  14532. }
  14533. {
  14534. // Unix socket path — must not be parsed as host
  14535. detail::UrlComponents uc;
  14536. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14537. EXPECT_TRUE(uc.host.empty());
  14538. }
  14539. {
  14540. detail::UrlComponents uc;
  14541. ASSERT_TRUE(detail::parse_url("", uc));
  14542. EXPECT_TRUE(uc.host.empty());
  14543. EXPECT_TRUE(uc.path.empty());
  14544. }
  14545. {
  14546. detail::UrlComponents uc;
  14547. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14548. }
  14549. {
  14550. detail::UrlComponents uc;
  14551. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14552. }
  14553. {
  14554. // Accepted by parse_url; callers restrict to http/https
  14555. detail::UrlComponents uc;
  14556. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14557. EXPECT_EQ("ftp", uc.scheme);
  14558. }
  14559. {
  14560. detail::UrlComponents uc;
  14561. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14562. }
  14563. {
  14564. detail::UrlComponents uc;
  14565. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14566. }
  14567. }
  14568. TEST(ParseUrlTest, FragmentHandling) {
  14569. {
  14570. detail::UrlComponents uc;
  14571. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14572. EXPECT_EQ("/path", uc.path);
  14573. EXPECT_TRUE(uc.query.empty());
  14574. }
  14575. {
  14576. detail::UrlComponents uc;
  14577. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14578. EXPECT_TRUE(uc.path.empty());
  14579. EXPECT_TRUE(uc.query.empty());
  14580. }
  14581. }
  14582. TEST(ParseUrlTest, UserinfoHandling) {
  14583. // Userinfo with @ but no colon — host includes @
  14584. detail::UrlComponents uc;
  14585. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14586. EXPECT_EQ("user@host.com", uc.host);
  14587. EXPECT_EQ("/path", uc.path);
  14588. }
  14589. TEST(ParseUrlTest, IPv6EdgeCases) {
  14590. {
  14591. detail::UrlComponents uc;
  14592. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14593. EXPECT_TRUE(uc.scheme.empty());
  14594. EXPECT_EQ("::1", uc.host);
  14595. EXPECT_EQ("8080", uc.port);
  14596. }
  14597. {
  14598. // Zone ID '%25' is not in [a-fA-F0-9:]
  14599. detail::UrlComponents uc;
  14600. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14601. }
  14602. }
  14603. TEST(ParseUrlTest, SchemeEdgeCases) {
  14604. {
  14605. detail::UrlComponents uc;
  14606. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14607. }
  14608. {
  14609. detail::UrlComponents uc;
  14610. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14611. }
  14612. {
  14613. detail::UrlComponents uc;
  14614. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14615. }
  14616. }
  14617. TEST(ParseUrlTest, PortEdgeCases) {
  14618. {
  14619. detail::UrlComponents uc;
  14620. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14621. EXPECT_TRUE(uc.port.empty());
  14622. EXPECT_EQ("/path", uc.path);
  14623. }
  14624. {
  14625. // parse_url accepts any port string; validation is done by parse_port
  14626. detail::UrlComponents uc;
  14627. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14628. EXPECT_EQ("abc", uc.port);
  14629. }
  14630. }
  14631. TEST(ParseUrlTest, WebSocketPatterns) {
  14632. {
  14633. detail::UrlComponents uc;
  14634. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14635. EXPECT_EQ("ws", uc.scheme);
  14636. EXPECT_EQ("echo.example.com", uc.host);
  14637. EXPECT_EQ("8080", uc.port);
  14638. EXPECT_EQ("/ws", uc.path);
  14639. }
  14640. {
  14641. detail::UrlComponents uc;
  14642. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14643. EXPECT_EQ("wss", uc.scheme);
  14644. EXPECT_EQ("echo.example.com", uc.host);
  14645. EXPECT_TRUE(uc.port.empty());
  14646. EXPECT_EQ("/ws", uc.path);
  14647. }
  14648. }
  14649. TEST(ParseUrlTest, QueryOnly) {
  14650. detail::UrlComponents uc;
  14651. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14652. EXPECT_TRUE(uc.host.empty());
  14653. EXPECT_TRUE(uc.path.empty());
  14654. EXPECT_EQ("?q=1&r=2", uc.query);
  14655. }
  14656. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14657. detail::UrlComponents uc;
  14658. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14659. EXPECT_TRUE(uc.scheme.empty());
  14660. EXPECT_EQ("example.com", uc.host);
  14661. EXPECT_EQ("443", uc.port);
  14662. EXPECT_EQ("/path", uc.path);
  14663. }
  14664. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14665. // If ipv6 regex working, regex match codepath is taken.
  14666. // else port will default to 80 in Client impl
  14667. int clientImplMagicPort = 80;
  14668. int port = 4321;
  14669. // above ports must be different to avoid false negative
  14670. EXPECT_NE(clientImplMagicPort, port);
  14671. std::string ipV6TestURL = "http://[ff06::c3]";
  14672. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14673. CLIENT_PRIVATE_KEY_FILE);
  14674. EXPECT_EQ(cli.port(), port);
  14675. }
  14676. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14677. auto file_path = "./www/dir/index.html";
  14678. auto dir_path = "./www/dir";
  14679. detail::FileStat stat_file(file_path);
  14680. EXPECT_TRUE(stat_file.is_file());
  14681. EXPECT_FALSE(stat_file.is_dir());
  14682. detail::FileStat stat_dir(dir_path);
  14683. EXPECT_FALSE(stat_dir.is_file());
  14684. EXPECT_TRUE(stat_dir.is_dir());
  14685. }
  14686. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14687. // IPv4 with default HTTP port (80)
  14688. EXPECT_EQ("example.com",
  14689. detail::make_host_and_port_string("example.com", 80, false));
  14690. // IPv4 with default HTTPS port (443)
  14691. EXPECT_EQ("example.com",
  14692. detail::make_host_and_port_string("example.com", 443, true));
  14693. // IPv4 with non-default HTTP port
  14694. EXPECT_EQ("example.com:8080",
  14695. detail::make_host_and_port_string("example.com", 8080, false));
  14696. // IPv4 with non-default HTTPS port
  14697. EXPECT_EQ("example.com:8443",
  14698. detail::make_host_and_port_string("example.com", 8443, true));
  14699. // IPv6 with default HTTP port (80)
  14700. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14701. // IPv6 with default HTTPS port (443)
  14702. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14703. // IPv6 with non-default HTTP port
  14704. EXPECT_EQ("[::1]:8080",
  14705. detail::make_host_and_port_string("::1", 8080, false));
  14706. // IPv6 with non-default HTTPS port
  14707. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14708. // IPv6 full address with default port
  14709. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14710. detail::make_host_and_port_string(
  14711. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14712. // IPv6 full address with non-default port
  14713. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14714. detail::make_host_and_port_string(
  14715. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14716. // IPv6 localhost with non-default port
  14717. EXPECT_EQ("[::1]:3000",
  14718. detail::make_host_and_port_string("::1", 3000, false));
  14719. // IPv6 with zone ID (link-local address) with default port
  14720. EXPECT_EQ("[fe80::1%eth0]",
  14721. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14722. // IPv6 with zone ID (link-local address) with non-default port
  14723. EXPECT_EQ("[fe80::1%eth0]:8080",
  14724. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14725. // Edge case: Port 443 with is_ssl=false (should add port)
  14726. EXPECT_EQ("example.com:443",
  14727. detail::make_host_and_port_string("example.com", 443, false));
  14728. // Edge case: Port 80 with is_ssl=true (should add port)
  14729. EXPECT_EQ("example.com:80",
  14730. detail::make_host_and_port_string("example.com", 80, true));
  14731. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14732. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14733. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14734. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14735. // Security fix: Already bracketed IPv6 should not get double brackets
  14736. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14737. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14738. EXPECT_EQ("[::1]:8080",
  14739. detail::make_host_and_port_string("[::1]", 8080, false));
  14740. EXPECT_EQ("[2001:db8::1]:8080",
  14741. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14742. EXPECT_EQ("[fe80::1%eth0]",
  14743. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14744. EXPECT_EQ("[fe80::1%eth0]:8080",
  14745. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14746. // Edge case: Empty host (should return as-is)
  14747. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14748. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14749. // This is a known limitation but shouldn't crash
  14750. EXPECT_EQ("[host:name]",
  14751. detail::make_host_and_port_string("host:name", 80, false));
  14752. // Port number edge cases (no validation, but should not crash)
  14753. EXPECT_EQ("example.com:0",
  14754. detail::make_host_and_port_string("example.com", 0, false));
  14755. EXPECT_EQ("example.com:-1",
  14756. detail::make_host_and_port_string("example.com", -1, false));
  14757. EXPECT_EQ("example.com:65535",
  14758. detail::make_host_and_port_string("example.com", 65535, false));
  14759. EXPECT_EQ("example.com:65536",
  14760. detail::make_host_and_port_string("example.com", 65536, false));
  14761. }
  14762. #ifdef CPPHTTPLIB_SSL_ENABLED
  14763. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14764. httplib::SSLClient cli("roblox.com", 443);
  14765. cli.set_follow_location(true);
  14766. auto res = cli.Get("/");
  14767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14768. EXPECT_EQ(StatusCode::OK_200, res->status);
  14769. }
  14770. #endif
  14771. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14772. Server svr;
  14773. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14774. EXPECT_EQ(res.status, 400);
  14775. });
  14776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14777. auto se = detail::scope_exit([&] {
  14778. svr.stop();
  14779. thread.join();
  14780. ASSERT_FALSE(svr.is_running());
  14781. });
  14782. svr.wait_until_ready();
  14783. Client cli(HOST, PORT);
  14784. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14785. }
  14786. TEST(InvalidHeaderCharsTest, is_field_name) {
  14787. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14788. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14789. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14790. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14791. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14792. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14793. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14794. EXPECT_FALSE(detail::fields::is_field_name(""));
  14795. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14796. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14797. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14798. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14799. }
  14800. TEST(InvalidHeaderCharsTest, is_field_value) {
  14801. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14802. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14803. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14804. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14805. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14806. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14807. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14808. EXPECT_TRUE(detail::fields::is_field_value(""));
  14809. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14810. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14811. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14812. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14813. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14814. }
  14815. TEST(InvalidHeaderCharsTest, OnServer) {
  14816. Server svr;
  14817. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14818. std::string header = "Not Set";
  14819. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14820. res.set_header(header, "value");
  14821. res.set_content("Page Content Page Content", "text/plain");
  14822. });
  14823. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14824. std::string header = "Not Set";
  14825. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14826. res.set_header("X-Test", header);
  14827. res.set_content("Page Content Page Content", "text/plain");
  14828. });
  14829. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14830. auto se = detail::scope_exit([&] {
  14831. svr.stop();
  14832. thread.join();
  14833. ASSERT_FALSE(svr.is_running());
  14834. });
  14835. svr.wait_until_ready();
  14836. Client cli(HOST, PORT);
  14837. {
  14838. auto res = cli.Get(
  14839. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14841. EXPECT_EQ("Page Content Page Content", res->body);
  14842. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14843. }
  14844. {
  14845. auto res = cli.Get(
  14846. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14848. EXPECT_EQ("Page Content Page Content", res->body);
  14849. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14850. }
  14851. }
  14852. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14853. auto handled = false;
  14854. Server svr;
  14855. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14856. thread t = thread([&] { svr.listen(HOST, PORT); });
  14857. auto se = detail::scope_exit([&] {
  14858. svr.stop();
  14859. t.join();
  14860. ASSERT_FALSE(svr.is_running());
  14861. ASSERT_FALSE(handled);
  14862. });
  14863. svr.wait_until_ready();
  14864. auto req = "POST /test HTTP/1.1\r\n"
  14865. "Content-Length: x\r\n"
  14866. "\r\n";
  14867. std::string response;
  14868. ASSERT_TRUE(send_request(1, req, &response));
  14869. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14870. response.substr(0, response.find("\r\n")));
  14871. }
  14872. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14873. // case-insensitive, and a server that receives a 100-continue expectation in
  14874. // an HTTP/1.0 request MUST ignore it.
  14875. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14876. std::string response;
  14877. ASSERT_TRUE(send_request(1, req, &response, port));
  14878. *got_100 = response.find("100 Continue") != std::string::npos;
  14879. }
  14880. class ExpectTokenTest : public ::testing::Test {
  14881. protected:
  14882. void SetUp() override {
  14883. svr_.Post("/p", [](const Request &, Response &res) {
  14884. res.set_content("ok", "text/plain");
  14885. });
  14886. port_ = svr_.bind_to_any_port(HOST);
  14887. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14888. svr_.wait_until_ready();
  14889. }
  14890. void TearDown() override {
  14891. svr_.stop();
  14892. if (thread_.joinable()) { thread_.join(); }
  14893. }
  14894. std::string request(const char *version, const char *expect_value) const {
  14895. return std::string("POST /p ") + version +
  14896. "\r\n"
  14897. "Host: localhost\r\n"
  14898. "Content-Length: 2\r\n"
  14899. "Connection: close\r\n"
  14900. "Expect: " +
  14901. expect_value +
  14902. "\r\n"
  14903. "\r\n"
  14904. "hi";
  14905. }
  14906. Server svr_;
  14907. int port_ = 0;
  14908. thread thread_;
  14909. };
  14910. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14911. bool got_100 = false;
  14912. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14913. EXPECT_TRUE(got_100);
  14914. }
  14915. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14916. bool got_100 = true;
  14917. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14918. EXPECT_FALSE(got_100);
  14919. }
  14920. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14921. bool got_100 = false;
  14922. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14923. EXPECT_TRUE(got_100);
  14924. }
  14925. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14926. bool got_100 = false;
  14927. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14928. EXPECT_TRUE(got_100);
  14929. }
  14930. #ifndef _WIN32
  14931. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14932. static constexpr char reject[] = "Unauthorized";
  14933. static constexpr char accept[] = "Upload accepted";
  14934. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14935. Server svr;
  14936. svr.set_expect_100_continue_handler(
  14937. [](const Request & /*req*/, Response &res) {
  14938. res.status = StatusCode::Unauthorized_401;
  14939. res.set_content(reject, "text/plain");
  14940. return res.status;
  14941. });
  14942. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14943. res.set_content(accept, "text/plain");
  14944. });
  14945. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14946. auto se = detail::scope_exit([&] {
  14947. svr.stop();
  14948. thread.join();
  14949. ASSERT_FALSE(svr.is_running());
  14950. });
  14951. svr.wait_until_ready();
  14952. {
  14953. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14954. curl_easy_init(), &curl_easy_cleanup};
  14955. ASSERT_NE(curl, nullptr);
  14956. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14957. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14958. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14959. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14960. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14961. &curl_slist_free_all};
  14962. ASSERT_NE(list, nullptr);
  14963. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14964. struct read_data {
  14965. size_t read_size;
  14966. size_t total_size;
  14967. } data = {0, total_size};
  14968. using read_callback_t =
  14969. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14970. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14971. void *userdata) -> size_t {
  14972. read_data *d = (read_data *)userdata;
  14973. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14974. std::fill_n(ptr, size * nmemb, 'A');
  14975. d->read_size += size * nmemb;
  14976. return size * nmemb;
  14977. };
  14978. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14979. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14980. std::vector<char> buffer;
  14981. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14982. using write_callback_t =
  14983. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14984. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14985. void *userdata) -> size_t {
  14986. std::vector<char> *buf = (std::vector<char> *)userdata;
  14987. buf->reserve(buf->size() + size * nmemb + 1);
  14988. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14989. return size * nmemb;
  14990. };
  14991. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14992. {
  14993. const auto res = curl_easy_perform(curl.get());
  14994. ASSERT_EQ(res, CURLE_OK);
  14995. }
  14996. {
  14997. auto response_code = long{};
  14998. const auto res =
  14999. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15000. ASSERT_EQ(res, CURLE_OK);
  15001. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15002. }
  15003. {
  15004. auto dl = curl_off_t{};
  15005. const auto res =
  15006. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15007. ASSERT_EQ(res, CURLE_OK);
  15008. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15009. }
  15010. {
  15011. buffer.push_back('\0');
  15012. ASSERT_STRCASEEQ(buffer.data(), reject);
  15013. }
  15014. }
  15015. }
  15016. #endif
  15017. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15018. // Regression test for #2458.
  15019. //
  15020. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15021. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15022. // ticket can make the client socket spuriously readable during the
  15023. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15024. // the client withholds the body and then blocks reading a response that never
  15025. // comes, failing with `Failed to read connection`.
  15026. //
  15027. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15028. // within the timeout. This raw OpenSSL server deliberately never sends
  15029. // `100 Continue`; the client must still deliver the body and receive 200.
  15030. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15031. signal(SIGPIPE, SIG_IGN);
  15032. const auto port = PORT + 4;
  15033. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15034. ASSERT_NE(srv, INVALID_SOCKET);
  15035. int opt = 1;
  15036. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15037. sockaddr_in addr{};
  15038. addr.sin_family = AF_INET;
  15039. addr.sin_port = htons(static_cast<uint16_t>(port));
  15040. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15041. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15042. ASSERT_EQ(0, ::listen(srv, 1));
  15043. std::atomic<size_t> server_body_bytes{0};
  15044. auto server_thread = std::thread([&] {
  15045. sockaddr_in cli_addr{};
  15046. socklen_t cli_len = sizeof(cli_addr);
  15047. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15048. if (cli == INVALID_SOCKET) { return; }
  15049. // Bound the lifetime of the server side so a buggy client (which never
  15050. // sends the body) cannot make this thread block forever on join.
  15051. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15052. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15053. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15054. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15055. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15056. SSL *ssl = SSL_new(ctx);
  15057. SSL_set_fd(ssl, static_cast<int>(cli));
  15058. if (SSL_accept(ssl) > 0) {
  15059. // Read the request headers. Reading here also flushes the TLS 1.3
  15060. // session tickets to the client. Deliberately do NOT send
  15061. // `100 Continue`.
  15062. std::string buf;
  15063. char tmp[1024];
  15064. while (buf.find("\r\n\r\n") == std::string::npos) {
  15065. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15066. if (n <= 0) { break; }
  15067. buf.append(tmp, static_cast<size_t>(n));
  15068. }
  15069. // A correct client sends the body now; count what arrives.
  15070. auto pos = buf.find("\r\n\r\n");
  15071. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15072. while (body < 4096) {
  15073. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15074. if (n <= 0) { break; }
  15075. body += static_cast<size_t>(n);
  15076. }
  15077. server_body_bytes = body;
  15078. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15079. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15080. SSL_shutdown(ssl);
  15081. }
  15082. SSL_free(ssl);
  15083. detail::close_socket(cli);
  15084. SSL_CTX_free(ctx);
  15085. });
  15086. auto se = detail::scope_exit([&] {
  15087. server_thread.join();
  15088. detail::close_socket(srv);
  15089. });
  15090. SSLClient cli("127.0.0.1", port);
  15091. cli.enable_server_certificate_verification(false);
  15092. cli.set_connection_timeout(5, 0);
  15093. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15094. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15095. std::string body(4096, 'A');
  15096. auto res = cli.Put("/api/test", body, "application/json");
  15097. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15098. EXPECT_EQ(StatusCode::OK_200, res->status);
  15099. EXPECT_EQ(body.size(), server_body_bytes.load());
  15100. }
  15101. #endif
  15102. template <typename S, typename C>
  15103. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15104. svr.Get("/stream", [&](const Request &, Response &res) {
  15105. auto data = new std::string("01234567890123456789");
  15106. res.set_content_provider(
  15107. data->size(), "text/plain",
  15108. [&, data](size_t offset, size_t length, DataSink &sink) {
  15109. const size_t DATA_CHUNK_SIZE = 4;
  15110. const auto &d = *data;
  15111. std::this_thread::sleep_for(std::chrono::seconds(1));
  15112. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15113. return true;
  15114. },
  15115. [data](bool success) {
  15116. EXPECT_FALSE(success);
  15117. delete data;
  15118. });
  15119. });
  15120. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15121. auto i = new size_t(0);
  15122. res.set_content_provider(
  15123. "text/plain",
  15124. [i](size_t, DataSink &sink) {
  15125. if (*i < 5) {
  15126. std::this_thread::sleep_for(std::chrono::seconds(1));
  15127. sink.write("abcd", 4);
  15128. (*i)++;
  15129. } else {
  15130. sink.done();
  15131. }
  15132. return true;
  15133. },
  15134. [i](bool success) {
  15135. EXPECT_FALSE(success);
  15136. delete i;
  15137. });
  15138. });
  15139. svr.Get("/chunked", [&](const Request &, Response &res) {
  15140. auto i = new size_t(0);
  15141. res.set_chunked_content_provider(
  15142. "text/plain",
  15143. [i](size_t, DataSink &sink) {
  15144. if (*i < 5) {
  15145. std::this_thread::sleep_for(std::chrono::seconds(1));
  15146. sink.os << "abcd";
  15147. (*i)++;
  15148. } else {
  15149. sink.done();
  15150. }
  15151. return true;
  15152. },
  15153. [i](bool success) {
  15154. EXPECT_FALSE(success);
  15155. delete i;
  15156. });
  15157. });
  15158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15159. auto se = detail::scope_exit([&] {
  15160. svr.stop();
  15161. listen_thread.join();
  15162. ASSERT_FALSE(svr.is_running());
  15163. });
  15164. svr.wait_until_ready();
  15165. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15166. {
  15167. auto start = std::chrono::steady_clock::now();
  15168. auto res = cli.Get("/stream");
  15169. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15170. std::chrono::steady_clock::now() - start)
  15171. .count();
  15172. ASSERT_FALSE(res);
  15173. EXPECT_EQ(Error::Read, res.error());
  15174. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15175. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15176. }
  15177. {
  15178. auto start = std::chrono::steady_clock::now();
  15179. auto res = cli.Get("/stream_without_length");
  15180. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15181. std::chrono::steady_clock::now() - start)
  15182. .count();
  15183. ASSERT_FALSE(res);
  15184. EXPECT_EQ(Error::Read, res.error());
  15185. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15186. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15187. }
  15188. {
  15189. auto start = std::chrono::steady_clock::now();
  15190. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15191. EXPECT_EQ("abcd", string(data, data_length));
  15192. return true;
  15193. });
  15194. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15195. std::chrono::steady_clock::now() - start)
  15196. .count();
  15197. ASSERT_FALSE(res);
  15198. EXPECT_EQ(Error::Read, res.error());
  15199. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15200. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15201. }
  15202. }
  15203. TEST(MaxTimeoutTest, ContentStream) {
  15204. time_t timeout = 2000;
  15205. time_t threshold = 200;
  15206. Server svr;
  15207. Client cli("localhost", PORT);
  15208. max_timeout_test(svr, cli, timeout, threshold);
  15209. }
  15210. #ifdef CPPHTTPLIB_SSL_ENABLED
  15211. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15212. time_t timeout = 2000;
  15213. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15215. SSLClient cli("localhost", PORT);
  15216. cli.enable_server_certificate_verification(false);
  15217. max_timeout_test(svr, cli, timeout, threshold);
  15218. }
  15219. #endif
  15220. class EventDispatcher {
  15221. public:
  15222. EventDispatcher() {}
  15223. bool wait_event(DataSink *sink) {
  15224. unique_lock<mutex> lk(m_);
  15225. int id = id_;
  15226. // Wait with timeout to prevent hanging if client disconnects
  15227. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15228. [&] { return cid_ == id; })) {
  15229. return false; // Timeout occurred
  15230. }
  15231. sink->write(message_.data(), message_.size());
  15232. return true;
  15233. }
  15234. void send_event(const string &message) {
  15235. lock_guard<mutex> lk(m_);
  15236. cid_ = id_++;
  15237. message_ = message;
  15238. cv_.notify_all();
  15239. }
  15240. private:
  15241. mutex m_;
  15242. condition_variable cv_;
  15243. atomic_int id_{0};
  15244. atomic_int cid_{-1};
  15245. string message_;
  15246. };
  15247. TEST(ClientInThreadTest, Issue2068) {
  15248. EventDispatcher ed;
  15249. Server svr;
  15250. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15251. res.set_chunked_content_provider("text/event-stream",
  15252. [&](size_t /*offset*/, DataSink &sink) {
  15253. return ed.wait_event(&sink);
  15254. });
  15255. });
  15256. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15257. svr.wait_until_ready();
  15258. thread event_thread([&] {
  15259. int id = 0;
  15260. while (svr.is_running()) {
  15261. this_thread::sleep_for(chrono::milliseconds(500));
  15262. std::stringstream ss;
  15263. ss << "data: " << id << "\n\n";
  15264. ed.send_event(ss.str());
  15265. id++;
  15266. }
  15267. });
  15268. auto se = detail::scope_exit([&] {
  15269. svr.stop();
  15270. listen_thread.join();
  15271. event_thread.join();
  15272. ASSERT_FALSE(svr.is_running());
  15273. });
  15274. {
  15275. auto client = detail::make_unique<Client>(HOST, PORT);
  15276. client->set_read_timeout(std::chrono::minutes(10));
  15277. std::atomic<bool> stop{false};
  15278. std::thread t([&] {
  15279. client->Get("/event1",
  15280. [&](const char *, size_t) -> bool { return !stop; });
  15281. });
  15282. std::this_thread::sleep_for(std::chrono::seconds(2));
  15283. stop = true;
  15284. client->stop();
  15285. t.join();
  15286. // Reset client after thread has finished
  15287. client.reset();
  15288. }
  15289. }
  15290. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15291. auto handled = false;
  15292. Server svr;
  15293. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15294. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15295. auto se = detail::scope_exit([&] {
  15296. svr.stop();
  15297. t.join();
  15298. ASSERT_FALSE(svr.is_running());
  15299. ASSERT_FALSE(handled);
  15300. });
  15301. svr.wait_until_ready();
  15302. // Two Content-Length headers with different values — must be rejected
  15303. auto req = "POST /test HTTP/1.1\r\n"
  15304. "Content-Length: 5\r\n"
  15305. "Content-Length: 10\r\n"
  15306. "\r\n"
  15307. "hello";
  15308. std::string response;
  15309. ASSERT_TRUE(send_request(1, req, &response));
  15310. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15311. response.substr(0, response.find("\r\n")));
  15312. }
  15313. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15314. auto handled = false;
  15315. Server svr;
  15316. svr.Post("/test", [&](const Request &, Response &res) {
  15317. handled = true;
  15318. res.set_content("ok", "text/plain");
  15319. });
  15320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15321. auto se = detail::scope_exit([&] {
  15322. svr.stop();
  15323. t.join();
  15324. ASSERT_FALSE(svr.is_running());
  15325. ASSERT_TRUE(handled);
  15326. });
  15327. svr.wait_until_ready();
  15328. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15329. auto req = "POST /test HTTP/1.1\r\n"
  15330. "Content-Length: 5\r\n"
  15331. "Content-Length: 5\r\n"
  15332. "\r\n"
  15333. "hello";
  15334. std::string response;
  15335. ASSERT_TRUE(send_request(1, req, &response));
  15336. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15337. }
  15338. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15339. Server svr;
  15340. svr.Get("/", [](const Request &req, Response &res) {
  15341. EXPECT_EQ(2U, req.trailers.size());
  15342. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15343. // Denied
  15344. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15345. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15346. // Accepted
  15347. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15348. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15349. EXPECT_TRUE(req.has_trailer("X-World"));
  15350. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15351. res.set_content("ok", "text/plain");
  15352. });
  15353. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15354. auto se = detail::scope_exit([&] {
  15355. svr.stop();
  15356. t.join();
  15357. ASSERT_FALSE(svr.is_running());
  15358. });
  15359. svr.wait_until_ready();
  15360. const std::string req = "GET / HTTP/1.1\r\n"
  15361. "Transfer-Encoding: chunked\r\n"
  15362. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15363. "\r\n"
  15364. "0\r\n"
  15365. "Content-Length: 10\r\n"
  15366. "Host: internal.local\r\n"
  15367. "Content-Type: malicious/content\r\n"
  15368. "Cookie: any\r\n"
  15369. "Set-Cookie: any\r\n"
  15370. "X-Forwarded-For: attacker.com\r\n"
  15371. "X-Real-Ip: 1.1.1.1\r\n"
  15372. "X-Hello: hello\r\n"
  15373. "X-World: world\r\n"
  15374. "\r\n";
  15375. std::string res;
  15376. ASSERT_TRUE(send_request(1, req, &res));
  15377. }
  15378. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15379. // several field lines, and the combined value is what has to be parsed. A
  15380. // Trailer field split across lines therefore declares every name it lists;
  15381. // reading only the first line silently drops the trailers the later lines
  15382. // declare. The prohibited-trailer filter still applies to every line.
  15383. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15384. Server svr;
  15385. size_t observed_trailer_count = 0;
  15386. std::string observed_hello;
  15387. std::string observed_world;
  15388. bool observed_content_length = true;
  15389. svr.Get("/", [&](const Request &req, Response &res) {
  15390. observed_trailer_count = req.trailers.size();
  15391. observed_hello = req.get_trailer_value("X-Hello");
  15392. observed_world = req.get_trailer_value("X-World");
  15393. observed_content_length = req.has_trailer("Content-Length");
  15394. res.set_content("ok", "text/plain");
  15395. });
  15396. auto port = svr.bind_to_any_port(HOST);
  15397. thread t = thread([&]() { svr.listen_after_bind(); });
  15398. auto se = detail::scope_exit([&] {
  15399. svr.stop();
  15400. t.join();
  15401. ASSERT_FALSE(svr.is_running());
  15402. });
  15403. svr.wait_until_ready();
  15404. const std::string req = "GET / HTTP/1.1\r\n"
  15405. "Transfer-Encoding: chunked\r\n"
  15406. "Trailer: X-Hello\r\n"
  15407. "Trailer: X-World, Content-Length\r\n"
  15408. "\r\n"
  15409. "0\r\n"
  15410. "X-Hello: hello\r\n"
  15411. "X-World: world\r\n"
  15412. "Content-Length: 10\r\n"
  15413. "\r\n";
  15414. std::string res;
  15415. ASSERT_TRUE(send_request(1, req, &res, port));
  15416. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15417. // Accepted: both field lines contribute to the declared set
  15418. EXPECT_EQ(2U, observed_trailer_count);
  15419. EXPECT_EQ(observed_hello, "hello");
  15420. EXPECT_EQ(observed_world, "world");
  15421. // Denied: a prohibited name stays prohibited on a later field line
  15422. EXPECT_FALSE(observed_content_length);
  15423. }
  15424. // A direct client that is not listed in trusted_proxies must not be able to
  15425. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15426. // the peer address on the actual TCP connection determines whether the
  15427. // header is honored.
  15428. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15429. Server svr;
  15430. // Deliberately does NOT include the loopback address the test client
  15431. // actually connects from, so the direct connection is not a trusted proxy.
  15432. svr.set_trusted_proxies({"203.0.113.66"});
  15433. std::string observed_remote_addr;
  15434. svr.Get("/ip", [&](const Request &req, Response &res) {
  15435. observed_remote_addr = req.remote_addr;
  15436. res.set_content("ok", "text/plain");
  15437. });
  15438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. ASSERT_FALSE(svr.is_running());
  15443. });
  15444. svr.wait_until_ready();
  15445. Client cli(HOST, PORT);
  15446. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15448. EXPECT_EQ(StatusCode::OK_200, res->status);
  15449. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15450. // ignored entirely and the real connection-level address retained.
  15451. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15452. observed_remote_addr == "127.0.0.1");
  15453. }
  15454. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15455. Server svr;
  15456. std::string observed_remote_addr;
  15457. std::string observed_xff;
  15458. svr.Get("/ip", [&](const Request &req, Response &res) {
  15459. observed_remote_addr = req.remote_addr;
  15460. observed_xff = req.get_header_value("X-Forwarded-For");
  15461. res.set_content("ok", "text/plain");
  15462. });
  15463. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15464. auto se = detail::scope_exit([&] {
  15465. svr.stop();
  15466. t.join();
  15467. ASSERT_FALSE(svr.is_running());
  15468. });
  15469. svr.wait_until_ready();
  15470. Client cli(HOST, PORT);
  15471. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15473. EXPECT_EQ(StatusCode::OK_200, res->status);
  15474. EXPECT_EQ(observed_xff, "203.0.113.66");
  15475. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15476. observed_remote_addr == "127.0.0.1");
  15477. }
  15478. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15479. Server svr;
  15480. svr.set_trusted_proxies({"203.0.113.66"});
  15481. std::string observed_remote_addr;
  15482. std::string observed_xff;
  15483. svr.Get("/ip", [&](const Request &req, Response &res) {
  15484. observed_remote_addr = req.remote_addr;
  15485. observed_xff = req.get_header_value("X-Forwarded-For");
  15486. res.set_content("ok", "text/plain");
  15487. });
  15488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15489. auto se = detail::scope_exit([&] {
  15490. svr.stop();
  15491. t.join();
  15492. ASSERT_FALSE(svr.is_running());
  15493. });
  15494. svr.wait_until_ready();
  15495. Client cli(HOST, PORT);
  15496. auto res = cli.Get("/ip");
  15497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15498. EXPECT_EQ(StatusCode::OK_200, res->status);
  15499. EXPECT_EQ(observed_xff, "");
  15500. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15501. observed_remote_addr == "127.0.0.1");
  15502. }
  15503. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15504. Server svr;
  15505. // Include the loopback address the test client actually connects from, so
  15506. // the direct connection itself is recognized as the trusted proxy hop.
  15507. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15508. std::string observed_remote_addr;
  15509. std::string observed_xff;
  15510. svr.Get("/ip", [&](const Request &req, Response &res) {
  15511. observed_remote_addr = req.remote_addr;
  15512. observed_xff = req.get_header_value("X-Forwarded-For");
  15513. res.set_content("ok", "text/plain");
  15514. });
  15515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15516. auto se = detail::scope_exit([&] {
  15517. svr.stop();
  15518. t.join();
  15519. ASSERT_FALSE(svr.is_running());
  15520. });
  15521. svr.wait_until_ready();
  15522. Client cli(HOST, PORT);
  15523. auto res = cli.Get(
  15524. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15526. EXPECT_EQ(StatusCode::OK_200, res->status);
  15527. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15528. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15529. }
  15530. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15531. Server svr;
  15532. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15533. std::string observed_remote_addr;
  15534. std::string observed_xff;
  15535. svr.Get("/ip", [&](const Request &req, Response &res) {
  15536. observed_remote_addr = req.remote_addr;
  15537. observed_xff = req.get_header_value("X-Forwarded-For");
  15538. res.set_content("ok", "text/plain");
  15539. });
  15540. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15541. auto se = detail::scope_exit([&] {
  15542. svr.stop();
  15543. t.join();
  15544. ASSERT_FALSE(svr.is_running());
  15545. });
  15546. svr.wait_until_ready();
  15547. Client cli(HOST, PORT);
  15548. auto res = cli.Get(
  15549. "/ip",
  15550. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15552. EXPECT_EQ(StatusCode::OK_200, res->status);
  15553. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15554. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15555. }
  15556. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15557. Server svr;
  15558. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15559. std::string observed_remote_addr;
  15560. std::string observed_xff;
  15561. svr.Get("/ip", [&](const Request &req, Response &res) {
  15562. observed_remote_addr = req.remote_addr;
  15563. observed_xff = req.get_header_value("X-Forwarded-For");
  15564. res.set_content("ok", "text/plain");
  15565. });
  15566. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15567. auto se = detail::scope_exit([&] {
  15568. svr.stop();
  15569. t.join();
  15570. ASSERT_FALSE(svr.is_running());
  15571. });
  15572. svr.wait_until_ready();
  15573. Client cli(HOST, PORT);
  15574. auto res = cli.Get(
  15575. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15577. EXPECT_EQ(StatusCode::OK_200, res->status);
  15578. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15579. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15580. // and must not be selected.
  15581. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15582. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15583. }
  15584. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15585. Server svr;
  15586. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15587. std::string observed_remote_addr;
  15588. svr.Get("/ip", [&](const Request &req, Response &res) {
  15589. observed_remote_addr = req.remote_addr;
  15590. res.set_content("ok", "text/plain");
  15591. });
  15592. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15593. auto se = detail::scope_exit([&] {
  15594. svr.stop();
  15595. t.join();
  15596. ASSERT_FALSE(svr.is_running());
  15597. });
  15598. svr.wait_until_ready();
  15599. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15600. // a forged address and the trusted proxy's own address; the forged value must
  15601. // not win over the address the trusted proxy actually recorded.
  15602. Client cli(HOST, PORT);
  15603. auto res = cli.Get(
  15604. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15606. EXPECT_EQ(StatusCode::OK_200, res->status);
  15607. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15608. }
  15609. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15610. Server svr;
  15611. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15612. std::string observed_remote_addr;
  15613. std::string observed_xff;
  15614. svr.Get("/ip", [&](const Request &req, Response &res) {
  15615. observed_remote_addr = req.remote_addr;
  15616. observed_xff = req.get_header_value("X-Forwarded-For");
  15617. res.set_content("ok", "text/plain");
  15618. });
  15619. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15620. auto se = detail::scope_exit([&] {
  15621. svr.stop();
  15622. t.join();
  15623. ASSERT_FALSE(svr.is_running());
  15624. });
  15625. svr.wait_until_ready();
  15626. Client cli(HOST, PORT);
  15627. auto res = cli.Get(
  15628. "/ip",
  15629. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15631. EXPECT_EQ(StatusCode::OK_200, res->status);
  15632. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15633. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15634. }
  15635. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15636. Server svr;
  15637. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15638. std::string observed_remote_addr;
  15639. std::string observed_xff;
  15640. svr.Get("/ip", [&](const Request &req, Response &res) {
  15641. observed_remote_addr = req.remote_addr;
  15642. observed_xff = req.get_header_value("X-Forwarded-For");
  15643. res.set_content("ok", "text/plain");
  15644. });
  15645. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15646. auto se = detail::scope_exit([&] {
  15647. svr.stop();
  15648. t.join();
  15649. ASSERT_FALSE(svr.is_running());
  15650. });
  15651. svr.wait_until_ready();
  15652. std::string raw_req =
  15653. "GET /ip HTTP/1.1\r\n"
  15654. "Host: localhost\r\n"
  15655. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15656. "Connection: close\r\n"
  15657. "\r\n";
  15658. std::string out;
  15659. ASSERT_TRUE(send_request(5, raw_req, &out));
  15660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15661. // Header parser trims surrounding whitespace of the header value
  15662. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15663. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15664. }
  15665. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15666. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15667. // their own X-Forwarded-For as a separate field line rather than extending the
  15668. // one the client sent, so every occurrence has to be taken into account.
  15669. // Reading only the first one hands back the address the client chose.
  15670. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15671. Server svr;
  15672. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15673. std::string observed_remote_addr;
  15674. size_t observed_xff_count = 0;
  15675. svr.Get("/ip", [&](const Request &req, Response &res) {
  15676. observed_remote_addr = req.remote_addr;
  15677. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15678. res.set_content("ok", "text/plain");
  15679. });
  15680. auto port = svr.bind_to_any_port(HOST);
  15681. thread t = thread([&]() { svr.listen_after_bind(); });
  15682. auto se = detail::scope_exit([&] {
  15683. svr.stop();
  15684. t.join();
  15685. ASSERT_FALSE(svr.is_running());
  15686. });
  15687. svr.wait_until_ready();
  15688. // The client supplies the first field line; the trusted proxy appends the
  15689. // address it observed as a second one.
  15690. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15691. "Host: localhost\r\n"
  15692. "X-Forwarded-For: 1.2.3.4\r\n"
  15693. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15694. "Connection: close\r\n"
  15695. "\r\n";
  15696. std::string out;
  15697. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15698. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15699. EXPECT_EQ(observed_xff_count, 2U);
  15700. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15701. // The same chain spread over one field line per hop derives the same client
  15702. // address, i.e. the split and the comma-joined representations agree.
  15703. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15704. "Host: localhost\r\n"
  15705. "X-Forwarded-For: 1.2.3.4\r\n"
  15706. "X-Forwarded-For: 198.51.100.23\r\n"
  15707. "X-Forwarded-For: 192.0.2.45\r\n"
  15708. "Connection: close\r\n"
  15709. "\r\n";
  15710. out.clear();
  15711. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15712. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15713. EXPECT_EQ(observed_xff_count, 3U);
  15714. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15715. }
  15716. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15717. // crash the server (it used to call front() on an empty vector inside
  15718. // get_client_ip). The connection-level remote address must be retained instead.
  15719. static void run_malformed_xff_test(const std::string &xff_value) {
  15720. Server svr;
  15721. svr.set_trusted_proxies({"192.0.2.45"});
  15722. std::string observed_remote_addr;
  15723. svr.Get("/ip", [&](const Request &req, Response &res) {
  15724. observed_remote_addr = req.remote_addr;
  15725. res.set_content("ok", "text/plain");
  15726. });
  15727. int port = 0;
  15728. thread t = thread([&]() {
  15729. port = svr.bind_to_any_port(HOST);
  15730. svr.listen_after_bind();
  15731. });
  15732. auto se = detail::scope_exit([&] {
  15733. svr.stop();
  15734. t.join();
  15735. ASSERT_FALSE(svr.is_running());
  15736. });
  15737. svr.wait_until_ready();
  15738. Client cli(HOST, port);
  15739. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15741. EXPECT_EQ(StatusCode::OK_200, res->status);
  15742. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15743. observed_remote_addr == "127.0.0.1");
  15744. }
  15745. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15746. run_malformed_xff_test("");
  15747. }
  15748. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15749. run_malformed_xff_test(",");
  15750. }
  15751. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15752. run_malformed_xff_test(", , ,");
  15753. }
  15754. // The same rule applies to Accept: a request whose acceptable types are spread
  15755. // over several field lines must be negotiated against all of them.
  15756. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15757. // case-insensitive connection options. Comparing the whole field value against
  15758. // one option misses a client that sends several of them, and misses every
  15759. // casing but the one written in the comparison.
  15760. //
  15761. // Sends req, reads the response, then reuses the same socket for a second
  15762. // request to find out whether the server kept the connection.
  15763. static void probe_connection_reuse(int port, const std::string &req,
  15764. bool *announced_close, bool *reusable) {
  15765. auto error = Error::Success;
  15766. auto sock = detail::create_client_socket(
  15767. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15768. /*connection_timeout_sec=*/5, 0,
  15769. /*read_timeout_sec=*/1, 0,
  15770. /*write_timeout_sec=*/5, 0, std::string(), error);
  15771. ASSERT_NE(sock, INVALID_SOCKET);
  15772. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15773. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15774. "Host: localhost\r\n"
  15775. "Connection: close\r\n"
  15776. "\r\n";
  15777. std::string first_response;
  15778. std::string second_response;
  15779. detail::process_client_socket(
  15780. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15781. [&](Stream &strm) {
  15782. if (strm.write(req.data(), req.size()) !=
  15783. static_cast<ssize_t>(req.size())) {
  15784. return false;
  15785. }
  15786. char buf[512];
  15787. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15788. // Headers plus the two-byte body of the handler below
  15789. while (reader.getline()) {
  15790. first_response += reader.ptr();
  15791. if (first_response.find("ok") != std::string::npos) { break; }
  15792. }
  15793. if (strm.write(second.data(), second.size()) !=
  15794. static_cast<ssize_t>(second.size())) {
  15795. return true;
  15796. }
  15797. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15798. while (reader2.getline()) {
  15799. second_response += reader2.ptr();
  15800. if (second_response.find("ok") != std::string::npos) { break; }
  15801. }
  15802. return true;
  15803. });
  15804. *announced_close =
  15805. first_response.find("Connection: close") != std::string::npos;
  15806. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15807. }
  15808. class ConnectionTokenTest : public ::testing::Test {
  15809. protected:
  15810. void SetUp() override {
  15811. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15812. res.set_content("ok", "text/plain");
  15813. });
  15814. port_ = svr_.bind_to_any_port(HOST);
  15815. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15816. svr_.wait_until_ready();
  15817. }
  15818. void TearDown() override {
  15819. svr_.stop();
  15820. if (thread_.joinable()) { thread_.join(); }
  15821. }
  15822. Server svr_;
  15823. int port_ = 0;
  15824. thread thread_;
  15825. };
  15826. // "close" alongside another option still closes the connection, and the
  15827. // response says so rather than leaving the peer to discover it.
  15828. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15829. bool announced_close = false;
  15830. bool reusable = true;
  15831. probe_connection_reuse(port_,
  15832. "GET /keepalive HTTP/1.1\r\n"
  15833. "Host: localhost\r\n"
  15834. "Connection: keep-alive, close\r\n"
  15835. "\r\n",
  15836. &announced_close, &reusable);
  15837. EXPECT_TRUE(announced_close);
  15838. EXPECT_FALSE(reusable);
  15839. }
  15840. // "close" split over two field lines is the same list, so it is honored too.
  15841. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15842. bool announced_close = false;
  15843. bool reusable = true;
  15844. probe_connection_reuse(port_,
  15845. "GET /keepalive HTTP/1.1\r\n"
  15846. "Host: localhost\r\n"
  15847. "Connection: keep-alive\r\n"
  15848. "Connection: close\r\n"
  15849. "\r\n",
  15850. &announced_close, &reusable);
  15851. EXPECT_TRUE(announced_close);
  15852. EXPECT_FALSE(reusable);
  15853. }
  15854. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15855. // keep-alive in the spelling everyone actually sends keeps its connection.
  15856. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15857. bool announced_close = false;
  15858. bool reusable = false;
  15859. probe_connection_reuse(port_,
  15860. "GET /keepalive HTTP/1.0\r\n"
  15861. "Host: localhost\r\n"
  15862. "Connection: keep-alive\r\n"
  15863. "\r\n",
  15864. &announced_close, &reusable);
  15865. EXPECT_FALSE(announced_close);
  15866. EXPECT_TRUE(reusable);
  15867. }
  15868. // A token the value merely contains is not the token itself.
  15869. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15870. bool announced_close = false;
  15871. bool reusable = false;
  15872. probe_connection_reuse(port_,
  15873. "GET /keepalive HTTP/1.1\r\n"
  15874. "Host: localhost\r\n"
  15875. "Connection: notclose\r\n"
  15876. "\r\n",
  15877. &announced_close, &reusable);
  15878. EXPECT_FALSE(announced_close);
  15879. EXPECT_TRUE(reusable);
  15880. }
  15881. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15882. Server svr;
  15883. std::vector<std::string> observed_types;
  15884. svr.Get("/", [&](const Request &req, Response &res) {
  15885. observed_types = req.accept_content_types;
  15886. res.set_content("ok", "text/plain");
  15887. });
  15888. auto port = svr.bind_to_any_port(HOST);
  15889. thread t = thread([&]() { svr.listen_after_bind(); });
  15890. auto se = detail::scope_exit([&] {
  15891. svr.stop();
  15892. t.join();
  15893. ASSERT_FALSE(svr.is_running());
  15894. });
  15895. svr.wait_until_ready();
  15896. Client cli(HOST, port);
  15897. Headers headers;
  15898. headers.emplace("Accept", "text/plain;q=0.5");
  15899. headers.emplace("Accept", "application/json");
  15900. auto res = cli.Get("/", headers);
  15901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15902. EXPECT_EQ(StatusCode::OK_200, res->status);
  15903. // Sorted by q-value, so the second field line's type comes first
  15904. ASSERT_EQ(2U, observed_types.size());
  15905. EXPECT_EQ("application/json", observed_types[0]);
  15906. EXPECT_EQ("text/plain", observed_types[1]);
  15907. }
  15908. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15909. // empty field line must not contribute a bare comma to the combined value.
  15910. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15911. Server svr;
  15912. std::vector<std::string> observed_types;
  15913. svr.Get("/", [&](const Request &req, Response &res) {
  15914. observed_types = req.accept_content_types;
  15915. res.set_content("ok", "text/plain");
  15916. });
  15917. auto port = svr.bind_to_any_port(HOST);
  15918. thread t = thread([&]() { svr.listen_after_bind(); });
  15919. auto se = detail::scope_exit([&] {
  15920. svr.stop();
  15921. t.join();
  15922. ASSERT_FALSE(svr.is_running());
  15923. });
  15924. svr.wait_until_ready();
  15925. // Empty first field line, then a real one
  15926. std::string raw_req = "GET / HTTP/1.1\r\n"
  15927. "Host: localhost\r\n"
  15928. "Accept:\r\n"
  15929. "Accept: application/json\r\n"
  15930. "Connection: close\r\n"
  15931. "\r\n";
  15932. std::string out;
  15933. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15934. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15935. ASSERT_EQ(1U, observed_types.size());
  15936. EXPECT_EQ("application/json", observed_types[0]);
  15937. }
  15938. // The skip in get_combined_header_value() is what keeps an empty field line
  15939. // from contributing a bare comma. Only a trailing empty field line exercises
  15940. // it: a leading one is already covered by the "combined is still empty" check,
  15941. // and parse_accept_header() now ignores the empty element either way, so the
  15942. // request-level test above can no longer tell the two apart.
  15943. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  15944. Headers headers;
  15945. headers.emplace("Accept", "text/html");
  15946. headers.emplace("Accept", "");
  15947. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  15948. headers.clear();
  15949. headers.emplace("Accept", "");
  15950. headers.emplace("Accept", "application/json");
  15951. EXPECT_EQ("application/json",
  15952. detail::get_combined_header_value(headers, "Accept"));
  15953. }
  15954. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15955. // An encoding offered on a later Accept-Encoding field line is still offered.
  15956. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15957. Server svr;
  15958. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15959. res.set_content(std::string(1024, 'x'), "text/plain");
  15960. });
  15961. auto port = svr.bind_to_any_port(HOST);
  15962. thread t = thread([&]() { svr.listen_after_bind(); });
  15963. auto se = detail::scope_exit([&] {
  15964. svr.stop();
  15965. t.join();
  15966. ASSERT_FALSE(svr.is_running());
  15967. });
  15968. svr.wait_until_ready();
  15969. Client cli(HOST, port);
  15970. cli.set_decompress(false);
  15971. Headers headers;
  15972. headers.emplace("Accept-Encoding", "identity");
  15973. headers.emplace("Accept-Encoding", "gzip");
  15974. auto res = cli.Get("/", headers);
  15975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15976. EXPECT_EQ(StatusCode::OK_200, res->status);
  15977. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15978. }
  15979. #endif
  15980. #ifndef _WIN32
  15981. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15982. Server svr;
  15983. svr.Post("/post", [&](const Request &req, Response &res) {
  15984. res.set_content(req.body, "text/plain");
  15985. });
  15986. svr.Put("/put", [&](const Request &req, Response &res) {
  15987. res.set_content(req.body, "text/plain");
  15988. });
  15989. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15990. res.set_content(req.body, "text/plain");
  15991. });
  15992. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15993. res.set_content(req.body, "text/plain");
  15994. });
  15995. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15996. auto se = detail::scope_exit([&] {
  15997. svr.stop();
  15998. t.join();
  15999. ASSERT_FALSE(svr.is_running());
  16000. });
  16001. svr.wait_until_ready();
  16002. std::string resp;
  16003. // POST without Content-Length
  16004. ASSERT_TRUE(send_request(5,
  16005. "POST /post HTTP/1.1\r\n"
  16006. "Host: localhost\r\n"
  16007. "Connection: close\r\n"
  16008. "\r\n",
  16009. &resp));
  16010. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16011. // PUT without Content-Length
  16012. resp.clear();
  16013. ASSERT_TRUE(send_request(5,
  16014. "PUT /put HTTP/1.1\r\n"
  16015. "Host: localhost\r\n"
  16016. "Connection: close\r\n"
  16017. "\r\n",
  16018. &resp));
  16019. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16020. // PATCH without Content-Length
  16021. resp.clear();
  16022. ASSERT_TRUE(send_request(5,
  16023. "PATCH /patch HTTP/1.1\r\n"
  16024. "Host: localhost\r\n"
  16025. "Connection: close\r\n"
  16026. "\r\n",
  16027. &resp));
  16028. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16029. // DELETE without Content-Length
  16030. resp.clear();
  16031. ASSERT_TRUE(send_request(5,
  16032. "DELETE /delete HTTP/1.1\r\n"
  16033. "Host: localhost\r\n"
  16034. "Connection: close\r\n"
  16035. "\r\n",
  16036. &resp));
  16037. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16038. }
  16039. #endif
  16040. //==============================================================================
  16041. // open_stream() Tests
  16042. //==============================================================================
  16043. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16044. std::string result;
  16045. char buf[8192];
  16046. ssize_t n;
  16047. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16048. result.append(buf, static_cast<size_t>(n));
  16049. }
  16050. return result;
  16051. }
  16052. // Mock stream for unit tests
  16053. class MockStream : public Stream {
  16054. public:
  16055. std::string data;
  16056. size_t pos = 0;
  16057. ssize_t error_after = -1; // -1 = no error
  16058. explicit MockStream(const std::string &d, ssize_t err = -1)
  16059. : data(d), error_after(err) {}
  16060. bool is_readable() const override { return true; }
  16061. bool wait_readable() const override { return true; }
  16062. bool wait_writable() const override { return true; }
  16063. ssize_t read(char *ptr, size_t size) override {
  16064. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16065. if (pos >= data.size()) return 0;
  16066. size_t limit =
  16067. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16068. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16069. std::memcpy(ptr, data.data() + pos, to_read);
  16070. pos += to_read;
  16071. return static_cast<ssize_t>(to_read);
  16072. }
  16073. ssize_t write(const char *, size_t) override { return -1; }
  16074. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16075. ip = "127.0.0.1";
  16076. port = 0;
  16077. }
  16078. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16079. ip = "127.0.0.1";
  16080. port = 0;
  16081. }
  16082. socket_t socket() const override { return INVALID_SOCKET; }
  16083. time_t duration() const override { return 0; }
  16084. };
  16085. TEST(StreamHandleTest, Basic) {
  16086. ClientImpl::StreamHandle handle;
  16087. EXPECT_FALSE(handle.is_valid());
  16088. handle.response = detail::make_unique<Response>();
  16089. handle.error = Error::Connection;
  16090. EXPECT_FALSE(handle.is_valid());
  16091. handle.error = Error::Success;
  16092. EXPECT_TRUE(handle.is_valid());
  16093. }
  16094. TEST(BodyReaderTest, Basic) {
  16095. MockStream stream("Hello, World!");
  16096. detail::BodyReader reader;
  16097. reader.stream = &stream;
  16098. reader.content_length = 13;
  16099. char buf[32];
  16100. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16101. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16102. EXPECT_TRUE(reader.eof);
  16103. }
  16104. TEST(BodyReaderTest, NoStream) {
  16105. detail::BodyReader reader;
  16106. char buf[32];
  16107. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16108. EXPECT_EQ(Error::Connection, reader.last_error);
  16109. }
  16110. TEST(BodyReaderTest, Error) {
  16111. MockStream stream("Hello, World!", 5);
  16112. detail::BodyReader reader;
  16113. reader.stream = &stream;
  16114. reader.content_length = 13;
  16115. char buf[32];
  16116. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16117. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16118. EXPECT_EQ(Error::Read, reader.last_error);
  16119. }
  16120. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16121. // Mock-based StreamHandle tests relying on private internals are removed.
  16122. class OpenStreamTest : public ::testing::Test {
  16123. protected:
  16124. void SetUp() override {
  16125. svr_.Get("/hello", [](const Request &, Response &res) {
  16126. res.set_content("Hello World!", "text/plain");
  16127. });
  16128. svr_.Get("/large", [](const Request &, Response &res) {
  16129. res.set_content(std::string(10000, 'X'), "text/plain");
  16130. });
  16131. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16132. res.set_content("Hello World!", "image/jpeg");
  16133. res.set_header("Content-Encoding", "UTF-8");
  16134. });
  16135. svr_.Get("/chunked", [](const Request &, Response &res) {
  16136. res.set_chunked_content_provider("text/plain",
  16137. [](size_t offset, DataSink &sink) {
  16138. if (offset < 15) {
  16139. sink.write("chunk", 5);
  16140. return true;
  16141. }
  16142. sink.done();
  16143. return true;
  16144. });
  16145. });
  16146. svr_.Get("/compressible", [](const Request &, Response &res) {
  16147. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16148. DataSink &sink) {
  16149. if (offset < 100 * 1024) {
  16150. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16151. sink.write(chunk.data(), chunk.size());
  16152. return true;
  16153. }
  16154. sink.done();
  16155. return true;
  16156. });
  16157. });
  16158. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16159. [](const Request & /*req*/, Response &res) {
  16160. auto i = new int(0);
  16161. res.set_header("Trailer", "Content-Length, X-Allowed");
  16162. res.set_chunked_content_provider(
  16163. "text/plain",
  16164. [i](size_t /*offset*/, DataSink &sink) {
  16165. switch (*i) {
  16166. case 0: sink.os << "123"; break;
  16167. case 1: sink.os << "456"; break;
  16168. case 2: sink.os << "789"; break;
  16169. case 3: {
  16170. sink.done_with_trailer(
  16171. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16172. } break;
  16173. }
  16174. (*i)++;
  16175. return true;
  16176. },
  16177. [i](bool success) {
  16178. EXPECT_TRUE(success);
  16179. delete i;
  16180. });
  16181. });
  16182. // Echo headers endpoint for header-related tests
  16183. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16184. std::string body;
  16185. for (const auto &h : req.headers) {
  16186. body.append(h.first);
  16187. body.push_back(':');
  16188. body.append(h.second);
  16189. body.push_back('\n');
  16190. }
  16191. res.set_content(body, "text/plain");
  16192. });
  16193. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16194. std::string body;
  16195. for (const auto &h : req.headers) {
  16196. body.append(h.first);
  16197. body.push_back(':');
  16198. body.append(h.second);
  16199. body.push_back('\n');
  16200. }
  16201. res.set_content(body, "text/plain");
  16202. });
  16203. port_ = svr_.bind_to_any_port("127.0.0.1");
  16204. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16205. svr_.wait_until_ready();
  16206. }
  16207. void TearDown() override {
  16208. svr_.stop();
  16209. if (thread_.joinable()) thread_.join();
  16210. }
  16211. Server svr_;
  16212. std::thread thread_;
  16213. int port_ = 0;
  16214. };
  16215. TEST_F(OpenStreamTest, Basic) {
  16216. Client cli("127.0.0.1", port_);
  16217. auto handle = cli.open_stream("GET", "/hello");
  16218. EXPECT_TRUE(handle.is_valid());
  16219. EXPECT_EQ("Hello World!", read_all(handle));
  16220. }
  16221. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16222. Client cli("127.0.0.1", port_);
  16223. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16224. ASSERT_TRUE(handle.is_valid());
  16225. EXPECT_EQ("Hello World!", read_all(handle));
  16226. }
  16227. TEST_F(OpenStreamTest, SmallBuffer) {
  16228. Client cli("127.0.0.1", port_);
  16229. auto handle = cli.open_stream("GET", "/hello");
  16230. std::string result;
  16231. char buf[4];
  16232. ssize_t n;
  16233. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16234. result.append(buf, static_cast<size_t>(n));
  16235. EXPECT_EQ("Hello World!", result);
  16236. }
  16237. TEST_F(OpenStreamTest, DefaultHeaders) {
  16238. Client cli("127.0.0.1", port_);
  16239. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16240. {
  16241. auto handle = cli.open_stream("GET", "/echo-headers");
  16242. ASSERT_TRUE(handle.is_valid());
  16243. auto body = read_all(handle);
  16244. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16245. std::string::npos);
  16246. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16247. std::string::npos);
  16248. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16249. }
  16250. // open_stream POST with body and no explicit content_type should NOT add
  16251. // text/plain Content-Type (behavior differs from non-streaming path), but
  16252. // should include Content-Length
  16253. {
  16254. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16255. ASSERT_TRUE(handle.is_valid());
  16256. auto body = read_all(handle);
  16257. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16258. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16259. }
  16260. // open_stream POST with explicit Content-Type should preserve it
  16261. {
  16262. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16263. {{"Content-Type", "application/custom"}},
  16264. "{}", "application/custom");
  16265. ASSERT_TRUE(handle.is_valid());
  16266. auto body = read_all(handle);
  16267. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16268. }
  16269. // User-specified User-Agent must not be overwritten for stream API
  16270. {
  16271. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16272. {{"User-Agent", "MyAgent/1.2"}});
  16273. ASSERT_TRUE(handle.is_valid());
  16274. auto body = read_all(handle);
  16275. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16276. }
  16277. }
  16278. TEST_F(OpenStreamTest, Large) {
  16279. Client cli("127.0.0.1", port_);
  16280. auto handle = cli.open_stream("GET", "/large");
  16281. EXPECT_EQ(10000u, read_all(handle).size());
  16282. }
  16283. TEST_F(OpenStreamTest, ConnectionError) {
  16284. Client cli("127.0.0.1", 9999);
  16285. auto handle = cli.open_stream("GET", "/hello");
  16286. EXPECT_FALSE(handle.is_valid());
  16287. }
  16288. TEST_F(OpenStreamTest, Chunked) {
  16289. Client cli("127.0.0.1", port_);
  16290. auto handle = cli.open_stream("GET", "/chunked");
  16291. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16292. "Transfer-Encoding") == "chunked");
  16293. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16294. }
  16295. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16296. Client cli("127.0.0.1", port_);
  16297. auto handle =
  16298. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16299. ASSERT_TRUE(handle.is_valid());
  16300. // Consume body to allow trailers to be received/parsed
  16301. auto body = read_all(handle);
  16302. // Explicitly parse trailers (ensure trailers are available for assertion)
  16303. handle.parse_trailers_if_needed();
  16304. EXPECT_EQ(std::string("123456789"), body);
  16305. // The response should include a Trailer header declaring both names
  16306. ASSERT_TRUE(handle.response);
  16307. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16308. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16309. handle.response->get_header_value("Trailer"));
  16310. // Prohibited trailer must not be present
  16311. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16312. // Allowed trailer should be present
  16313. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16314. EXPECT_EQ(std::string("yes"),
  16315. handle.response->get_trailer_value("X-Allowed"));
  16316. // Verify trailers are NOT present as regular headers
  16317. EXPECT_EQ(std::string(""),
  16318. handle.response->get_header_value("Content-Length"));
  16319. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16320. }
  16321. static std::thread serve_single_response(std::promise<int> &port_promise,
  16322. const std::string &response) {
  16323. return std::thread([&port_promise, response] {
  16324. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16325. default_socket_options(srv);
  16326. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16327. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16328. sockaddr_in addr{};
  16329. addr.sin_family = AF_INET;
  16330. addr.sin_port = htons(0); // Let OS assign a free port
  16331. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16332. int opt = 1;
  16333. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16334. #ifdef _WIN32
  16335. reinterpret_cast<const char *>(&opt),
  16336. #else
  16337. &opt,
  16338. #endif
  16339. sizeof(opt));
  16340. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16341. ::listen(srv, 1) != 0) {
  16342. port_promise.set_value(-1);
  16343. detail::close_socket(srv);
  16344. return;
  16345. }
  16346. socklen_t addr_len = sizeof(addr);
  16347. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16348. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16349. sockaddr_in cli_addr{};
  16350. socklen_t cli_len = sizeof(cli_addr);
  16351. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16352. if (cli != INVALID_SOCKET) {
  16353. // Read the complete HTTP request (until the blank line that terminates
  16354. // headers) before sending the response. If the server closes the socket
  16355. // while the client's request data is still unread in the kernel receive
  16356. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16357. // connection on both sides: it discards the client's receive buffer
  16358. // (which already holds our response) and causes any in-progress write on
  16359. // the client to fail with ECONNRESET. Reading all request data first
  16360. // ensures close() emits a graceful FIN.
  16361. {
  16362. char rbuf[256];
  16363. std::string req;
  16364. while (req.find("\r\n\r\n") == std::string::npos) {
  16365. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16366. if (n <= 0) { break; }
  16367. req.append(rbuf, static_cast<size_t>(n));
  16368. }
  16369. }
  16370. ::send(cli,
  16371. #ifdef _WIN32
  16372. static_cast<const char *>(response.c_str()),
  16373. static_cast<int>(response.size()),
  16374. #else
  16375. response.c_str(), response.size(),
  16376. #endif
  16377. 0);
  16378. detail::close_socket(cli);
  16379. }
  16380. detail::close_socket(srv);
  16381. });
  16382. }
  16383. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16384. #ifndef _WIN32
  16385. signal(SIGPIPE, SIG_IGN);
  16386. #endif
  16387. std::promise<int> port_promise;
  16388. auto port_future = port_promise.get_future();
  16389. auto server_thread =
  16390. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16391. "Content-Type: text/plain\r\n"
  16392. "Content-Length: not-a-number\r\n"
  16393. "Connection: close\r\n"
  16394. "\r\n"
  16395. "hello");
  16396. auto port = port_future.get();
  16397. ASSERT_GT(port, 0);
  16398. Client cli("127.0.0.1", port);
  16399. auto handle = cli.open_stream("GET", "/");
  16400. EXPECT_FALSE(handle.is_valid());
  16401. server_thread.join();
  16402. }
  16403. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16404. #ifndef _WIN32
  16405. signal(SIGPIPE, SIG_IGN);
  16406. #endif
  16407. std::promise<int> port_promise;
  16408. auto port_future = port_promise.get_future();
  16409. auto server_thread = serve_single_response(
  16410. port_promise, "HTTP/1.1 200 OK\r\n"
  16411. "Content-Type: text/plain\r\n"
  16412. "Content-Length: 99999999999999999999999999\r\n"
  16413. "Connection: close\r\n"
  16414. "\r\n"
  16415. "hello");
  16416. auto port = port_future.get();
  16417. ASSERT_GT(port, 0);
  16418. // Historically std::stoull would throw std::out_of_range here and crash
  16419. // the process, then parsing silently clamped to a bogus framing length and
  16420. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16421. // so the stream fails to open, matching the not-a-number case above. The
  16422. // process still must NOT terminate.
  16423. Client cli("127.0.0.1", port);
  16424. auto handle = cli.open_stream("GET", "/");
  16425. EXPECT_FALSE(handle.is_valid());
  16426. server_thread.join();
  16427. }
  16428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16429. TEST_F(OpenStreamTest, Gzip) {
  16430. Client cli("127.0.0.1", port_);
  16431. auto handle = cli.open_stream("GET", "/compressible", {},
  16432. {{"Accept-Encoding", "gzip"}});
  16433. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16434. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16435. }
  16436. #endif
  16437. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16438. TEST_F(OpenStreamTest, Brotli) {
  16439. Client cli("127.0.0.1", port_);
  16440. auto handle =
  16441. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16442. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16443. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16444. }
  16445. #endif
  16446. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16447. TEST_F(OpenStreamTest, Zstd) {
  16448. Client cli("127.0.0.1", port_);
  16449. auto handle = cli.open_stream("GET", "/compressible", {},
  16450. {{"Accept-Encoding", "zstd"}});
  16451. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16452. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16453. }
  16454. #endif
  16455. #ifdef CPPHTTPLIB_SSL_ENABLED
  16456. class SSLOpenStreamTest : public ::testing::Test {
  16457. protected:
  16458. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16459. void SetUp() override {
  16460. svr_.Get("/hello", [](const Request &, Response &res) {
  16461. res.set_content("Hello SSL World!", "text/plain");
  16462. });
  16463. svr_.Get("/chunked", [](const Request &, Response &res) {
  16464. res.set_chunked_content_provider("text/plain",
  16465. [](size_t offset, DataSink &sink) {
  16466. if (offset < 15) {
  16467. sink.write("chunk", 5);
  16468. return true;
  16469. }
  16470. sink.done();
  16471. return true;
  16472. });
  16473. });
  16474. svr_.Post("/echo", [](const Request &req, Response &res) {
  16475. res.set_content(req.body, req.get_header_value("Content-Type"));
  16476. });
  16477. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16478. std::string body = req.body;
  16479. res.set_chunked_content_provider(
  16480. "text/plain", [body](size_t offset, DataSink &sink) {
  16481. if (offset < body.size()) {
  16482. sink.write(body.data() + offset, body.size() - offset);
  16483. }
  16484. sink.done();
  16485. return true;
  16486. });
  16487. });
  16488. port_ = svr_.bind_to_any_port("127.0.0.1");
  16489. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16490. svr_.wait_until_ready();
  16491. }
  16492. void TearDown() override {
  16493. svr_.stop();
  16494. if (thread_.joinable()) thread_.join();
  16495. }
  16496. SSLServer svr_;
  16497. std::thread thread_;
  16498. int port_ = 0;
  16499. };
  16500. TEST_F(SSLOpenStreamTest, Basic) {
  16501. SSLClient cli("127.0.0.1", port_);
  16502. cli.enable_server_certificate_verification(false);
  16503. auto handle = cli.open_stream("GET", "/hello");
  16504. ASSERT_TRUE(handle.is_valid());
  16505. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16506. }
  16507. TEST_F(SSLOpenStreamTest, Chunked) {
  16508. SSLClient cli("127.0.0.1", port_);
  16509. cli.enable_server_certificate_verification(false);
  16510. auto handle = cli.open_stream("GET", "/chunked");
  16511. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16512. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16513. "Transfer-Encoding") == "chunked");
  16514. auto body = read_all(handle);
  16515. EXPECT_EQ("chunkchunkchunk", body);
  16516. }
  16517. TEST_F(SSLOpenStreamTest, Post) {
  16518. SSLClient cli("127.0.0.1", port_);
  16519. cli.enable_server_certificate_verification(false);
  16520. auto handle =
  16521. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16522. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16523. EXPECT_EQ(200, handle.response->status);
  16524. auto body = read_all(handle);
  16525. EXPECT_EQ("Hello SSL POST", body);
  16526. }
  16527. TEST_F(SSLOpenStreamTest, PostChunked) {
  16528. SSLClient cli("127.0.0.1", port_);
  16529. cli.enable_server_certificate_verification(false);
  16530. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16531. "Chunked SSL Data", "text/plain");
  16532. ASSERT_TRUE(handle.is_valid());
  16533. EXPECT_EQ(200, handle.response->status);
  16534. auto body = read_all(handle);
  16535. EXPECT_EQ("Chunked SSL Data", body);
  16536. }
  16537. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16538. // Content-Length is terminated by the server closing the connection. When the
  16539. // SSL peer sends a close_notify after the body, the client must treat it as a
  16540. // clean EOF and return a successful response rather than an error.
  16541. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16543. ASSERT_TRUE(svr.is_valid());
  16544. svr.set_keep_alive_max_count(1);
  16545. const std::string expected_body = "Hello from connection-close response!";
  16546. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16547. res.set_content_provider("text/plain",
  16548. [&](size_t offset, DataSink &sink) -> bool {
  16549. if (offset < expected_body.size()) {
  16550. sink.write(expected_body.data() + offset,
  16551. expected_body.size() - offset);
  16552. }
  16553. sink.done();
  16554. return true;
  16555. });
  16556. });
  16557. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16558. auto se = detail::scope_exit([&] {
  16559. svr.stop();
  16560. listen_thread.join();
  16561. ASSERT_FALSE(svr.is_running());
  16562. });
  16563. svr.wait_until_ready();
  16564. SSLClient cli(HOST, PORT);
  16565. cli.enable_server_certificate_verification(false);
  16566. auto res = cli.Get("/no-content-length");
  16567. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16568. EXPECT_EQ(StatusCode::OK_200, res->status);
  16569. EXPECT_EQ(expected_body, res->body);
  16570. }
  16571. #endif // CPPHTTPLIB_SSL_ENABLED
  16572. //==============================================================================
  16573. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16574. // results for various scenarios.
  16575. //==============================================================================
  16576. TEST(ParityTest, GetVsOpenStream) {
  16577. Server svr;
  16578. const std::string path = "/parity";
  16579. const std::string content = "Parity test content: hello world";
  16580. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16581. res.set_content(content, "text/plain");
  16582. });
  16583. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16584. auto se = detail::scope_exit([&] {
  16585. svr.stop();
  16586. t.join();
  16587. ASSERT_FALSE(svr.is_running());
  16588. });
  16589. svr.wait_until_ready();
  16590. Client cli(HOST, PORT);
  16591. // Non-stream path
  16592. auto r1 = cli.Get(path);
  16593. ASSERT_TRUE(r1);
  16594. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16595. // Stream path
  16596. auto h = cli.open_stream("GET", path);
  16597. ASSERT_TRUE(h.is_valid());
  16598. EXPECT_EQ(r1->body, read_all(h));
  16599. }
  16600. // Helper to compress data with provided compressor type T
  16601. template <typename Compressor>
  16602. static std::string compress_payload_for_parity(const std::string &in) {
  16603. std::string out;
  16604. Compressor compressor;
  16605. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16606. [&](const char *data, size_t n) {
  16607. out.append(data, n);
  16608. return true;
  16609. });
  16610. EXPECT_TRUE(ok);
  16611. return out;
  16612. }
  16613. // Helper function for compression parity tests
  16614. template <typename Compressor>
  16615. static void test_compression_parity(const std::string &original,
  16616. const std::string &path,
  16617. const std::string &encoding) {
  16618. const std::string compressed =
  16619. compress_payload_for_parity<Compressor>(original);
  16620. Server svr;
  16621. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16622. res.set_content(compressed, "application/octet-stream");
  16623. res.set_header("Content-Encoding", encoding);
  16624. });
  16625. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16626. auto se = detail::scope_exit([&] {
  16627. svr.stop();
  16628. t.join();
  16629. ASSERT_FALSE(svr.is_running());
  16630. });
  16631. svr.wait_until_ready();
  16632. Client cli(HOST, PORT);
  16633. // Non-streaming
  16634. {
  16635. auto res = cli.Get(path);
  16636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16637. EXPECT_EQ(StatusCode::OK_200, res->status);
  16638. EXPECT_EQ(original, res->body);
  16639. }
  16640. // Streaming
  16641. {
  16642. auto h = cli.open_stream("GET", path);
  16643. ASSERT_TRUE(h.is_valid());
  16644. EXPECT_EQ(original, read_all(h));
  16645. }
  16646. }
  16647. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16648. TEST(ParityTest, Gzip) {
  16649. test_compression_parity<detail::gzip_compressor>(
  16650. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16651. }
  16652. #endif
  16653. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16654. TEST(ParityTest, Brotli) {
  16655. test_compression_parity<detail::brotli_compressor>(
  16656. "Hello, brotli parity test payload", "/parity-br", "br");
  16657. }
  16658. #endif
  16659. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16660. TEST(ParityTest, Zstd) {
  16661. test_compression_parity<detail::zstd_compressor>(
  16662. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16663. }
  16664. #endif
  16665. //==============================================================================
  16666. // New Stream API Tests
  16667. //==============================================================================
  16668. inline std::string read_body(httplib::stream::Result &result) {
  16669. std::string body;
  16670. while (result.next()) {
  16671. body.append(result.data(), result.size());
  16672. }
  16673. return body;
  16674. }
  16675. TEST(ClientConnectionTest, Basic) {
  16676. httplib::ClientConnection conn;
  16677. EXPECT_FALSE(conn.is_open());
  16678. conn.sock = 1;
  16679. EXPECT_TRUE(conn.is_open());
  16680. httplib::ClientConnection conn2(std::move(conn));
  16681. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16682. conn2.sock = INVALID_SOCKET;
  16683. }
  16684. // Unified test server for all stream::* tests
  16685. class StreamApiTest : public ::testing::Test {
  16686. protected:
  16687. void SetUp() override {
  16688. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16689. res.set_content("Hello World!", "text/plain");
  16690. });
  16691. svr_.Get("/echo-params",
  16692. [](const httplib::Request &req, httplib::Response &res) {
  16693. std::string r;
  16694. for (const auto &p : req.params) {
  16695. if (!r.empty()) r += "&";
  16696. r += p.first + "=" + p.second;
  16697. }
  16698. res.set_content(r, "text/plain");
  16699. });
  16700. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16701. res.set_content(req.body, req.get_header_value("Content-Type"));
  16702. });
  16703. svr_.Post("/echo-headers",
  16704. [](const httplib::Request &req, httplib::Response &res) {
  16705. std::string r;
  16706. for (const auto &h : req.headers)
  16707. r += h.first + ": " + h.second + "\n";
  16708. res.set_content(r, "text/plain");
  16709. });
  16710. svr_.Post("/echo-params",
  16711. [](const httplib::Request &req, httplib::Response &res) {
  16712. std::string r = "params:";
  16713. for (const auto &p : req.params)
  16714. r += p.first + "=" + p.second + ";";
  16715. res.set_content(r + " body:" + req.body, "text/plain");
  16716. });
  16717. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16718. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16719. });
  16720. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16721. res.set_content("PUT:" + req.body, "text/plain");
  16722. });
  16723. svr_.Patch("/echo",
  16724. [](const httplib::Request &req, httplib::Response &res) {
  16725. res.set_content("PATCH:" + req.body, "text/plain");
  16726. });
  16727. svr_.Delete(
  16728. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16729. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16730. "text/plain");
  16731. });
  16732. svr_.Get("/head-test",
  16733. [](const httplib::Request &, httplib::Response &res) {
  16734. res.set_content("body for HEAD", "text/plain");
  16735. });
  16736. svr_.Options("/options",
  16737. [](const httplib::Request &, httplib::Response &res) {
  16738. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16739. });
  16740. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16741. svr_.wait_until_ready();
  16742. }
  16743. void TearDown() override {
  16744. svr_.stop();
  16745. if (thread_.joinable()) thread_.join();
  16746. }
  16747. httplib::Server svr_;
  16748. std::thread thread_;
  16749. };
  16750. // stream::Get tests
  16751. TEST_F(StreamApiTest, GetBasic) {
  16752. httplib::Client cli(HOST, PORT);
  16753. auto result = httplib::stream::Get(cli, "/hello");
  16754. ASSERT_TRUE(result.is_valid());
  16755. EXPECT_EQ(200, result.status());
  16756. EXPECT_EQ("Hello World!", read_body(result));
  16757. }
  16758. TEST_F(StreamApiTest, GetWithParams) {
  16759. httplib::Client cli(HOST, PORT);
  16760. httplib::Params params{{"foo", "bar"}};
  16761. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16762. ASSERT_TRUE(result.is_valid());
  16763. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16764. }
  16765. TEST_F(StreamApiTest, GetConnectionError) {
  16766. httplib::Client cli(HOST, 9999);
  16767. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16768. }
  16769. TEST_F(StreamApiTest, Get404) {
  16770. httplib::Client cli(HOST, PORT);
  16771. auto result = httplib::stream::Get(cli, "/nonexistent");
  16772. EXPECT_TRUE(result.is_valid());
  16773. EXPECT_EQ(404, result.status());
  16774. }
  16775. // stream::Post tests
  16776. TEST_F(StreamApiTest, PostBasic) {
  16777. httplib::Client cli(HOST, PORT);
  16778. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16779. "application/json");
  16780. ASSERT_TRUE(result.is_valid());
  16781. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16782. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16783. }
  16784. TEST_F(StreamApiTest, PostWithHeaders) {
  16785. httplib::Client cli(HOST, PORT);
  16786. httplib::Headers headers{{"X-Custom", "value"}};
  16787. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16788. "text/plain");
  16789. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16790. }
  16791. TEST_F(StreamApiTest, PostWithParams) {
  16792. httplib::Client cli(HOST, PORT);
  16793. httplib::Params params{{"k", "v"}};
  16794. auto result =
  16795. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16796. auto body = read_body(result);
  16797. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16798. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16799. }
  16800. TEST_F(StreamApiTest, PostLarge) {
  16801. httplib::Client cli(HOST, PORT);
  16802. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16803. size_t total = 0;
  16804. while (result.next()) {
  16805. total += result.size();
  16806. }
  16807. EXPECT_EQ(100u * 1024u, total);
  16808. }
  16809. // stream::Put/Patch tests
  16810. TEST_F(StreamApiTest, PutAndPatch) {
  16811. httplib::Client cli(HOST, PORT);
  16812. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16813. EXPECT_EQ("PUT:test", read_body(put));
  16814. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16815. EXPECT_EQ("PATCH:test", read_body(patch));
  16816. }
  16817. // stream::Delete tests
  16818. TEST_F(StreamApiTest, Delete) {
  16819. httplib::Client cli(HOST, PORT);
  16820. auto del1 = httplib::stream::Delete(cli, "/resource");
  16821. EXPECT_EQ("Deleted", read_body(del1));
  16822. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16823. EXPECT_EQ("Deleted:data", read_body(del2));
  16824. }
  16825. // stream::Head/Options tests
  16826. TEST_F(StreamApiTest, HeadAndOptions) {
  16827. httplib::Client cli(HOST, PORT);
  16828. auto head = httplib::stream::Head(cli, "/head-test");
  16829. EXPECT_TRUE(head.is_valid());
  16830. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16831. auto opts = httplib::stream::Options(cli, "/options");
  16832. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16833. }
  16834. // SSL stream::* tests
  16835. #ifdef CPPHTTPLIB_SSL_ENABLED
  16836. class SSLStreamApiTest : public ::testing::Test {
  16837. protected:
  16838. void SetUp() override {
  16839. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16840. res.set_content("Hello SSL!", "text/plain");
  16841. });
  16842. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16843. res.set_content(req.body, "text/plain");
  16844. });
  16845. port_ = svr_.bind_to_any_port("127.0.0.1");
  16846. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16847. svr_.wait_until_ready();
  16848. }
  16849. void TearDown() override {
  16850. svr_.stop();
  16851. if (thread_.joinable()) thread_.join();
  16852. }
  16853. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16854. std::thread thread_;
  16855. int port_ = 0;
  16856. };
  16857. TEST_F(SSLStreamApiTest, GetAndPost) {
  16858. httplib::SSLClient cli("127.0.0.1", port_);
  16859. cli.enable_server_certificate_verification(false);
  16860. auto get = httplib::stream::Get(cli, "/hello");
  16861. EXPECT_EQ("Hello SSL!", read_body(get));
  16862. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16863. EXPECT_EQ("test", read_body(post));
  16864. }
  16865. #endif
  16866. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16867. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16868. // BodyReader
  16869. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16870. // Test that read timeout during streaming is detected
  16871. // Use a large content-length response where server delays mid-stream
  16872. Server svr;
  16873. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16874. // Send a large response with delay in the middle
  16875. res.set_content_provider(
  16876. 1000, // content_length
  16877. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16878. if (offset < 100) {
  16879. // Send first 100 bytes immediately
  16880. std::string data(100, 'A');
  16881. sink.write(data.c_str(), data.size());
  16882. return true;
  16883. }
  16884. // Then delay longer than client timeout
  16885. std::this_thread::sleep_for(std::chrono::seconds(3));
  16886. std::string data(900, 'B');
  16887. sink.write(data.c_str(), data.size());
  16888. return true;
  16889. });
  16890. });
  16891. auto port = 8091;
  16892. std::thread t([&]() { svr.listen("localhost", port); });
  16893. svr.wait_until_ready();
  16894. Client cli("localhost", port);
  16895. cli.set_read_timeout(1, 0); // 1 second timeout
  16896. auto handle = cli.open_stream("GET", "/slow-stream");
  16897. ASSERT_TRUE(handle.is_valid());
  16898. char buf[256];
  16899. ssize_t total = 0;
  16900. ssize_t n;
  16901. bool got_error = false;
  16902. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16903. total += n;
  16904. }
  16905. if (n < 0) {
  16906. got_error = true;
  16907. // Should be timeout or read error
  16908. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16909. handle.get_read_error() == Error::Read)
  16910. << "Actual error: " << to_string(handle.get_read_error());
  16911. }
  16912. // Either we got an error, or we got less data than expected
  16913. EXPECT_TRUE(got_error || total < 1000)
  16914. << "Expected timeout but got all " << total << " bytes";
  16915. svr.stop();
  16916. t.join();
  16917. }
  16918. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16919. // Test connection closed detection via BodyReader
  16920. Server svr;
  16921. std::atomic<bool> close_now{false};
  16922. svr.Get("/will-close", [&](const Request &, Response &res) {
  16923. res.set_content_provider(
  16924. 10000, // Large content_length that we won't fully send
  16925. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16926. if (offset < 100) {
  16927. std::string data(100, 'X');
  16928. sink.write(data.c_str(), data.size());
  16929. return true;
  16930. }
  16931. // Wait for signal then abort
  16932. while (!close_now) {
  16933. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16934. }
  16935. return false; // Abort - server will close connection
  16936. });
  16937. });
  16938. auto port = 8092;
  16939. std::thread t([&]() { svr.listen("localhost", port); });
  16940. svr.wait_until_ready();
  16941. Client cli("localhost", port);
  16942. auto handle = cli.open_stream("GET", "/will-close");
  16943. ASSERT_TRUE(handle.is_valid());
  16944. char buf[256];
  16945. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16946. EXPECT_GT(n, 0) << "First read should succeed";
  16947. // Signal server to close
  16948. close_now = true;
  16949. // Keep reading until error or EOF
  16950. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16951. // Keep reading
  16952. }
  16953. // Should get an error since content_length wasn't satisfied
  16954. if (n < 0) {
  16955. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16956. handle.get_read_error() == Error::Read)
  16957. << "Actual error: " << to_string(handle.get_read_error());
  16958. }
  16959. svr.stop();
  16960. t.join();
  16961. }
  16962. #ifdef CPPHTTPLIB_SSL_ENABLED
  16963. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16964. // Test that read timeout during SSL streaming is detected
  16965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16966. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16967. res.set_content_provider(
  16968. 1000, "text/plain",
  16969. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16970. if (offset < 100) {
  16971. std::string data(100, 'A');
  16972. sink.write(data.c_str(), data.size());
  16973. return true;
  16974. }
  16975. std::this_thread::sleep_for(std::chrono::seconds(3));
  16976. std::string data(900, 'B');
  16977. sink.write(data.c_str(), data.size());
  16978. return true;
  16979. });
  16980. });
  16981. auto port = 8093;
  16982. std::thread t([&]() { svr.listen("localhost", port); });
  16983. svr.wait_until_ready();
  16984. SSLClient cli("localhost", port);
  16985. cli.enable_server_certificate_verification(false);
  16986. cli.set_read_timeout(1, 0); // 1 second timeout
  16987. auto handle = cli.open_stream("GET", "/slow-stream");
  16988. ASSERT_TRUE(handle.is_valid());
  16989. char buf[256];
  16990. ssize_t total = 0;
  16991. ssize_t n;
  16992. bool got_error = false;
  16993. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16994. total += n;
  16995. }
  16996. if (n < 0) {
  16997. got_error = true;
  16998. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16999. handle.get_read_error() == Error::Read)
  17000. << "Actual error: " << to_string(handle.get_read_error());
  17001. }
  17002. EXPECT_TRUE(got_error || total < 1000)
  17003. << "Expected timeout but got all " << total << " bytes";
  17004. svr.stop();
  17005. t.join();
  17006. }
  17007. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17008. // Test SSL connection closed detection
  17009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17010. std::atomic<bool> close_now{false};
  17011. svr.Get("/will-close", [&](const Request &, Response &res) {
  17012. res.set_content_provider(
  17013. 10000, "text/plain",
  17014. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17015. if (offset < 100) {
  17016. std::string data(100, 'X');
  17017. sink.write(data.c_str(), data.size());
  17018. return true;
  17019. }
  17020. while (!close_now) {
  17021. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17022. }
  17023. return false;
  17024. });
  17025. });
  17026. auto port = 8094;
  17027. std::thread t([&]() { svr.listen("localhost", port); });
  17028. svr.wait_until_ready();
  17029. SSLClient cli("localhost", port);
  17030. cli.enable_server_certificate_verification(false);
  17031. auto handle = cli.open_stream("GET", "/will-close");
  17032. ASSERT_TRUE(handle.is_valid());
  17033. char buf[256];
  17034. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17035. EXPECT_GT(n, 0);
  17036. // Signal server to close
  17037. close_now = true;
  17038. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17039. // Keep reading
  17040. }
  17041. if (n < 0) {
  17042. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17043. handle.get_read_error() == Error::Read)
  17044. << "Actual error: " << to_string(handle.get_read_error());
  17045. }
  17046. svr.stop();
  17047. t.join();
  17048. }
  17049. #endif
  17050. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17051. using namespace httplib;
  17052. // Create a test file
  17053. const char *fname = "etag_testfile.txt";
  17054. const char *content = "etag-content";
  17055. {
  17056. std::ofstream ofs(fname);
  17057. ofs << content;
  17058. ASSERT_TRUE(ofs.good());
  17059. }
  17060. Server svr;
  17061. svr.set_mount_point("/static", ".");
  17062. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17063. svr.wait_until_ready();
  17064. Client cli(HOST, PORT);
  17065. // First request: should get 200 with ETag header
  17066. auto res1 = cli.Get("/static/etag_testfile.txt");
  17067. ASSERT_TRUE(res1);
  17068. ASSERT_EQ(200, res1->status);
  17069. ASSERT_TRUE(res1->has_header("ETag"));
  17070. std::string etag = res1->get_header_value("ETag");
  17071. EXPECT_FALSE(etag.empty());
  17072. // Verify ETag format: W/"hex-hex"
  17073. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17074. EXPECT_EQ('W', etag[0]);
  17075. EXPECT_EQ('/', etag[1]);
  17076. EXPECT_EQ('"', etag[2]);
  17077. EXPECT_EQ('"', etag.back());
  17078. // Exact match: expect 304 Not Modified
  17079. Headers h2 = {{"If-None-Match", etag}};
  17080. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17081. ASSERT_TRUE(res2);
  17082. EXPECT_EQ(304, res2->status);
  17083. // Wildcard match: expect 304 Not Modified
  17084. Headers h3 = {{"If-None-Match", "*"}};
  17085. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17086. ASSERT_TRUE(res3);
  17087. EXPECT_EQ(304, res3->status);
  17088. // Non-matching ETag: expect 200
  17089. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17090. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17091. ASSERT_TRUE(res4);
  17092. EXPECT_EQ(200, res4->status);
  17093. // Multiple ETags with one matching: expect 304
  17094. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17095. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17096. ASSERT_TRUE(res5);
  17097. EXPECT_EQ(304, res5->status);
  17098. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17099. // that equivalent to the single comma-separated list above, so the match on
  17100. // the second line must still be found.
  17101. Headers h6;
  17102. h6.emplace("If-None-Match", "W/\"other\"");
  17103. h6.emplace("If-None-Match", etag);
  17104. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17105. ASSERT_TRUE(res6);
  17106. EXPECT_EQ(304, res6->status);
  17107. svr.stop();
  17108. t.join();
  17109. std::remove(fname);
  17110. }
  17111. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17112. using namespace httplib;
  17113. Server svr;
  17114. svr.set_mount_point("/static", ".");
  17115. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17116. svr.wait_until_ready();
  17117. Client cli(HOST, PORT);
  17118. // Send If-None-Match: * to a non-existent file
  17119. Headers h = {{"If-None-Match", "*"}};
  17120. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17122. EXPECT_EQ(404, res->status);
  17123. svr.stop();
  17124. t.join();
  17125. }
  17126. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17127. using namespace httplib;
  17128. // Create a test file
  17129. const char *fname = "etag_boundary_testfile.txt";
  17130. const char *content = "boundary-test";
  17131. {
  17132. std::ofstream ofs(fname);
  17133. ofs << content;
  17134. ASSERT_TRUE(ofs.good());
  17135. }
  17136. Server svr;
  17137. svr.set_mount_point("/static", ".");
  17138. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17139. svr.wait_until_ready();
  17140. Client cli(HOST, PORT);
  17141. // Get the actual ETag
  17142. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17143. ASSERT_TRUE(res1);
  17144. ASSERT_EQ(200, res1->status);
  17145. ASSERT_TRUE(res1->has_header("ETag"));
  17146. std::string etag = res1->get_header_value("ETag");
  17147. // Test 1: Very long ETag value (longer than actual ETag)
  17148. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17149. Headers h1 = {{"If-None-Match", "W/"
  17150. "\"very-long-etag-value-that-is-much-longer-"
  17151. "than-the-actual-etag-value\""}};
  17152. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17153. ASSERT_TRUE(res2);
  17154. EXPECT_EQ(200, res2->status); // Should not match
  17155. // Test 2: Long string followed by wildcard
  17156. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17157. // string)
  17158. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17159. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17160. ASSERT_TRUE(res3);
  17161. EXPECT_EQ(304, res3->status); // Should match on "*"
  17162. // Test 3: Wildcard followed by long string
  17163. // Should match on "*" immediately and return 304
  17164. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17165. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17166. ASSERT_TRUE(res4);
  17167. EXPECT_EQ(304, res4->status); // Should match on "*"
  17168. // Test 4: Multiple long non-matching values
  17169. // Should NOT match and return 200 (test that all comparisons are safe)
  17170. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17171. "W/\"second-long-non-matching-value\", "
  17172. "W/\"third-long-non-matching-value\""}};
  17173. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17174. ASSERT_TRUE(res5);
  17175. EXPECT_EQ(200, res5->status); // Should not match
  17176. // Test 5: Single character that is not "*" (edge case)
  17177. Headers h5 = {{"If-None-Match", "X"}};
  17178. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17179. ASSERT_TRUE(res6);
  17180. EXPECT_EQ(200, res6->status); // Should not match
  17181. svr.stop();
  17182. t.join();
  17183. std::remove(fname);
  17184. }
  17185. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17186. using namespace httplib;
  17187. // Create a test file
  17188. const char *fname = "ims_testfile.txt";
  17189. const char *content = "if-modified-since-test";
  17190. {
  17191. std::ofstream ofs(fname);
  17192. ofs << content;
  17193. ASSERT_TRUE(ofs.good());
  17194. }
  17195. Server svr;
  17196. svr.set_mount_point("/static", ".");
  17197. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17198. svr.wait_until_ready();
  17199. Client cli(HOST, PORT);
  17200. // First request: should get 200 with Last-Modified header
  17201. auto res1 = cli.Get("/static/ims_testfile.txt");
  17202. ASSERT_TRUE(res1);
  17203. ASSERT_EQ(200, res1->status);
  17204. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17205. std::string last_modified = res1->get_header_value("Last-Modified");
  17206. EXPECT_FALSE(last_modified.empty());
  17207. // If-Modified-Since with same time: expect 304
  17208. Headers h2 = {{"If-Modified-Since", last_modified}};
  17209. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17210. ASSERT_TRUE(res2);
  17211. EXPECT_EQ(304, res2->status);
  17212. // If-Modified-Since with future time: expect 304
  17213. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17214. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17215. ASSERT_TRUE(res3);
  17216. EXPECT_EQ(304, res3->status);
  17217. // If-Modified-Since with past time: expect 200
  17218. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17219. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17220. ASSERT_TRUE(res4);
  17221. EXPECT_EQ(200, res4->status);
  17222. // If-None-Match takes precedence over If-Modified-Since
  17223. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17224. ASSERT_TRUE(res1->has_header("ETag"));
  17225. std::string etag = res1->get_header_value("ETag");
  17226. Headers h5 = {{"If-None-Match", etag},
  17227. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17228. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17229. ASSERT_TRUE(res5);
  17230. EXPECT_EQ(304, res5->status);
  17231. svr.stop();
  17232. t.join();
  17233. std::remove(fname);
  17234. }
  17235. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17236. using namespace httplib;
  17237. Server svr;
  17238. // Endpoint that returns compressible content
  17239. svr.Get("/compressible", [](const Request &, Response &res) {
  17240. // Return a large enough body to trigger compression
  17241. std::string body(1000, 'a');
  17242. res.set_content(body, "text/plain");
  17243. });
  17244. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17245. svr.wait_until_ready();
  17246. Client cli(HOST, PORT);
  17247. // Request with gzip support: should get Vary header when compressed
  17248. cli.set_compress(true);
  17249. auto res1 = cli.Get("/compressible");
  17250. ASSERT_TRUE(res1);
  17251. EXPECT_EQ(200, res1->status);
  17252. // If Content-Encoding is set, Vary should also be set
  17253. if (res1->has_header("Content-Encoding")) {
  17254. EXPECT_TRUE(res1->has_header("Vary"));
  17255. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17256. }
  17257. // Request without Accept-Encoding header: should not have compression
  17258. Headers h_no_compress;
  17259. auto res2 = cli.Get("/compressible", h_no_compress);
  17260. ASSERT_TRUE(res2);
  17261. EXPECT_EQ(200, res2->status);
  17262. // Verify Vary header is present when compression is applied
  17263. // (the exact behavior depends on server configuration)
  17264. svr.stop();
  17265. t.join();
  17266. }
  17267. TEST(ETagTest, IfRangeWithETag) {
  17268. using namespace httplib;
  17269. // Create a test file with known content
  17270. const char *fname = "if_range_testfile.txt";
  17271. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17272. {
  17273. std::ofstream ofs(fname);
  17274. ofs << content;
  17275. ASSERT_TRUE(ofs.good());
  17276. }
  17277. Server svr;
  17278. svr.set_mount_point("/static", ".");
  17279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17280. svr.wait_until_ready();
  17281. Client cli(HOST, PORT);
  17282. // First request: get ETag
  17283. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17284. ASSERT_TRUE(res1);
  17285. ASSERT_EQ(200, res1->status);
  17286. ASSERT_TRUE(res1->has_header("ETag"));
  17287. std::string etag = res1->get_header_value("ETag");
  17288. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17289. // Since our server generates weak ETags (W/"..."), If-Range with our
  17290. // ETag should NOT result in partial content - it should return full content.
  17291. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17292. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17293. ASSERT_TRUE(res2);
  17294. // Weak ETag in If-Range -> full content (200), not partial (206)
  17295. EXPECT_EQ(200, res2->status);
  17296. EXPECT_EQ(content, res2->body);
  17297. EXPECT_FALSE(res2->has_header("Content-Range"));
  17298. // Range request with non-matching If-Range (ETag): should get 200 (full
  17299. // content)
  17300. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17301. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17302. ASSERT_TRUE(res3);
  17303. EXPECT_EQ(200, res3->status);
  17304. EXPECT_EQ(content, res3->body);
  17305. EXPECT_FALSE(res3->has_header("Content-Range"));
  17306. // Range request with strong ETag (hypothetical - our server doesn't generate
  17307. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17308. // should return full content)
  17309. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17310. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17311. ASSERT_TRUE(res4);
  17312. EXPECT_EQ(200, res4->status);
  17313. EXPECT_EQ(content, res4->body);
  17314. EXPECT_FALSE(res4->has_header("Content-Range"));
  17315. svr.stop();
  17316. t.join();
  17317. std::remove(fname);
  17318. }
  17319. TEST(ETagTest, IfRangeWithDate) {
  17320. using namespace httplib;
  17321. // Create a test file
  17322. const char *fname = "if_range_date_testfile.txt";
  17323. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17324. {
  17325. std::ofstream ofs(fname);
  17326. ofs << content;
  17327. ASSERT_TRUE(ofs.good());
  17328. }
  17329. Server svr;
  17330. svr.set_mount_point("/static", ".");
  17331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17332. svr.wait_until_ready();
  17333. Client cli(HOST, PORT);
  17334. // First request: get Last-Modified
  17335. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17336. ASSERT_TRUE(res1);
  17337. ASSERT_EQ(200, res1->status);
  17338. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17339. std::string last_modified = res1->get_header_value("Last-Modified");
  17340. // Range request with matching If-Range (date): should get 206
  17341. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17342. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17343. ASSERT_TRUE(res2);
  17344. EXPECT_EQ(206, res2->status);
  17345. EXPECT_EQ("FGHIJ", res2->body);
  17346. // Range request with old If-Range date: should get 200 (full content)
  17347. Headers h3 = {{"Range", "bytes=5-9"},
  17348. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17349. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17350. ASSERT_TRUE(res3);
  17351. EXPECT_EQ(200, res3->status);
  17352. EXPECT_EQ(content, res3->body);
  17353. // Range request with future If-Range date: should get 206
  17354. Headers h4 = {{"Range", "bytes=0-4"},
  17355. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17356. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17357. ASSERT_TRUE(res4);
  17358. EXPECT_EQ(206, res4->status);
  17359. EXPECT_EQ("ABCDE", res4->body);
  17360. svr.stop();
  17361. t.join();
  17362. std::remove(fname);
  17363. }
  17364. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17365. using namespace httplib;
  17366. const char *fname = "etag_malformed.txt";
  17367. const char *content = "malformed-etag";
  17368. {
  17369. std::ofstream ofs(fname);
  17370. ofs << content;
  17371. ASSERT_TRUE(ofs.good());
  17372. }
  17373. Server svr;
  17374. svr.set_mount_point("/static", ".");
  17375. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17376. svr.wait_until_ready();
  17377. Client cli(HOST, PORT);
  17378. // baseline: should get 200 and an ETag
  17379. auto res1 = cli.Get("/static/etag_malformed.txt");
  17380. ASSERT_TRUE(res1);
  17381. ASSERT_EQ(200, res1->status);
  17382. ASSERT_TRUE(res1->has_header("ETag"));
  17383. // Malformed ETag value (missing quotes) should be treated as non-matching
  17384. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17385. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17386. ASSERT_TRUE(res_bad);
  17387. EXPECT_EQ(200, res_bad->status);
  17388. // Whitespace-only header value should be considered invalid / non-matching
  17389. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17390. "Host: localhost\r\n"
  17391. "If-None-Match: \r\n"
  17392. "Connection: close\r\n"
  17393. "\r\n";
  17394. std::string out;
  17395. ASSERT_TRUE(send_request(5, raw_req, &out));
  17396. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17397. svr.stop();
  17398. t.join();
  17399. std::remove(fname);
  17400. }
  17401. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17402. using namespace httplib;
  17403. const char *fname = "ims_invalid_format.txt";
  17404. const char *content = "ims-bad-format";
  17405. {
  17406. std::ofstream ofs(fname);
  17407. ofs << content;
  17408. ASSERT_TRUE(ofs.good());
  17409. }
  17410. Server svr;
  17411. svr.set_mount_point("/static", ".");
  17412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17413. svr.wait_until_ready();
  17414. Client cli(HOST, PORT);
  17415. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17416. ASSERT_TRUE(res1);
  17417. ASSERT_EQ(200, res1->status);
  17418. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17419. // If-Modified-Since with invalid format should not result in 304
  17420. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17421. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17422. ASSERT_TRUE(res_bad);
  17423. EXPECT_EQ(200, res_bad->status);
  17424. // If-Range with invalid date format should be treated as mismatch -> full
  17425. // content (200)
  17426. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17427. {"If-Range", "invalid-date"}};
  17428. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17429. ASSERT_TRUE(res_ifrange);
  17430. EXPECT_EQ(200, res_ifrange->status);
  17431. svr.stop();
  17432. t.join();
  17433. std::remove(fname);
  17434. }
  17435. TEST(ETagTest, IfRangeWithMalformedETag) {
  17436. using namespace httplib;
  17437. const char *fname = "ifrange_malformed.txt";
  17438. const std::string content = "0123456789";
  17439. {
  17440. std::ofstream ofs(fname);
  17441. ofs << content;
  17442. ASSERT_TRUE(ofs.good());
  17443. }
  17444. Server svr;
  17445. svr.set_mount_point("/static", ".");
  17446. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17447. svr.wait_until_ready();
  17448. Client cli(HOST, PORT);
  17449. // First request: get ETag
  17450. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17451. ASSERT_TRUE(res1);
  17452. ASSERT_EQ(200, res1->status);
  17453. ASSERT_TRUE(res1->has_header("ETag"));
  17454. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17455. // full content (200)
  17456. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17457. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17458. ASSERT_TRUE(res2);
  17459. EXPECT_EQ(200, res2->status);
  17460. EXPECT_EQ(content, res2->body);
  17461. svr.stop();
  17462. t.join();
  17463. std::remove(fname);
  17464. }
  17465. TEST(ETagTest, ExtremeLargeDateValues) {
  17466. using namespace httplib;
  17467. const char *fname = "ims_extreme_date.txt";
  17468. const char *content = "ims-extreme-date";
  17469. {
  17470. std::ofstream ofs(fname);
  17471. ofs << content;
  17472. ASSERT_TRUE(ofs.good());
  17473. }
  17474. Server svr;
  17475. svr.set_mount_point("/static", ".");
  17476. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17477. svr.wait_until_ready();
  17478. Client cli(HOST, PORT);
  17479. auto res1 = cli.Get(std::string("/static/") + fname);
  17480. ASSERT_TRUE(res1);
  17481. ASSERT_EQ(200, res1->status);
  17482. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17483. // Extremely large year that may overflow date parsing routines.
  17484. Headers h_large_date = {
  17485. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17486. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17487. ASSERT_TRUE(res_bad);
  17488. // Expect server to treat this as invalid/mismatch and return full content
  17489. EXPECT_EQ(200, res_bad->status);
  17490. // If-Range with extremely large date should be treated as mismatch -> full
  17491. // content (200)
  17492. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17493. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17494. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17495. ASSERT_TRUE(res_ifrange);
  17496. EXPECT_EQ(200, res_ifrange->status);
  17497. svr.stop();
  17498. t.join();
  17499. std::remove(fname);
  17500. }
  17501. TEST(ETagTest, NegativeFileModificationTime) {
  17502. using namespace httplib;
  17503. const char *fname = "ims_negative_mtime.txt";
  17504. const std::string content = "negative-mtime";
  17505. {
  17506. std::ofstream ofs(fname);
  17507. ofs << content;
  17508. ASSERT_TRUE(ofs.good());
  17509. }
  17510. // Try to set file mtime to a negative value. This may fail on some
  17511. // platforms/filesystems; if it fails, the test will still verify server
  17512. // behaves safely by performing a regular conditional request.
  17513. #if defined(__APPLE__) || defined(__linux__)
  17514. bool set_negative = false;
  17515. do {
  17516. struct timeval times[2];
  17517. // access time: now
  17518. times[0].tv_sec = time(nullptr);
  17519. times[0].tv_usec = 0;
  17520. // modification time: negative (e.g., -1)
  17521. times[1].tv_sec = -1;
  17522. times[1].tv_usec = 0;
  17523. if (utimes(fname, times) == 0) { set_negative = true; }
  17524. } while (0);
  17525. #else
  17526. bool set_negative = false;
  17527. #endif
  17528. Server svr;
  17529. svr.set_mount_point("/static", ".");
  17530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17531. svr.wait_until_ready();
  17532. Client cli(HOST, PORT);
  17533. auto res1 = cli.Get(std::string("/static/") + fname);
  17534. ASSERT_TRUE(res1);
  17535. ASSERT_EQ(200, res1->status);
  17536. bool has_last_modified = res1->has_header("Last-Modified");
  17537. std::string last_modified;
  17538. if (has_last_modified) {
  17539. last_modified = res1->get_header_value("Last-Modified");
  17540. }
  17541. if (set_negative) {
  17542. // If we successfully set a negative mtime, ensure server returns a
  17543. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17544. // with an old date and ensure server handles it without crash.
  17545. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17546. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17547. ASSERT_TRUE(res2);
  17548. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17549. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17550. } else {
  17551. // Could not set negative mtime on this platform; fall back to verifying
  17552. // that normal invalid/malformed dates are treated safely (non-304).
  17553. Headers h_bad_date = {
  17554. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17555. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17556. ASSERT_TRUE(res_bad);
  17557. EXPECT_EQ(200, res_bad->status);
  17558. }
  17559. svr.stop();
  17560. t.join();
  17561. std::remove(fname);
  17562. }
  17563. //==============================================================================
  17564. // SSE Parsing Tests
  17565. //==============================================================================
  17566. class SSEParsingTest : public ::testing::Test {
  17567. protected:
  17568. // Test helper that mimics SSE parsing behavior
  17569. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17570. int &retry_ms) {
  17571. // Blank line signals end of event
  17572. if (line.empty() || line == "\r") { return true; }
  17573. // Lines starting with ':' are comments (ignored)
  17574. if (!line.empty() && line[0] == ':') { return false; }
  17575. // Find the colon separator
  17576. auto colon_pos = line.find(':');
  17577. if (colon_pos == std::string::npos) {
  17578. // Line with no colon is treated as field name with empty value
  17579. return false;
  17580. }
  17581. std::string field = line.substr(0, colon_pos);
  17582. std::string value;
  17583. // Value starts after colon, skip optional single space
  17584. if (colon_pos + 1 < line.size()) {
  17585. size_t value_start = colon_pos + 1;
  17586. if (line[value_start] == ' ') { value_start++; }
  17587. value = line.substr(value_start);
  17588. // Remove trailing \r if present
  17589. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17590. }
  17591. // Handle known fields
  17592. if (field == "event") {
  17593. msg.event = value;
  17594. } else if (field == "data") {
  17595. // Multiple data lines are concatenated with newlines
  17596. if (!msg.data.empty()) { msg.data += "\n"; }
  17597. msg.data += value;
  17598. } else if (field == "id") {
  17599. // Empty id is valid (clears the last event ID)
  17600. msg.id = value;
  17601. } else if (field == "retry") {
  17602. // Parse retry interval in milliseconds
  17603. {
  17604. int v = 0;
  17605. auto res =
  17606. detail::from_chars(value.data(), value.data() + value.size(), v);
  17607. if (res.ec == std::errc{}) { retry_ms = v; }
  17608. }
  17609. }
  17610. // Unknown fields are ignored per SSE spec
  17611. return false;
  17612. }
  17613. };
  17614. // Test: Single-line data
  17615. TEST_F(SSEParsingTest, SingleLineData) {
  17616. sse::SSEMessage msg;
  17617. int retry_ms = 3000;
  17618. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17619. EXPECT_EQ(msg.data, "hello");
  17620. EXPECT_EQ(msg.event, "message");
  17621. // Blank line ends event
  17622. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17623. }
  17624. // Test: Multi-line data
  17625. TEST_F(SSEParsingTest, MultiLineData) {
  17626. sse::SSEMessage msg;
  17627. int retry_ms = 3000;
  17628. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17629. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17630. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17631. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17632. }
  17633. // Test: Custom event types
  17634. TEST_F(SSEParsingTest, CustomEventType) {
  17635. sse::SSEMessage msg;
  17636. int retry_ms = 3000;
  17637. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17638. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17639. EXPECT_EQ(msg.event, "update");
  17640. EXPECT_EQ(msg.data, "payload");
  17641. }
  17642. // Test: Event ID handling
  17643. TEST_F(SSEParsingTest, EventIdHandling) {
  17644. sse::SSEMessage msg;
  17645. int retry_ms = 3000;
  17646. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17647. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17648. EXPECT_EQ(msg.id, "12345");
  17649. }
  17650. // Test: Empty event ID (clears last event ID)
  17651. TEST_F(SSEParsingTest, EmptyEventId) {
  17652. sse::SSEMessage msg;
  17653. msg.id = "previous";
  17654. int retry_ms = 3000;
  17655. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17656. EXPECT_EQ(msg.id, "");
  17657. }
  17658. // Test: Retry field parsing
  17659. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17660. sse::SSEMessage msg;
  17661. int retry_ms = 3000;
  17662. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17663. EXPECT_EQ(retry_ms, 5000);
  17664. }
  17665. // Test: Invalid retry value
  17666. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17667. sse::SSEMessage msg;
  17668. int retry_ms = 3000;
  17669. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17670. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17671. }
  17672. // Test: Comments (lines starting with :)
  17673. TEST_F(SSEParsingTest, CommentsIgnored) {
  17674. sse::SSEMessage msg;
  17675. int retry_ms = 3000;
  17676. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17677. EXPECT_EQ(msg.data, "");
  17678. EXPECT_EQ(msg.event, "message");
  17679. }
  17680. // Test: Colon in value
  17681. TEST_F(SSEParsingTest, ColonInValue) {
  17682. sse::SSEMessage msg;
  17683. int retry_ms = 3000;
  17684. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17685. EXPECT_EQ(msg.data, "hello:world:test");
  17686. }
  17687. // Test: Line with no colon (field name only)
  17688. TEST_F(SSEParsingTest, FieldNameOnly) {
  17689. sse::SSEMessage msg;
  17690. int retry_ms = 3000;
  17691. // According to SSE spec, this is treated as field name with empty value
  17692. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17693. // Since we don't recognize "data" without colon, data should be empty
  17694. EXPECT_EQ(msg.data, "");
  17695. }
  17696. // Test: Trailing \r handling
  17697. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17698. sse::SSEMessage msg;
  17699. int retry_ms = 3000;
  17700. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17701. EXPECT_EQ(msg.data, "hello");
  17702. }
  17703. // Test: Unknown fields ignored
  17704. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17705. sse::SSEMessage msg;
  17706. int retry_ms = 3000;
  17707. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17708. EXPECT_EQ(msg.data, "");
  17709. EXPECT_EQ(msg.event, "message");
  17710. }
  17711. // Test: Space after colon is optional
  17712. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17713. sse::SSEMessage msg1, msg2;
  17714. int retry_ms = 3000;
  17715. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17716. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17717. EXPECT_EQ(msg1.data, "hello");
  17718. EXPECT_EQ(msg2.data, "hello");
  17719. }
  17720. // Test: SSEMessage clear
  17721. TEST_F(SSEParsingTest, MessageClear) {
  17722. sse::SSEMessage msg;
  17723. msg.event = "custom";
  17724. msg.data = "some data";
  17725. msg.id = "123";
  17726. msg.clear();
  17727. EXPECT_EQ(msg.event, "message");
  17728. EXPECT_EQ(msg.data, "");
  17729. EXPECT_EQ(msg.id, "");
  17730. }
  17731. // Test: Complete event parsing
  17732. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17733. sse::SSEMessage msg;
  17734. int retry_ms = 3000;
  17735. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17736. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17737. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17738. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17739. // Blank line ends event
  17740. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17741. EXPECT_EQ(msg.event, "notification");
  17742. EXPECT_EQ(msg.id, "evt-42");
  17743. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17744. EXPECT_EQ(retry_ms, 1000);
  17745. }
  17746. //==============================================================================
  17747. // Integration Tests with Server
  17748. //==============================================================================
  17749. class SSEIntegrationTest : public ::testing::Test {
  17750. protected:
  17751. void SetUp() override {
  17752. stop_server_.store(false);
  17753. events_.clear();
  17754. server_ = httplib::detail::make_unique<Server>();
  17755. setup_server();
  17756. start_server();
  17757. }
  17758. void TearDown() override {
  17759. stop_server_.store(true);
  17760. event_cv_.notify_all();
  17761. server_->stop();
  17762. if (server_thread_.joinable()) { server_thread_.join(); }
  17763. }
  17764. void setup_server() {
  17765. // Simple SSE endpoint
  17766. server_->Get("/events", [this](const Request &req, Response &res) {
  17767. auto last_id = req.get_header_value("Last-Event-ID");
  17768. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17769. res.set_chunked_content_provider(
  17770. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17771. std::unique_lock<std::mutex> lock(event_mutex_);
  17772. if (event_cv_.wait_for(
  17773. lock, std::chrono::milliseconds(200), [this] {
  17774. return !events_.empty() || stop_server_.load();
  17775. })) {
  17776. if (stop_server_.load()) { return false; }
  17777. if (!events_.empty()) {
  17778. std::string event = events_.front();
  17779. events_.erase(events_.begin());
  17780. sink.write(event.data(), event.size());
  17781. return true;
  17782. }
  17783. }
  17784. return !stop_server_.load();
  17785. });
  17786. });
  17787. // Endpoint that returns error
  17788. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17789. res.status = 500;
  17790. res.set_content("Internal Server Error", "text/plain");
  17791. });
  17792. // Endpoint for custom event types
  17793. server_->Get("/custom-events", [](const Request &, Response &res) {
  17794. res.set_chunked_content_provider(
  17795. "text/event-stream", [](size_t offset, DataSink &sink) {
  17796. if (offset == 0) {
  17797. std::string event = "event: update\ndata: updated\n\n"
  17798. "event: delete\ndata: deleted\n\n";
  17799. sink.write(event.data(), event.size());
  17800. }
  17801. return false; // End stream after sending
  17802. });
  17803. });
  17804. }
  17805. void start_server() {
  17806. port_ = server_->bind_to_any_port(HOST);
  17807. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17808. // Wait for server to start
  17809. while (!server_->is_running()) {
  17810. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17811. }
  17812. }
  17813. int get_port() const { return port_; }
  17814. void send_event(const std::string &event) {
  17815. std::lock_guard<std::mutex> lock(event_mutex_);
  17816. events_.push_back(event);
  17817. event_cv_.notify_all();
  17818. }
  17819. std::unique_ptr<Server> server_;
  17820. std::thread server_thread_;
  17821. std::mutex event_mutex_;
  17822. std::condition_variable event_cv_;
  17823. std::vector<std::string> events_;
  17824. std::atomic<bool> stop_server_{false};
  17825. std::string last_received_event_id_;
  17826. int port_ = 0;
  17827. };
  17828. // Test: Successful connection and on_open callback
  17829. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17830. // Add a simple endpoint that sends one event and closes
  17831. server_->Get("/simple-event", [](const Request &, Response &res) {
  17832. res.set_chunked_content_provider(
  17833. "text/event-stream", [](size_t offset, DataSink &sink) {
  17834. if (offset == 0) {
  17835. std::string event = "data: hello\n\n";
  17836. sink.write(event.data(), event.size());
  17837. }
  17838. return false; // Close stream after sending
  17839. });
  17840. });
  17841. Client client("localhost", get_port());
  17842. sse::SSEClient sse(client, "/simple-event");
  17843. std::atomic<bool> open_called{false};
  17844. std::atomic<bool> message_received{false};
  17845. sse.on_open([&open_called]() { open_called.store(true); });
  17846. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17847. if (msg.data == "hello") { message_received.store(true); }
  17848. });
  17849. sse.set_reconnect_interval(100);
  17850. sse.set_max_reconnect_attempts(1);
  17851. // Start async
  17852. sse.start_async();
  17853. // Wait for message to be processed
  17854. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17855. sse.stop();
  17856. EXPECT_TRUE(open_called.load());
  17857. EXPECT_TRUE(message_received.load());
  17858. }
  17859. // Test: on_message callback
  17860. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17861. // Endpoint that sends multiple events then closes
  17862. server_->Get("/multi-event", [](const Request &, Response &res) {
  17863. res.set_chunked_content_provider(
  17864. "text/event-stream", [](size_t offset, DataSink &sink) {
  17865. if (offset == 0) {
  17866. std::string events = "data: message1\n\ndata: message2\n\n";
  17867. sink.write(events.data(), events.size());
  17868. }
  17869. return false;
  17870. });
  17871. });
  17872. Client client("localhost", get_port());
  17873. sse::SSEClient sse(client, "/multi-event");
  17874. std::vector<std::string> received_messages;
  17875. std::mutex messages_mutex;
  17876. sse.on_message([&](const sse::SSEMessage &msg) {
  17877. std::lock_guard<std::mutex> lock(messages_mutex);
  17878. received_messages.push_back(msg.data);
  17879. });
  17880. sse.set_reconnect_interval(100);
  17881. sse.set_max_reconnect_attempts(1);
  17882. sse.start_async();
  17883. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17884. sse.stop();
  17885. std::lock_guard<std::mutex> lock(messages_mutex);
  17886. EXPECT_GE(received_messages.size(), 2u);
  17887. if (received_messages.size() >= 2) {
  17888. EXPECT_EQ(received_messages[0], "message1");
  17889. EXPECT_EQ(received_messages[1], "message2");
  17890. }
  17891. }
  17892. // Test: on_event for specific types
  17893. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17894. Client client("localhost", get_port());
  17895. sse::SSEClient sse(client, "/custom-events");
  17896. std::atomic<bool> update_received{false};
  17897. std::atomic<bool> delete_received{false};
  17898. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17899. if (msg.data == "updated") { update_received.store(true); }
  17900. });
  17901. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17902. if (msg.data == "deleted") { delete_received.store(true); }
  17903. });
  17904. sse.set_max_reconnect_attempts(1);
  17905. sse.start_async();
  17906. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17907. sse.stop();
  17908. EXPECT_TRUE(update_received.load());
  17909. EXPECT_TRUE(delete_received.load());
  17910. }
  17911. // Test: on_error callback on connection failure
  17912. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17913. // Connect to a non-existent port
  17914. Client client("localhost", 59999);
  17915. sse::SSEClient sse(client, "/events");
  17916. std::atomic<bool> error_called{false};
  17917. Error received_error = Error::Success;
  17918. sse.on_error([&](Error err) {
  17919. error_called.store(true);
  17920. received_error = err;
  17921. });
  17922. sse.set_reconnect_interval(50);
  17923. sse.set_max_reconnect_attempts(1);
  17924. sse.start_async();
  17925. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17926. sse.stop();
  17927. EXPECT_TRUE(error_called.load());
  17928. EXPECT_NE(received_error, Error::Success);
  17929. }
  17930. // Test: Last-Event-ID header sent on reconnect
  17931. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17932. // Endpoint that sends event with ID
  17933. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17934. res.set_chunked_content_provider(
  17935. "text/event-stream", [](size_t offset, DataSink &sink) {
  17936. if (offset == 0) {
  17937. std::string event = "id: evt-123\ndata: test\n\n";
  17938. sink.write(event.data(), event.size());
  17939. }
  17940. return false;
  17941. });
  17942. });
  17943. Client client("localhost", get_port());
  17944. sse::SSEClient sse(client, "/event-with-id");
  17945. std::atomic<bool> id_received{false};
  17946. sse.on_message([&](const sse::SSEMessage &msg) {
  17947. if (!msg.id.empty()) { id_received.store(true); }
  17948. });
  17949. sse.set_reconnect_interval(100);
  17950. sse.set_max_reconnect_attempts(1);
  17951. sse.start_async();
  17952. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17953. sse.stop();
  17954. EXPECT_TRUE(id_received.load());
  17955. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17956. }
  17957. // Test: Manual stop
  17958. TEST_F(SSEIntegrationTest, ManualStop) {
  17959. // Endpoint that sends one event and stays open briefly
  17960. std::atomic<bool> handler_running{true};
  17961. server_->Get("/stay-open", [&handler_running](const Request &,
  17962. Response &res) {
  17963. res.set_chunked_content_provider(
  17964. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17965. if (offset == 0) {
  17966. std::string event = "data: connected\n\n";
  17967. sink.write(event.data(), event.size());
  17968. }
  17969. // Keep connection open while handler_running is true
  17970. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17971. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17972. }
  17973. return false;
  17974. });
  17975. });
  17976. Client client("localhost", get_port());
  17977. sse::SSEClient sse(client, "/stay-open");
  17978. std::atomic<bool> connected{false};
  17979. sse.on_open([&connected]() { connected.store(true); });
  17980. sse.set_reconnect_interval(100);
  17981. sse.set_max_reconnect_attempts(1);
  17982. sse.start_async();
  17983. // Wait for connection to establish
  17984. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17985. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17986. }
  17987. EXPECT_TRUE(connected.load());
  17988. EXPECT_TRUE(sse.is_connected());
  17989. // Signal handler to stop
  17990. handler_running.store(false);
  17991. // Stop SSE client
  17992. sse.stop();
  17993. EXPECT_FALSE(sse.is_connected());
  17994. }
  17995. // Test: SSEClient with custom headers
  17996. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17997. // Setup a server endpoint that checks for custom header
  17998. std::atomic<bool> header_received{false};
  17999. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18000. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18001. header_received.store(true);
  18002. }
  18003. res.set_chunked_content_provider("text/event-stream",
  18004. [](size_t, DataSink &) { return false; });
  18005. });
  18006. Client client("localhost", get_port());
  18007. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18008. sse::SSEClient sse(client, "/header-check", headers);
  18009. sse.set_max_reconnect_attempts(1);
  18010. sse.start_async();
  18011. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18012. sse.stop();
  18013. EXPECT_TRUE(header_received.load());
  18014. }
  18015. // Test: Reconnect interval configuration
  18016. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18017. Client client("localhost", get_port());
  18018. sse::SSEClient sse(client, "/events");
  18019. auto &result = sse.set_reconnect_interval(500);
  18020. // Builder pattern should return reference to self
  18021. EXPECT_EQ(&result, &sse);
  18022. }
  18023. // Test: Max reconnect attempts
  18024. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18025. // Connect to non-existent port to force reconnects
  18026. Client client("localhost", 59998);
  18027. sse::SSEClient sse(client, "/events");
  18028. std::atomic<int> error_count{0};
  18029. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18030. sse.set_reconnect_interval(50);
  18031. sse.set_max_reconnect_attempts(2);
  18032. auto start = std::chrono::steady_clock::now();
  18033. sse.start(); // Blocking call
  18034. auto end = std::chrono::steady_clock::now();
  18035. // Should have stopped after 2 failed attempts
  18036. EXPECT_GE(error_count.load(), 2);
  18037. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18038. auto duration =
  18039. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18040. #ifdef _WIN32
  18041. // Windows is much slower for socket connection failures
  18042. EXPECT_LT(duration.count(), 7000);
  18043. #else
  18044. EXPECT_LT(duration.count(), 1000);
  18045. #endif
  18046. }
  18047. // Test: Multi-line data in integration
  18048. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18049. // Endpoint with multi-line data
  18050. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18051. res.set_chunked_content_provider(
  18052. "text/event-stream", [](size_t offset, DataSink &sink) {
  18053. if (offset == 0) {
  18054. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18055. sink.write(event.data(), event.size());
  18056. }
  18057. return false;
  18058. });
  18059. });
  18060. Client client("localhost", get_port());
  18061. sse::SSEClient sse(client, "/multiline-data");
  18062. std::string received_data;
  18063. std::mutex data_mutex;
  18064. sse.on_message([&](const sse::SSEMessage &msg) {
  18065. std::lock_guard<std::mutex> lock(data_mutex);
  18066. received_data = msg.data;
  18067. });
  18068. sse.set_reconnect_interval(100);
  18069. sse.set_max_reconnect_attempts(1);
  18070. sse.start_async();
  18071. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18072. sse.stop();
  18073. std::lock_guard<std::mutex> lock(data_mutex);
  18074. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18075. }
  18076. // Test: Auto-reconnect after server disconnection
  18077. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18078. std::atomic<int> connection_count{0};
  18079. std::atomic<int> message_count{0};
  18080. // Endpoint that sends one event and closes, forcing reconnect
  18081. server_->Get("/reconnect-test",
  18082. [&connection_count](const Request &, Response &res) {
  18083. connection_count.fetch_add(1);
  18084. res.set_chunked_content_provider(
  18085. "text/event-stream", [](size_t offset, DataSink &sink) {
  18086. if (offset == 0) {
  18087. std::string event = "data: hello\n\n";
  18088. sink.write(event.data(), event.size());
  18089. }
  18090. return false; // Close connection after sending
  18091. });
  18092. });
  18093. Client client("localhost", get_port());
  18094. sse::SSEClient sse(client, "/reconnect-test");
  18095. sse.on_message([&message_count](const sse::SSEMessage &) {
  18096. message_count.fetch_add(1);
  18097. });
  18098. sse.set_reconnect_interval(100);
  18099. sse.set_max_reconnect_attempts(3);
  18100. sse.start_async();
  18101. // Wait long enough for multiple reconnects
  18102. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18103. sse.stop();
  18104. // Should have connected multiple times (initial + reconnects)
  18105. EXPECT_GE(connection_count.load(), 2);
  18106. // Should have received messages from multiple connections
  18107. EXPECT_GE(message_count.load(), 2);
  18108. }
  18109. // Test: Last-Event-ID sent on reconnect
  18110. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18111. std::atomic<int> connection_count{0};
  18112. std::vector<std::string> received_last_event_ids;
  18113. std::mutex id_mutex;
  18114. // Endpoint that checks Last-Event-ID header and sends event with ID
  18115. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18116. int conn = connection_count.fetch_add(1);
  18117. // Capture the Last-Event-ID header from each connection
  18118. {
  18119. std::lock_guard<std::mutex> lock(id_mutex);
  18120. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18121. }
  18122. res.set_chunked_content_provider(
  18123. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18124. if (offset == 0) {
  18125. std::string event =
  18126. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18127. sink.write(event.data(), event.size());
  18128. }
  18129. return false;
  18130. });
  18131. });
  18132. Client client("localhost", get_port());
  18133. sse::SSEClient sse(client, "/reconnect-with-id");
  18134. sse.set_reconnect_interval(100);
  18135. sse.set_max_reconnect_attempts(3);
  18136. sse.start_async();
  18137. // Wait for at least 2 connections
  18138. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18139. sse.stop();
  18140. // Verify behavior
  18141. std::lock_guard<std::mutex> lock(id_mutex);
  18142. EXPECT_GE(received_last_event_ids.size(), 2u);
  18143. // First connection should have no Last-Event-ID
  18144. if (!received_last_event_ids.empty()) {
  18145. EXPECT_EQ(received_last_event_ids[0], "");
  18146. }
  18147. // Second connection should have Last-Event-ID from first connection
  18148. if (received_last_event_ids.size() >= 2) {
  18149. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18150. }
  18151. }
  18152. // Test: set_headers updates headers used on reconnect
  18153. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18154. std::vector<std::string> received_tokens;
  18155. std::mutex token_mutex;
  18156. // Endpoint that captures Authorization header
  18157. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18158. {
  18159. std::lock_guard<std::mutex> lock(token_mutex);
  18160. received_tokens.push_back(req.get_header_value("Authorization"));
  18161. }
  18162. res.set_chunked_content_provider(
  18163. "text/event-stream", [](size_t offset, DataSink &sink) {
  18164. if (offset == 0) {
  18165. std::string event = "data: hello\n\n";
  18166. sink.write(event.data(), event.size());
  18167. }
  18168. return false; // Close connection to trigger reconnect
  18169. });
  18170. });
  18171. Client client("localhost", get_port());
  18172. Headers headers = {{"Authorization", "Bearer old-token"}};
  18173. sse::SSEClient sse(client, "/auth-check", headers);
  18174. // Update headers on each successful connection
  18175. sse.on_open(
  18176. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18177. sse.set_reconnect_interval(100);
  18178. sse.set_max_reconnect_attempts(3);
  18179. sse.start_async();
  18180. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18181. sse.stop();
  18182. std::lock_guard<std::mutex> lock(token_mutex);
  18183. ASSERT_GE(received_tokens.size(), 2u);
  18184. // First connection uses original header
  18185. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18186. // Second connection uses updated header from set_headers
  18187. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18188. }
  18189. // Test: 401 allows reconnection (so on_error can refresh headers)
  18190. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18191. std::atomic<int> connection_count{0};
  18192. // Endpoint: returns 401 on first attempt, 200 on second
  18193. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18194. int conn = connection_count.fetch_add(1);
  18195. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18196. res.status = StatusCode::Unauthorized_401;
  18197. res.set_content("Unauthorized", "text/plain");
  18198. return;
  18199. }
  18200. res.set_chunked_content_provider(
  18201. "text/event-stream", [](size_t offset, DataSink &sink) {
  18202. if (offset == 0) {
  18203. std::string event = "data: authenticated\n\n";
  18204. sink.write(event.data(), event.size());
  18205. }
  18206. return false;
  18207. });
  18208. });
  18209. Client client("localhost", get_port());
  18210. Headers headers = {{"Authorization", "Bearer expired"}};
  18211. sse::SSEClient sse(client, "/auth-retry", headers);
  18212. std::atomic<bool> message_received{false};
  18213. // Refresh token on error
  18214. sse.on_error(
  18215. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18216. sse.on_message([&](const sse::SSEMessage &msg) {
  18217. if (msg.data == "authenticated") { message_received.store(true); }
  18218. });
  18219. sse.set_reconnect_interval(100);
  18220. sse.set_max_reconnect_attempts(3);
  18221. sse.start_async();
  18222. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18223. sse.stop();
  18224. // Should have reconnected after 401 and succeeded with new token
  18225. EXPECT_GE(connection_count.load(), 2);
  18226. EXPECT_TRUE(message_received.load());
  18227. }
  18228. TEST(Issue2318Test, EmptyHostString) {
  18229. {
  18230. httplib::Client cli_empty("", PORT);
  18231. auto res = cli_empty.Get("/");
  18232. ASSERT_FALSE(res);
  18233. EXPECT_EQ(httplib::Error::Connection, res.error());
  18234. }
  18235. {
  18236. httplib::Client cli(" ", PORT);
  18237. auto res = cli.Get("/");
  18238. ASSERT_FALSE(res);
  18239. EXPECT_EQ(httplib::Error::Connection, res.error());
  18240. }
  18241. }
  18242. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18243. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18244. Server svr;
  18245. // Set a small payload limit (1KB)
  18246. svr.set_payload_max_length(1024);
  18247. svr.Post("/test", [&](const Request &req, Response &res) {
  18248. res.set_content("Body size: " + std::to_string(req.body.size()),
  18249. "text/plain");
  18250. });
  18251. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18252. auto se = detail::scope_exit([&] {
  18253. svr.stop();
  18254. listen_thread.join();
  18255. });
  18256. svr.wait_until_ready();
  18257. // Create data that compresses well but exceeds limit when decompressed
  18258. // 8KB of repeated null bytes compresses to a very small size
  18259. std::string original_data(8 * 1024, '\0');
  18260. // Compress the data using gzip
  18261. std::string compressed_data;
  18262. detail::gzip_compressor compressor;
  18263. compressor.compress(original_data.data(), original_data.size(), true,
  18264. [&](const char *data, size_t size) {
  18265. compressed_data.append(data, size);
  18266. return true;
  18267. });
  18268. // Verify compression worked (compressed should be much smaller)
  18269. ASSERT_LT(compressed_data.size(), original_data.size());
  18270. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18271. // Send compressed data with Content-Encoding: gzip
  18272. Client cli(HOST, PORT);
  18273. Headers headers = {{"Content-Encoding", "gzip"}};
  18274. auto res =
  18275. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18276. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18278. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18279. }
  18280. #endif
  18281. // ============================================================================
  18282. // OpenSSL-Specific Tests
  18283. // ============================================================================
  18284. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18285. X509 *readCertificate(const std::string &strFileName) {
  18286. std::ifstream inStream(strFileName);
  18287. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18288. std::istreambuf_iterator<char>());
  18289. if (strCertPEM.empty()) return (nullptr);
  18290. BIO *pbCert = BIO_new(BIO_s_mem());
  18291. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18292. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18293. BIO_free(pbCert);
  18294. return (pCert);
  18295. }
  18296. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18297. std::ifstream inStream(strFileName);
  18298. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18299. std::istreambuf_iterator<char>());
  18300. if (strPrivateKeyPEM.empty()) return (nullptr);
  18301. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18302. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18303. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18304. BIO_free(pbPrivKey);
  18305. return (pPrivateKey);
  18306. }
  18307. TEST(BindServerTest, UpdateCerts) {
  18308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18309. int port = svr.bind_to_any_port("0.0.0.0");
  18310. ASSERT_TRUE(svr.is_valid());
  18311. ASSERT_TRUE(port > 0);
  18312. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18313. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18314. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18315. ASSERT_TRUE(cert != nullptr);
  18316. ASSERT_TRUE(ca_cert != nullptr);
  18317. ASSERT_TRUE(key != nullptr);
  18318. X509_STORE *cert_store = X509_STORE_new();
  18319. X509_STORE_add_cert(cert_store, ca_cert);
  18320. // svr.update_certs(cert, key, cert_store); // deprecated
  18321. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18322. CLIENT_CA_CERT_FILE);
  18323. ASSERT_TRUE(svr.is_valid());
  18324. svr.stop();
  18325. X509_STORE_free(cert_store);
  18326. X509_free(cert);
  18327. X509_free(ca_cert);
  18328. EVP_PKEY_free(key);
  18329. }
  18330. // Test that update_certs() updates client CA list correctly
  18331. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18332. // Start with file-based constructor
  18333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18334. ASSERT_TRUE(svr.is_valid());
  18335. // Initially no client CA list should be set
  18336. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18337. ASSERT_TRUE(ssl_ctx != nullptr);
  18338. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18339. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18340. EXPECT_EQ(0, count_before);
  18341. // Now update with client CA (PEM string)
  18342. std::string cert_pem, key_pem, ca_pem;
  18343. read_file(SERVER_CERT_FILE, cert_pem);
  18344. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18345. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18346. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18347. ASSERT_TRUE(svr.is_valid());
  18348. // Now client CA list should be set
  18349. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18350. ASSERT_TRUE(ca_list_after != nullptr);
  18351. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18352. }
  18353. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18354. // Test that the file-path SSLServer constructor properly sets the client CA
  18355. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18357. ASSERT_TRUE(svr.is_valid());
  18358. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18359. ASSERT_TRUE(ssl_ctx != nullptr);
  18360. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18361. ASSERT_TRUE(ca_list != nullptr);
  18362. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18363. }
  18364. #endif
  18365. // ============================================================================
  18366. // MbedTLS-Specific Tests
  18367. // ============================================================================
  18368. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18369. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18370. using namespace httplib::tls;
  18371. // Track if callback was invoked
  18372. bool callback_invoked = false;
  18373. // The callback receives void* ctx which is actually MbedTlsContext*
  18374. // We can access the mbedtls_ssl_config via the context
  18375. auto setup_callback = [&callback_invoked](void *ctx) {
  18376. callback_invoked = true;
  18377. // Cast to MbedTlsContext* to access the ssl config
  18378. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18379. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18380. // Use static variables to hold certificate data (simplified for test)
  18381. static mbedtls_x509_crt own_cert;
  18382. static mbedtls_pk_context own_key;
  18383. static mbedtls_x509_crt ca_chain;
  18384. static bool initialized = false;
  18385. if (!initialized) {
  18386. mbedtls_x509_crt_init(&own_cert);
  18387. mbedtls_pk_init(&own_key);
  18388. mbedtls_x509_crt_init(&ca_chain);
  18389. // Load server certificate
  18390. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18391. return false;
  18392. }
  18393. // Load server private key.
  18394. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18395. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18396. #if MBEDTLS_VERSION_MAJOR == 3
  18397. ,
  18398. mbedtls_ctr_drbg_random, nullptr
  18399. #endif
  18400. ) != 0) {
  18401. return false;
  18402. }
  18403. // Load CA chain for client verification
  18404. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18405. return false;
  18406. }
  18407. initialized = true;
  18408. }
  18409. // Configure the SSL config
  18410. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18411. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18412. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18413. // Set minimum TLS version using mbedTLS native API
  18414. #if MBEDTLS_VERSION_MAJOR >= 3
  18415. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18416. #else
  18417. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18418. MBEDTLS_SSL_MINOR_VERSION_3);
  18419. #endif
  18420. return true;
  18421. };
  18422. SSLServer svr(setup_callback);
  18423. ASSERT_TRUE(svr.is_valid());
  18424. ASSERT_TRUE(callback_invoked);
  18425. svr.Get("/test", [&](const Request &req, Response &res) {
  18426. res.set_content("test", "text/plain");
  18427. auto cert = req.peer_cert();
  18428. ASSERT_TRUE(static_cast<bool>(cert));
  18429. auto common_name = cert.subject_cn();
  18430. EXPECT_EQ("Common Name", common_name);
  18431. });
  18432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18433. auto se = detail::scope_exit([&] {
  18434. svr.stop();
  18435. t.join();
  18436. ASSERT_FALSE(svr.is_running());
  18437. });
  18438. svr.wait_until_ready();
  18439. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18440. cli.enable_server_certificate_verification(false);
  18441. cli.set_connection_timeout(30);
  18442. auto res = cli.Get("/test");
  18443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18444. ASSERT_EQ(StatusCode::OK_200, res->status);
  18445. }
  18446. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18447. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18448. // keep-alive SSL session, which reads through that config in
  18449. // mbedtls_ssl_close_notify.
  18450. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18452. ASSERT_TRUE(svr.is_valid());
  18453. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18454. res.set_content("test", "text/plain");
  18455. });
  18456. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18457. auto se = detail::scope_exit([&] {
  18458. svr.stop();
  18459. t.join();
  18460. ASSERT_FALSE(svr.is_running());
  18461. });
  18462. svr.wait_until_ready();
  18463. {
  18464. SSLClient cli(HOST, PORT);
  18465. cli.enable_server_certificate_verification(false);
  18466. cli.set_keep_alive(true);
  18467. auto res = cli.Get("/test");
  18468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18469. ASSERT_EQ(StatusCode::OK_200, res->status);
  18470. // cli is destructed here with the keep-alive SSL session still open.
  18471. }
  18472. }
  18473. #endif
  18474. // WebSocket Tests
  18475. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18476. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18477. // defining the meaning of these bits has been negotiated.
  18478. auto make_frame = [](uint8_t first_byte) {
  18479. std::string frame;
  18480. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18481. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18482. frame += "Hello";
  18483. return frame;
  18484. };
  18485. // RSV1 set (0x40)
  18486. {
  18487. detail::BufferStream strm;
  18488. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18489. ws::Opcode opcode;
  18490. std::string payload;
  18491. bool fin;
  18492. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18493. false, 1024));
  18494. }
  18495. // RSV2 set (0x20)
  18496. {
  18497. detail::BufferStream strm;
  18498. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18499. ws::Opcode opcode;
  18500. std::string payload;
  18501. bool fin;
  18502. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18503. false, 1024));
  18504. }
  18505. // RSV3 set (0x10)
  18506. {
  18507. detail::BufferStream strm;
  18508. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18509. ws::Opcode opcode;
  18510. std::string payload;
  18511. bool fin;
  18512. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18513. false, 1024));
  18514. }
  18515. // No RSV bits set - should succeed
  18516. {
  18517. detail::BufferStream strm;
  18518. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18519. ws::Opcode opcode;
  18520. std::string payload;
  18521. bool fin;
  18522. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18523. false, 1024));
  18524. EXPECT_EQ(ws::Opcode::Text, opcode);
  18525. EXPECT_EQ("Hello", payload);
  18526. EXPECT_TRUE(fin);
  18527. }
  18528. }
  18529. TEST(WebSocketTest, ControlFrameValidation) {
  18530. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18531. // payload length <= 125.
  18532. // Ping with FIN=0 - must be rejected
  18533. {
  18534. detail::BufferStream strm;
  18535. std::string frame;
  18536. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18537. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18538. strm.write(frame.data(), frame.size());
  18539. ws::Opcode opcode;
  18540. std::string payload;
  18541. bool fin;
  18542. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18543. false, 1024));
  18544. }
  18545. // Close with FIN=0 - must be rejected
  18546. {
  18547. detail::BufferStream strm;
  18548. std::string frame;
  18549. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18550. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18551. strm.write(frame.data(), frame.size());
  18552. ws::Opcode opcode;
  18553. std::string payload;
  18554. bool fin;
  18555. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18556. false, 1024));
  18557. }
  18558. // Ping with payload_len=126 (extended length) - must be rejected
  18559. {
  18560. detail::BufferStream strm;
  18561. std::string frame;
  18562. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18563. frame += static_cast<char>(126); // payload_len=126 (>125)
  18564. frame += static_cast<char>(0x00); // extended length high byte
  18565. frame += static_cast<char>(126); // extended length low byte
  18566. frame += std::string(126, 'x');
  18567. strm.write(frame.data(), frame.size());
  18568. ws::Opcode opcode;
  18569. std::string payload;
  18570. bool fin;
  18571. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18572. false, 1024));
  18573. }
  18574. // Ping with FIN=1 and payload_len=125 - should succeed
  18575. {
  18576. detail::BufferStream strm;
  18577. std::string frame;
  18578. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18579. frame += static_cast<char>(125); // payload_len=125
  18580. frame += std::string(125, 'x');
  18581. strm.write(frame.data(), frame.size());
  18582. ws::Opcode opcode;
  18583. std::string payload;
  18584. bool fin;
  18585. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18586. false, 1024));
  18587. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18588. EXPECT_EQ(125u, payload.size());
  18589. EXPECT_TRUE(fin);
  18590. }
  18591. }
  18592. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18593. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18594. // length MUST be 0.
  18595. // MSB set - must be rejected
  18596. {
  18597. detail::BufferStream strm;
  18598. std::string frame;
  18599. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18600. frame += static_cast<char>(127); // 64-bit extended length
  18601. frame += static_cast<char>(0x80); // MSB set (invalid)
  18602. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18603. strm.write(frame.data(), frame.size());
  18604. ws::Opcode opcode;
  18605. std::string payload;
  18606. bool fin;
  18607. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18608. false, 1024));
  18609. }
  18610. // MSB clear - should pass length parsing (will be rejected by max_len,
  18611. // but that's a different check; use a small length to verify)
  18612. {
  18613. detail::BufferStream strm;
  18614. std::string frame;
  18615. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18616. frame += static_cast<char>(127); // 64-bit extended length
  18617. frame += std::string(7, '\0'); // high bytes = 0
  18618. frame += static_cast<char>(0x03); // length = 3
  18619. frame += "abc";
  18620. strm.write(frame.data(), frame.size());
  18621. ws::Opcode opcode;
  18622. std::string payload;
  18623. bool fin;
  18624. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18625. false, 1024));
  18626. EXPECT_EQ(ws::Opcode::Text, opcode);
  18627. EXPECT_EQ("abc", payload);
  18628. }
  18629. }
  18630. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18631. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18632. // Valid UTF-8
  18633. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18634. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18635. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18636. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18637. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18638. // Invalid UTF-8
  18639. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18640. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18641. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18642. EXPECT_FALSE(
  18643. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18644. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18645. }
  18646. TEST(WebSocketTest, ConnectAndDisconnect) {
  18647. Server svr;
  18648. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18649. std::string msg;
  18650. while (ws.read(msg)) {}
  18651. });
  18652. auto port = svr.bind_to_any_port(HOST);
  18653. std::thread t([&]() { svr.listen_after_bind(); });
  18654. svr.wait_until_ready();
  18655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18656. auto res = client.connect();
  18657. ASSERT_TRUE(res);
  18658. EXPECT_EQ(Error::Success, res.error());
  18659. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18660. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18661. EXPECT_TRUE(client.is_open());
  18662. client.close();
  18663. EXPECT_FALSE(client.is_open());
  18664. svr.stop();
  18665. t.join();
  18666. }
  18667. TEST(WebSocketTest, ValidURL) {
  18668. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18669. EXPECT_TRUE(ws1.is_valid());
  18670. ws::WebSocketClient ws2("ws://example.com/path");
  18671. EXPECT_TRUE(ws2.is_valid());
  18672. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18673. EXPECT_TRUE(ws3.is_valid());
  18674. #ifdef CPPHTTPLIB_SSL_ENABLED
  18675. ws::WebSocketClient wss1("wss://example.com/path");
  18676. EXPECT_TRUE(wss1.is_valid());
  18677. ws::WebSocketClient wss2("wss://example.com:443/path");
  18678. EXPECT_TRUE(wss2.is_valid());
  18679. #endif
  18680. }
  18681. TEST(WebSocketTest, InvalidURL) {
  18682. // No scheme
  18683. ws::WebSocketClient ws1("localhost:8080/path");
  18684. EXPECT_FALSE(ws1.is_valid());
  18685. // No path
  18686. ws::WebSocketClient ws2("ws://localhost:8080");
  18687. EXPECT_FALSE(ws2.is_valid());
  18688. // Empty string
  18689. ws::WebSocketClient ws3("");
  18690. EXPECT_FALSE(ws3.is_valid());
  18691. // Missing host
  18692. ws::WebSocketClient ws4("ws://:8080/path");
  18693. EXPECT_FALSE(ws4.is_valid());
  18694. // Port number overflow — should not crash
  18695. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18696. EXPECT_FALSE(ws5.is_valid());
  18697. // Port out of range
  18698. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18699. EXPECT_FALSE(ws6.is_valid());
  18700. }
  18701. TEST(WebSocketTest, UnsupportedScheme) {
  18702. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18703. ws::WebSocketClient ws1("http://localhost:8080/path");
  18704. EXPECT_FALSE(ws1.is_valid());
  18705. ws::WebSocketClient ws2("https://localhost:8080/path");
  18706. EXPECT_FALSE(ws2.is_valid());
  18707. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18708. EXPECT_FALSE(ws3.is_valid());
  18709. #else
  18710. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18711. std::invalid_argument);
  18712. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18713. std::invalid_argument);
  18714. #endif
  18715. }
  18716. TEST(WebSocketTest, ConnectWhenInvalid) {
  18717. ws::WebSocketClient ws("not a valid url");
  18718. EXPECT_FALSE(ws.is_valid());
  18719. auto res = ws.connect();
  18720. EXPECT_FALSE(res);
  18721. EXPECT_EQ(Error::Connection, res.error());
  18722. EXPECT_EQ(-1, res.status());
  18723. }
  18724. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18725. // Grab a port that is free, then close it again so nothing listens there
  18726. Server svr;
  18727. auto port = svr.bind_to_any_port(HOST);
  18728. svr.stop();
  18729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18730. auto res = client.connect();
  18731. ASSERT_FALSE(res);
  18732. EXPECT_EQ(Error::Connection, res.error());
  18733. EXPECT_EQ(-1, res.status());
  18734. }
  18735. TEST(WebSocketTest, DefaultPort) {
  18736. ws::WebSocketClient ws1("ws://example.com/path");
  18737. EXPECT_TRUE(ws1.is_valid());
  18738. // ws:// defaults to port 80 (verified by successful parse)
  18739. #ifdef CPPHTTPLIB_SSL_ENABLED
  18740. ws::WebSocketClient ws2("wss://example.com/path");
  18741. EXPECT_TRUE(ws2.is_valid());
  18742. // wss:// defaults to port 443 (verified by successful parse)
  18743. #endif
  18744. }
  18745. TEST(WebSocketTest, IPv6LiteralAddress) {
  18746. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18747. EXPECT_TRUE(ws1.is_valid());
  18748. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18749. EXPECT_TRUE(ws2.is_valid());
  18750. }
  18751. TEST(WebSocketTest, ComplexPath) {
  18752. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18753. EXPECT_TRUE(ws1.is_valid());
  18754. ws::WebSocketClient ws2("ws://localhost:8080/");
  18755. EXPECT_TRUE(ws2.is_valid());
  18756. }
  18757. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18758. Server svr;
  18759. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18760. std::string msg;
  18761. while (ws.read(msg)) {}
  18762. });
  18763. auto port = svr.bind_to_any_port(HOST);
  18764. std::thread t([&]() { svr.listen_after_bind(); });
  18765. svr.wait_until_ready();
  18766. auto another_host = "example.com";
  18767. auto wrong_ip = "192.0.2.1";
  18768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18769. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18770. ASSERT_TRUE(client.connect());
  18771. EXPECT_TRUE(client.is_open());
  18772. client.close();
  18773. svr.stop();
  18774. t.join();
  18775. }
  18776. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18777. Server svr;
  18778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18779. std::string msg;
  18780. while (ws.read(msg)) {}
  18781. });
  18782. auto port = svr.bind_to_any_port(HOST);
  18783. std::thread t([&]() { svr.listen_after_bind(); });
  18784. svr.wait_until_ready();
  18785. auto wrong_ip = "192.0.2.1";
  18786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18787. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18788. client.set_connection_timeout(1);
  18789. client.set_read_timeout(1);
  18790. client.set_write_timeout(1);
  18791. EXPECT_FALSE(client.connect());
  18792. EXPECT_FALSE(client.is_open());
  18793. svr.stop();
  18794. t.join();
  18795. }
  18796. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18797. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18798. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18799. // (RFC 6761) is only a map key and the Host header value.
  18800. auto host = "target.invalid";
  18801. Server svr;
  18802. std::string received_host;
  18803. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18804. received_host = req.get_header_value("Host");
  18805. std::string msg;
  18806. while (ws.read(msg)) {}
  18807. });
  18808. auto port = svr.bind_to_any_port(HOST);
  18809. std::thread t([&]() { svr.listen_after_bind(); });
  18810. // ASSERT_* below returns from the test body, which would leave t joinable
  18811. // and make ~thread call std::terminate.
  18812. auto se = detail::scope_exit([&] {
  18813. svr.stop();
  18814. if (t.joinable()) { t.join(); }
  18815. });
  18816. svr.wait_until_ready();
  18817. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18818. std::to_string(port) + "/ws");
  18819. client.set_hostname_addr_map({{host, HOST}});
  18820. ASSERT_TRUE(client.connect());
  18821. EXPECT_TRUE(client.is_open());
  18822. client.close();
  18823. svr.stop();
  18824. t.join();
  18825. // The mapping only redirects the connection; the identity stays host_.
  18826. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18827. }
  18828. class WebSocketIntegrationTest : public ::testing::Test {
  18829. protected:
  18830. void SetUp() override {
  18831. server_ = httplib::detail::make_unique<Server>();
  18832. setup_server();
  18833. start_server();
  18834. }
  18835. void TearDown() override {
  18836. server_->stop();
  18837. if (server_thread_.joinable()) { server_thread_.join(); }
  18838. }
  18839. void setup_server() {
  18840. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18841. std::string msg;
  18842. ws::ReadResult ret;
  18843. while ((ret = ws.read(msg))) {
  18844. if (ret == ws::Binary) {
  18845. ws.send(msg.data(), msg.size());
  18846. } else {
  18847. ws.send(msg);
  18848. }
  18849. }
  18850. });
  18851. server_->WebSocket("/ws-echo-string",
  18852. [](const Request &, ws::WebSocket &ws) {
  18853. std::string msg;
  18854. while (ws.read(msg)) {
  18855. ws.send("echo: " + msg);
  18856. }
  18857. });
  18858. server_->WebSocket(
  18859. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18860. // Echo back request metadata
  18861. ws.send("path:" + req.path);
  18862. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18863. std::string msg;
  18864. while (ws.read(msg)) {}
  18865. });
  18866. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18867. std::string msg;
  18868. ws.read(msg); // wait for a message
  18869. ws.close();
  18870. });
  18871. server_->WebSocket("/ws-close-status",
  18872. [](const Request &, ws::WebSocket &ws) {
  18873. std::string msg;
  18874. ws.read(msg); // wait for a message
  18875. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18876. });
  18877. server_->WebSocket(
  18878. "/ws-subprotocol",
  18879. [](const Request &, ws::WebSocket &ws) {
  18880. std::string msg;
  18881. while (ws.read(msg)) {
  18882. ws.send(msg);
  18883. }
  18884. },
  18885. [](const std::vector<std::string> &protocols) -> std::string {
  18886. for (const auto &p : protocols) {
  18887. if (p == "graphql-ws") { return p; }
  18888. }
  18889. return "";
  18890. });
  18891. }
  18892. void start_server() {
  18893. port_ = server_->bind_to_any_port(HOST);
  18894. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18895. server_->wait_until_ready();
  18896. }
  18897. std::unique_ptr<Server> server_;
  18898. std::thread server_thread_;
  18899. int port_ = 0;
  18900. };
  18901. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18902. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18903. "/ws-echo");
  18904. ASSERT_TRUE(client.connect());
  18905. ASSERT_TRUE(client.is_open());
  18906. ASSERT_TRUE(client.send("Hello WebSocket"));
  18907. std::string msg;
  18908. EXPECT_EQ(ws::Text, client.read(msg));
  18909. EXPECT_EQ("Hello WebSocket", msg);
  18910. client.close();
  18911. }
  18912. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18914. "/ws-echo");
  18915. ASSERT_TRUE(client.connect());
  18916. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18917. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18918. std::string msg;
  18919. EXPECT_EQ(ws::Binary, client.read(msg));
  18920. EXPECT_EQ(binary_data, msg);
  18921. client.close();
  18922. }
  18923. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18925. "/ws-echo");
  18926. ASSERT_TRUE(client.connect());
  18927. for (int i = 0; i < 10; i++) {
  18928. auto text = "message " + std::to_string(i);
  18929. ASSERT_TRUE(client.send(text));
  18930. std::string msg;
  18931. ASSERT_TRUE(client.read(msg));
  18932. EXPECT_EQ(text, msg);
  18933. }
  18934. client.close();
  18935. }
  18936. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18938. "/ws-close");
  18939. ASSERT_TRUE(client.connect());
  18940. // Send a message to trigger the server to close
  18941. ASSERT_TRUE(client.send("trigger close"));
  18942. // The server will close, so read should return false
  18943. std::string msg;
  18944. EXPECT_FALSE(client.read(msg));
  18945. EXPECT_FALSE(client.is_open());
  18946. }
  18947. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18949. "/ws-echo");
  18950. ASSERT_TRUE(client.connect());
  18951. // 128KB message
  18952. std::string large_data(128 * 1024, 'X');
  18953. ASSERT_TRUE(client.send(large_data));
  18954. std::string msg;
  18955. ASSERT_TRUE(client.read(msg));
  18956. EXPECT_EQ(large_data, msg);
  18957. client.close();
  18958. }
  18959. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18961. "/ws-echo");
  18962. ASSERT_TRUE(client.connect());
  18963. const int num_threads = 4;
  18964. std::vector<std::thread> threads;
  18965. std::atomic<int> send_count{0};
  18966. for (int t = 0; t < num_threads; t++) {
  18967. threads.emplace_back([&client, &send_count, t]() {
  18968. for (int i = 0; i < 5; i++) {
  18969. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18970. if (client.send(text)) { send_count++; }
  18971. }
  18972. });
  18973. }
  18974. for (auto &th : threads) {
  18975. th.join();
  18976. }
  18977. int received = 0;
  18978. std::string msg;
  18979. while (received < send_count.load()) {
  18980. if (!client.read(msg)) { break; }
  18981. received++;
  18982. }
  18983. EXPECT_EQ(send_count.load(), received);
  18984. client.close();
  18985. }
  18986. TEST_F(WebSocketIntegrationTest, ReadString) {
  18987. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18988. "/ws-echo-string");
  18989. ASSERT_TRUE(client.connect());
  18990. ASSERT_TRUE(client.send("hello"));
  18991. std::string msg;
  18992. ASSERT_TRUE(client.read(msg));
  18993. EXPECT_EQ("echo: hello", msg);
  18994. ASSERT_TRUE(client.send("world"));
  18995. ASSERT_TRUE(client.read(msg));
  18996. EXPECT_EQ("echo: world", msg);
  18997. client.close();
  18998. }
  18999. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19000. Headers headers = {{"X-Test-Header", "test-value"}};
  19001. ws::WebSocketClient client(
  19002. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19003. ASSERT_TRUE(client.connect());
  19004. std::string msg;
  19005. ASSERT_TRUE(client.read(msg));
  19006. EXPECT_EQ("path:/ws-request-info", msg);
  19007. ASSERT_TRUE(client.read(msg));
  19008. EXPECT_EQ("header:test-value", msg);
  19009. client.close();
  19010. }
  19011. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19013. "/ws-echo");
  19014. client.set_read_timeout(1, 0); // 1 second
  19015. ASSERT_TRUE(client.connect());
  19016. // Don't send anything — server echo handler waits for a message,
  19017. // so read() should time out and return false.
  19018. std::string msg;
  19019. EXPECT_FALSE(client.read(msg));
  19020. }
  19021. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19023. "/ws-echo");
  19024. client.set_read_timeout(5, 0);
  19025. ASSERT_TRUE(client.connect());
  19026. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19027. // The server should reject it and close the connection.
  19028. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19029. client.send(oversized);
  19030. // The server's read() should have failed due to payload limit,
  19031. // so our read() should return false (connection closed).
  19032. std::string msg;
  19033. EXPECT_FALSE(client.read(msg));
  19034. }
  19035. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19037. "/ws-echo");
  19038. client.set_read_timeout(10, 0);
  19039. ASSERT_TRUE(client.connect());
  19040. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19041. // This should succeed.
  19042. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19043. ASSERT_TRUE(client.send(at_limit));
  19044. std::string msg;
  19045. ASSERT_TRUE(client.read(msg));
  19046. EXPECT_EQ(at_limit.size(), msg.size());
  19047. client.close();
  19048. }
  19049. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19051. "/nonexistent");
  19052. auto res = client.connect();
  19053. EXPECT_FALSE(res);
  19054. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19055. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19056. EXPECT_FALSE(client.is_open());
  19057. }
  19058. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19060. "/ws-echo");
  19061. ASSERT_TRUE(client.connect());
  19062. ASSERT_TRUE(client.send(""));
  19063. std::string msg;
  19064. EXPECT_EQ(ws::Text, client.read(msg));
  19065. EXPECT_EQ("", msg);
  19066. client.close();
  19067. }
  19068. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19069. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19070. "/ws-echo");
  19071. // First connection
  19072. ASSERT_TRUE(client.connect());
  19073. ASSERT_TRUE(client.send("first"));
  19074. std::string msg;
  19075. ASSERT_TRUE(client.read(msg));
  19076. EXPECT_EQ("first", msg);
  19077. client.close();
  19078. EXPECT_FALSE(client.is_open());
  19079. // Reconnect using the same client object
  19080. ASSERT_TRUE(client.connect());
  19081. ASSERT_TRUE(client.is_open());
  19082. ASSERT_TRUE(client.send("second"));
  19083. ASSERT_TRUE(client.read(msg));
  19084. EXPECT_EQ("second", msg);
  19085. client.close();
  19086. }
  19087. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19089. "/ws-close-status");
  19090. ASSERT_TRUE(client.connect());
  19091. // Trigger the server to close with GoingAway status
  19092. ASSERT_TRUE(client.send("trigger"));
  19093. // read() should return false after receiving the close frame
  19094. std::string msg;
  19095. EXPECT_FALSE(client.read(msg));
  19096. EXPECT_FALSE(client.is_open());
  19097. }
  19098. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19100. "/ws-echo");
  19101. ASSERT_TRUE(client.connect());
  19102. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19103. EXPECT_FALSE(client.is_open());
  19104. }
  19105. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19106. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19107. ws::WebSocketClient client(
  19108. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19109. ASSERT_TRUE(client.connect());
  19110. // Server should have selected graphql-ws
  19111. EXPECT_EQ("graphql-ws", client.subprotocol());
  19112. client.close();
  19113. }
  19114. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19115. Headers headers;
  19116. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19117. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19118. ws::WebSocketClient client(
  19119. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19120. ASSERT_TRUE(client.connect());
  19121. // The offer on the second field line counts too, so graphql-ws is selected
  19122. EXPECT_EQ("graphql-ws", client.subprotocol());
  19123. client.close();
  19124. }
  19125. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19126. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19127. ws::WebSocketClient client(
  19128. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19129. ASSERT_TRUE(client.connect());
  19130. // Server should not have selected any subprotocol
  19131. EXPECT_TRUE(client.subprotocol().empty());
  19132. client.close();
  19133. }
  19134. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19135. // Connect without requesting any subprotocol
  19136. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19137. "/ws-subprotocol");
  19138. ASSERT_TRUE(client.connect());
  19139. EXPECT_TRUE(client.subprotocol().empty());
  19140. client.close();
  19141. }
  19142. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19143. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19144. "/ws-echo");
  19145. client.set_tcp_nodelay(true);
  19146. client.set_connection_timeout(3, 0);
  19147. bool socket_options_called = false;
  19148. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19149. ASSERT_TRUE(client.connect());
  19150. ASSERT_TRUE(client.is_open());
  19151. EXPECT_TRUE(socket_options_called);
  19152. ASSERT_TRUE(client.send("hello"));
  19153. std::string msg;
  19154. auto result = client.read(msg);
  19155. EXPECT_EQ(result, ws::ReadResult::Text);
  19156. EXPECT_EQ(msg, "hello");
  19157. client.close();
  19158. }
  19159. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19161. "/ws-echo");
  19162. client.set_connection_timeout(std::chrono::seconds(3));
  19163. client.set_write_timeout(std::chrono::seconds(3));
  19164. // A sub-second remainder exercises the seconds/microseconds split.
  19165. client.set_read_timeout(std::chrono::milliseconds(1500));
  19166. ASSERT_TRUE(client.connect());
  19167. auto start = std::chrono::steady_clock::now();
  19168. std::string msg;
  19169. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  19170. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19171. std::chrono::steady_clock::now() - start)
  19172. .count();
  19173. // Above 1s so that dropping the microseconds half of the split fails here,
  19174. // and well under the 300s default so that ignoring the setter fails too.
  19175. EXPECT_GE(elapsed, 1400);
  19176. EXPECT_LT(elapsed, 30000);
  19177. }
  19178. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19179. Server svr;
  19180. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19181. if (!req.has_header("Authorization")) {
  19182. res.status = StatusCode::Unauthorized_401;
  19183. res.set_content("Unauthorized", "text/plain");
  19184. return Server::HandlerResponse::Handled;
  19185. }
  19186. return Server::HandlerResponse::Unhandled;
  19187. });
  19188. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19189. std::string msg;
  19190. while (ws.read(msg)) {
  19191. ws.send(msg);
  19192. }
  19193. });
  19194. auto port = svr.bind_to_any_port("localhost");
  19195. std::thread t([&]() { svr.listen_after_bind(); });
  19196. svr.wait_until_ready();
  19197. // Without Authorization header - should be rejected before upgrade
  19198. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19199. EXPECT_FALSE(client1.connect());
  19200. // With Authorization header - should succeed
  19201. Headers headers = {{"Authorization", "Bearer token123"}};
  19202. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19203. headers);
  19204. ASSERT_TRUE(client2.connect());
  19205. ASSERT_TRUE(client2.send("hello"));
  19206. std::string msg;
  19207. ASSERT_TRUE(client2.read(msg));
  19208. EXPECT_EQ("hello", msg);
  19209. client2.close();
  19210. svr.stop();
  19211. t.join();
  19212. }
  19213. TEST(WebSocketTest, QueryStringInHandshake) {
  19214. Server svr;
  19215. std::mutex mtx;
  19216. std::string received_target;
  19217. std::string received_token;
  19218. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19219. {
  19220. std::lock_guard<std::mutex> lock(mtx);
  19221. received_target = req.target;
  19222. if (req.has_param("token")) {
  19223. received_token = req.get_param_value("token");
  19224. }
  19225. }
  19226. std::string msg;
  19227. while (ws.read(msg)) {
  19228. ws.send(msg);
  19229. }
  19230. });
  19231. auto port = svr.bind_to_any_port("localhost");
  19232. std::thread t([&]() { svr.listen_after_bind(); });
  19233. svr.wait_until_ready();
  19234. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19235. "/ws?token=ABC&session=123");
  19236. ASSERT_TRUE(client.connect());
  19237. // Round-trip ensures the handler has run and captured the request.
  19238. ASSERT_TRUE(client.send("hello"));
  19239. std::string msg;
  19240. ASSERT_TRUE(client.read(msg));
  19241. EXPECT_EQ("hello", msg);
  19242. client.close();
  19243. {
  19244. std::lock_guard<std::mutex> lock(mtx);
  19245. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  19246. EXPECT_EQ("ABC", received_token);
  19247. }
  19248. svr.stop();
  19249. t.join();
  19250. }
  19251. // Run a handshake against a throwaway server and hand the request the server
  19252. // received back to the caller, so tests can assert on the headers the client
  19253. // actually put on the wire.
  19254. static void capture_websocket_handshake_request(
  19255. const Headers &client_headers,
  19256. std::function<void(const Request &, int port)> verify) {
  19257. Server svr;
  19258. std::mutex mtx;
  19259. Request received;
  19260. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19261. {
  19262. std::lock_guard<std::mutex> lock(mtx);
  19263. received = req;
  19264. }
  19265. std::string msg;
  19266. while (ws.read(msg)) {
  19267. ws.send(msg);
  19268. }
  19269. });
  19270. auto port = svr.bind_to_any_port("localhost");
  19271. std::thread t([&]() { svr.listen_after_bind(); });
  19272. auto se = detail::scope_exit([&] {
  19273. svr.stop();
  19274. t.join();
  19275. });
  19276. svr.wait_until_ready();
  19277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  19278. client_headers);
  19279. ASSERT_TRUE(client.connect());
  19280. ASSERT_TRUE(client.send("hello"));
  19281. std::string msg;
  19282. ASSERT_TRUE(client.read(msg));
  19283. client.close();
  19284. {
  19285. std::lock_guard<std::mutex> lock(mtx);
  19286. verify(received, port);
  19287. }
  19288. }
  19289. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  19290. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  19291. // Non-default port must be present in the Host header. Default ports
  19292. // (80/443) are omitted; that logic is covered by
  19293. // MakeHostAndPortStringTest.
  19294. EXPECT_EQ("localhost:" + std::to_string(port),
  19295. req.get_header_value("Host"));
  19296. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  19297. req.get_header_value("User-Agent"));
  19298. EXPECT_FALSE(req.has_header("Accept"));
  19299. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  19300. EXPECT_FALSE(req.has_header("Content-Length"));
  19301. });
  19302. }
  19303. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  19304. capture_websocket_handshake_request(
  19305. {{"Host", "example.com"},
  19306. {"User-Agent", "custom-agent"},
  19307. {"X-Custom", "value"}},
  19308. [](const Request &req, int) {
  19309. EXPECT_EQ("example.com", req.get_header_value("Host"));
  19310. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  19311. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  19312. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  19313. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  19314. });
  19315. }
  19316. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  19317. capture_websocket_handshake_request(
  19318. {{"Upgrade", "bogus"},
  19319. {"Connection", "close"},
  19320. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  19321. {"Sec-WebSocket-Version", "8"}},
  19322. [](const Request &req, int) {
  19323. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  19324. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  19325. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  19326. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  19327. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  19328. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  19329. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  19330. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  19331. req.get_header_value("Sec-WebSocket-Key"));
  19332. });
  19333. }
  19334. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  19335. // A header the client refuses to send must abort the handshake before any
  19336. // part of it reaches the wire; a lone request line would otherwise sit in
  19337. // the peer's buffer as a truncated request.
  19338. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19339. ASSERT_NE(INVALID_SOCKET, srv);
  19340. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  19341. sockaddr_in addr{};
  19342. addr.sin_family = AF_INET;
  19343. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  19344. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19345. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19346. ASSERT_EQ(0, ::listen(srv, 1));
  19347. sockaddr_in bound{};
  19348. socklen_t bound_len = sizeof(bound);
  19349. ASSERT_EQ(
  19350. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  19351. auto port = ntohs(bound.sin_port);
  19352. ssize_t received = -1;
  19353. std::thread t([&] {
  19354. // Bound every blocking call so a regression fails the test with a bad
  19355. // value instead of hanging the suite.
  19356. fd_set rfds;
  19357. FD_ZERO(&rfds);
  19358. FD_SET(srv, &rfds);
  19359. timeval tv{5, 0};
  19360. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  19361. 0) {
  19362. return;
  19363. }
  19364. sockaddr_in cli_addr{};
  19365. socklen_t cli_len = sizeof(cli_addr);
  19366. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19367. if (cli == INVALID_SOCKET) { return; }
  19368. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  19369. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19370. char buf[4096];
  19371. received = ::recv(cli, buf, sizeof(buf), 0);
  19372. });
  19373. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  19374. // connect() has already shut the socket down by the time it returns false,
  19375. // so the peer sees EOF without waiting for the client to be destroyed.
  19376. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  19377. {{"X-Bad", "a\r\nInjected: 1"}});
  19378. EXPECT_FALSE(client.connect());
  19379. t.join();
  19380. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  19381. EXPECT_EQ(0, received);
  19382. }
  19383. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  19384. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  19385. // contains "upgrade" as a substring is a different token and must not
  19386. // start a WebSocket handshake.
  19387. auto make_request = [](const std::vector<std::string> &connection_values) {
  19388. Request req;
  19389. req.method = "GET";
  19390. req.headers.emplace("Upgrade", "websocket");
  19391. for (const auto &value : connection_values) {
  19392. req.headers.emplace("Connection", value);
  19393. }
  19394. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19395. req.headers.emplace("Sec-WebSocket-Version", "13");
  19396. return req;
  19397. };
  19398. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  19399. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  19400. EXPECT_TRUE(
  19401. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  19402. EXPECT_TRUE(
  19403. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  19404. EXPECT_TRUE(
  19405. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  19406. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  19407. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  19408. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  19409. EXPECT_FALSE(
  19410. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  19411. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  19412. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19413. }
  19414. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  19415. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  19416. // asks recipients to match each protocol-name case-insensitively, and RFC
  19417. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  19418. // client naming websocket alongside another protocol, or on a second field
  19419. // line, is offering websocket; a value that merely contains "websocket" as a
  19420. // substring is a different protocol name and is not.
  19421. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  19422. Request req;
  19423. req.method = "GET";
  19424. for (const auto &value : upgrade_values) {
  19425. req.headers.emplace("Upgrade", value);
  19426. }
  19427. req.headers.emplace("Connection", "Upgrade");
  19428. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19429. req.headers.emplace("Sec-WebSocket-Version", "13");
  19430. return req;
  19431. };
  19432. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  19433. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19434. EXPECT_TRUE(
  19435. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19436. EXPECT_TRUE(
  19437. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19438. EXPECT_TRUE(
  19439. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19440. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19441. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19442. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19443. EXPECT_FALSE(
  19444. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19445. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19446. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19447. }
  19448. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19449. Server svr;
  19450. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19451. auto port = svr.bind_to_any_port("localhost");
  19452. std::thread t([&]() { svr.listen_after_bind(); });
  19453. auto se = detail::scope_exit([&] {
  19454. svr.stop();
  19455. t.join();
  19456. });
  19457. svr.wait_until_ready();
  19458. Headers headers = {{"Upgrade", "websocket"},
  19459. {"Connection", "notupgrade"},
  19460. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19461. {"Sec-WebSocket-Version", "13"}};
  19462. Client cli("localhost", port);
  19463. auto res = cli.Get("/ws", headers);
  19464. // The route exists only as a WebSocket route, so a request that fails the
  19465. // handshake check falls through to ordinary routing.
  19466. ASSERT_TRUE(res);
  19467. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19468. }
  19469. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19470. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19471. // Connection value is the only thing left for the client to reject.
  19472. Server svr;
  19473. svr.Get("/ws", [](const Request &req, Response &res) {
  19474. res.status = StatusCode::SwitchingProtocol_101;
  19475. res.set_header("Upgrade", "websocket");
  19476. res.set_header("Connection", "notupgrade");
  19477. res.set_header("Sec-WebSocket-Accept",
  19478. detail::websocket_accept_key(
  19479. req.get_header_value("Sec-WebSocket-Key")));
  19480. });
  19481. auto port = svr.bind_to_any_port("localhost");
  19482. std::thread t([&]() { svr.listen_after_bind(); });
  19483. auto se = detail::scope_exit([&] {
  19484. svr.stop();
  19485. t.join();
  19486. });
  19487. svr.wait_until_ready();
  19488. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19489. auto res = client.connect();
  19490. EXPECT_FALSE(res);
  19491. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19492. EXPECT_FALSE(client.is_open());
  19493. }
  19494. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19495. // The socket path doubles as the URL host, so it must not contain '/'.
  19496. const char *shard = getenv("GTEST_SHARD_INDEX");
  19497. const std::string sock_path =
  19498. shard ? std::string("httplib-ws-") + shard + ".sock"
  19499. : std::string("httplib-ws.sock");
  19500. std::remove(sock_path.c_str());
  19501. Server svr;
  19502. std::mutex mtx;
  19503. std::string received_host;
  19504. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19505. {
  19506. std::lock_guard<std::mutex> lock(mtx);
  19507. received_host = req.get_header_value("Host");
  19508. }
  19509. std::string msg;
  19510. while (ws.read(msg)) {
  19511. ws.send(msg);
  19512. }
  19513. });
  19514. svr.set_address_family(AF_UNIX);
  19515. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19516. auto se = detail::scope_exit([&] {
  19517. svr.stop();
  19518. t.join();
  19519. std::remove(sock_path.c_str());
  19520. });
  19521. svr.wait_until_ready();
  19522. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19523. client.set_address_family(AF_UNIX);
  19524. ASSERT_TRUE(client.connect());
  19525. ASSERT_TRUE(client.send("hello"));
  19526. std::string msg;
  19527. ASSERT_TRUE(client.read(msg));
  19528. client.close();
  19529. {
  19530. std::lock_guard<std::mutex> lock(mtx);
  19531. // There is no host:port for a Unix socket, so the same "localhost"
  19532. // placeholder the HTTP client uses is expected.
  19533. EXPECT_EQ("localhost", received_host);
  19534. }
  19535. }
  19536. // Two threads must never parse WebSocket frames from the same stream.
  19537. // close() used to read the peer's Close reply with its own frame read, so it
  19538. // raced a reader thread that was in the middle of a payload: the payload loop
  19539. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19540. // so bytes taken by close() were replaced with bytes from further along the
  19541. // stream. The message kept its length and silently changed content.
  19542. //
  19543. // The raw peer below sends a frame header plus part of the payload, waits for
  19544. // the handler to call close(), and only then sends the rest. Whichever thread
  19545. // would win the race for those bytes, the message must arrive intact, because
  19546. // close() must not touch the stream while read() owns it.
  19547. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19548. #ifndef _WIN32
  19549. signal(SIGPIPE, SIG_IGN);
  19550. #endif
  19551. const size_t payload_len = 120; // fits the 7-bit length field
  19552. const size_t prefix_len = 8;
  19553. const int attempts = 8;
  19554. std::string expected(payload_len, '\0');
  19555. for (size_t i = 0; i < payload_len; i++) {
  19556. expected[i] = static_cast<char>('a' + i % 26);
  19557. }
  19558. std::atomic<bool> peer_stalled{false};
  19559. std::atomic<bool> handler_done{false};
  19560. std::mutex received_mutex;
  19561. std::vector<std::string> received;
  19562. // Bound every wait, so a regression fails the test instead of hanging the
  19563. // suite.
  19564. auto wait_for = [](const std::atomic<bool> &flag) {
  19565. for (int i = 0; i < 500 && !flag; i++) {
  19566. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19567. }
  19568. };
  19569. Server svr;
  19570. svr.set_websocket_ping_interval(0);
  19571. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19572. std::thread reader([&]() {
  19573. std::string msg;
  19574. while (ws.read(msg)) {
  19575. std::lock_guard<std::mutex> guard(received_mutex);
  19576. received.push_back(msg);
  19577. }
  19578. });
  19579. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19580. // inside read_websocket_frame() when close() runs.
  19581. wait_for(peer_stalled);
  19582. ws.close();
  19583. reader.join();
  19584. handler_done = true;
  19585. });
  19586. auto port = svr.bind_to_any_port("127.0.0.1");
  19587. std::thread t([&]() { svr.listen_after_bind(); });
  19588. auto se = detail::scope_exit([&] {
  19589. svr.stop();
  19590. t.join();
  19591. });
  19592. svr.wait_until_ready();
  19593. auto send_bytes = [](socket_t s, const std::string &data) {
  19594. #ifdef _WIN32
  19595. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19596. #else
  19597. auto n = ::send(s, data.data(), data.size(), 0);
  19598. #endif
  19599. return n == static_cast<decltype(n)>(data.size());
  19600. };
  19601. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19602. // Every length used here fits the 7-bit length field.
  19603. auto masked_header = [](uint8_t first_byte, size_t len) {
  19604. std::string h;
  19605. h += static_cast<char>(first_byte);
  19606. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19607. h.append(4, '\0'); // mask key
  19608. return h;
  19609. };
  19610. for (int attempt = 0; attempt < attempts; attempt++) {
  19611. peer_stalled = false;
  19612. handler_done = false;
  19613. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19614. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19615. auto se_sock = detail::scope_exit([&] {
  19616. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19617. });
  19618. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19619. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19620. sockaddr_in addr{};
  19621. addr.sin_family = AF_INET;
  19622. addr.sin_port = htons(static_cast<uint16_t>(port));
  19623. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19624. ASSERT_EQ(
  19625. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19626. << "attempt " << attempt;
  19627. ASSERT_TRUE(send_bytes(sock,
  19628. "GET /ws HTTP/1.1\r\n"
  19629. "Host: 127.0.0.1\r\n"
  19630. "Upgrade: websocket\r\n"
  19631. "Connection: Upgrade\r\n"
  19632. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19633. "Sec-WebSocket-Version: 13\r\n"
  19634. "\r\n"))
  19635. << "attempt " << attempt;
  19636. std::string response;
  19637. while (response.find("\r\n\r\n") == std::string::npos) {
  19638. char buf[512];
  19639. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19640. if (n <= 0) { break; }
  19641. response.append(buf, static_cast<size_t>(n));
  19642. }
  19643. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19644. << "attempt " << attempt;
  19645. // Send the header of a Binary message but only the first prefix_len bytes
  19646. // of its payload, leaving the reader thread stalled inside the payload.
  19647. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19648. expected.substr(0, prefix_len)))
  19649. << "attempt " << attempt;
  19650. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19651. peer_stalled = true;
  19652. // Let close() send its Close frame and park in its own read before the
  19653. // rest of the payload arrives, so both threads are waiting for it.
  19654. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19655. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19656. close_frame += static_cast<char>(0x03); // status 1000
  19657. close_frame += static_cast<char>(0xE8);
  19658. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19659. << "attempt " << attempt;
  19660. // Closing the peer releases the reader thread even on the buggy path,
  19661. // where it waits for bytes another thread already consumed.
  19662. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19663. detail::close_socket(sock);
  19664. sock = INVALID_SOCKET;
  19665. wait_for(handler_done);
  19666. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19667. }
  19668. std::lock_guard<std::mutex> guard(received_mutex);
  19669. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19670. << "a message in flight when close() ran was dropped";
  19671. for (size_t i = 0; i < received.size(); i++) {
  19672. EXPECT_EQ(expected, received[i]) << "message " << i;
  19673. }
  19674. }
  19675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19676. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19677. protected:
  19678. void SetUp() override {
  19679. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19680. SERVER_PRIVATE_KEY_FILE);
  19681. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19682. std::string msg;
  19683. ws::ReadResult ret;
  19684. while ((ret = ws.read(msg))) {
  19685. if (ret == ws::Binary) {
  19686. ws.send(msg.data(), msg.size());
  19687. } else {
  19688. ws.send(msg);
  19689. }
  19690. }
  19691. });
  19692. port_ = server_->bind_to_any_port(HOST);
  19693. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19694. server_->wait_until_ready();
  19695. }
  19696. void TearDown() override {
  19697. server_->stop();
  19698. if (server_thread_.joinable()) { server_thread_.join(); }
  19699. }
  19700. std::unique_ptr<SSLServer> server_;
  19701. std::thread server_thread_;
  19702. int port_ = 0;
  19703. };
  19704. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19705. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19706. "/ws-echo");
  19707. client.enable_server_certificate_verification(false);
  19708. ASSERT_TRUE(client.connect());
  19709. ASSERT_TRUE(client.is_open());
  19710. ASSERT_TRUE(client.send("Hello WSS"));
  19711. std::string msg;
  19712. EXPECT_EQ(ws::Text, client.read(msg));
  19713. EXPECT_EQ("Hello WSS", msg);
  19714. client.close();
  19715. }
  19716. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19717. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19718. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19719. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19720. // client (without calling close() first) is the only path that runs
  19721. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19722. // bug exactly.
  19723. //
  19724. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19725. // when linked against an instrumented libssl; run under Valgrind to catch it
  19726. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19727. // suite (the freed session otherwise stalls on the close handshake) — this test
  19728. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19729. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19730. {
  19731. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19732. "/ws-echo");
  19733. client.enable_server_certificate_verification(false);
  19734. client.set_read_timeout(2, 0);
  19735. client.set_write_timeout(2, 0);
  19736. ASSERT_TRUE(client.connect());
  19737. ASSERT_TRUE(client.is_open());
  19738. ASSERT_TRUE(client.send("still open"));
  19739. // Intentionally do NOT call client.close(): leaving scope runs
  19740. // shutdown_and_close() with the WebSocket still open, which must send the
  19741. // close frame while the TLS session is still alive.
  19742. }
  19743. }
  19744. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19745. // shutdown_and_close() at the start of connect(), reproducing the same
  19746. // use-after-free within the test body rather than at scope exit. The second
  19747. // connect must succeed and echo, proving the close handshake ran over a live
  19748. // session. See the note above about memory-tool requirements.
  19749. TEST_F(WebSocketSSLIntegrationTest,
  19750. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19751. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19752. "/ws-echo");
  19753. client.enable_server_certificate_verification(false);
  19754. client.set_read_timeout(2, 0);
  19755. client.set_write_timeout(2, 0);
  19756. ASSERT_TRUE(client.connect());
  19757. ASSERT_TRUE(client.is_open());
  19758. ASSERT_TRUE(client.send("still open"));
  19759. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19760. // the still-open connection, which must not touch a freed TLS session.
  19761. ASSERT_TRUE(client.connect());
  19762. ASSERT_TRUE(client.is_open());
  19763. ASSERT_TRUE(client.send("after reconnect"));
  19764. std::string msg;
  19765. EXPECT_EQ(ws::Text, client.read(msg));
  19766. EXPECT_EQ("after reconnect", msg);
  19767. client.close();
  19768. }
  19769. #endif
  19770. #ifdef CPPHTTPLIB_SSL_ENABLED
  19771. class WebSocketSSLCATest : public ::testing::Test {
  19772. protected:
  19773. void SetUp() override {
  19774. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19775. SERVER_PRIVATE_KEY_FILE);
  19776. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19777. std::string msg;
  19778. while (ws.read(msg)) {
  19779. ws.send(msg);
  19780. }
  19781. });
  19782. port_ = server_->bind_to_any_port("127.0.0.1");
  19783. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19784. server_->wait_until_ready();
  19785. }
  19786. void TearDown() override {
  19787. server_->stop();
  19788. if (server_thread_.joinable()) { server_thread_.join(); }
  19789. }
  19790. std::string url() const {
  19791. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19792. }
  19793. std::unique_ptr<SSLServer> server_;
  19794. std::thread server_thread_;
  19795. int port_ = 0;
  19796. };
  19797. // A custom CA loaded as PEM verifies the server with full certificate
  19798. // verification enabled
  19799. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19800. ws::WebSocketClient client(url());
  19801. std::string cert;
  19802. read_file(SERVER_CERT2_FILE, cert);
  19803. client.load_ca_cert_store(cert.c_str(), cert.size());
  19804. ASSERT_TRUE(client.connect());
  19805. ASSERT_TRUE(client.send("hello"));
  19806. std::string msg;
  19807. EXPECT_EQ(ws::Text, client.read(msg));
  19808. EXPECT_EQ("hello", msg);
  19809. client.close();
  19810. }
  19811. // A custom CA that does not cover the server must fail verification (the
  19812. // custom CA is exclusive; system certs are not loaded alongside it)
  19813. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19814. ws::WebSocketClient client(url());
  19815. std::string cert;
  19816. read_file(CLIENT_CA_CERT_FILE, cert);
  19817. client.load_ca_cert_store(cert.c_str(), cert.size());
  19818. auto res = client.connect();
  19819. ASSERT_FALSE(res);
  19820. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19821. EXPECT_EQ(-1, res.status());
  19822. EXPECT_NE(0u, res.ssl_backend_error());
  19823. }
  19824. // The same CA as a file path rather than PEM in memory
  19825. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19826. ws::WebSocketClient client(url());
  19827. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19828. ASSERT_TRUE(client.connect());
  19829. ASSERT_TRUE(client.send("hello"));
  19830. std::string msg;
  19831. EXPECT_EQ(ws::Text, client.read(msg));
  19832. EXPECT_EQ("hello", msg);
  19833. client.close();
  19834. }
  19835. // ...and a CA file that does not cover the server still fails, so it is the
  19836. // path above that decides the outcome
  19837. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19838. ws::WebSocketClient client(url());
  19839. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19840. ASSERT_FALSE(client.connect());
  19841. }
  19842. // Regression test: reconnecting with a native custom CA store used to reuse
  19843. // a store handle the previous TLS context had already freed (use-after-free
  19844. // under the OpenSSL backend). The context now lives as long as the client.
  19845. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19846. ws::WebSocketClient client(url());
  19847. std::string cert;
  19848. read_file(SERVER_CERT2_FILE, cert);
  19849. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19850. ASSERT_TRUE(client.connect());
  19851. client.close();
  19852. ASSERT_TRUE(client.connect());
  19853. ASSERT_TRUE(client.send("again"));
  19854. std::string msg;
  19855. EXPECT_EQ(ws::Text, client.read(msg));
  19856. EXPECT_EQ("again", msg);
  19857. client.close();
  19858. }
  19859. // Regression test: a certificate with a trusted chain but no identity match
  19860. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19861. // verification entirely for IP hosts, so this connection succeeded there.
  19862. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19863. // chain verification while the identity check must still fail.
  19864. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19866. ASSERT_TRUE(svr.is_valid());
  19867. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19868. std::string msg;
  19869. while (ws.read(msg)) {
  19870. ws.send(msg);
  19871. }
  19872. });
  19873. auto port = svr.bind_to_any_port("127.0.0.1");
  19874. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19875. auto se = detail::scope_exit([&] {
  19876. svr.stop();
  19877. t.join();
  19878. });
  19879. svr.wait_until_ready();
  19880. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19881. "/echo");
  19882. std::string cert;
  19883. read_file(SERVER_CERT_FILE, cert);
  19884. client.load_ca_cert_store(cert.c_str(), cert.size());
  19885. ASSERT_FALSE(client.connect());
  19886. }
  19887. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19888. // SNI, so nothing binds the host name to the TLS session. These bind the
  19889. // server to "localhost" instead, the only shape that exercises the SNI and
  19890. // hostname-verification path with certificate verification left enabled.
  19891. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19892. protected:
  19893. void Start(const char *cert_file) {
  19894. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19895. SERVER_PRIVATE_KEY_FILE);
  19896. ASSERT_TRUE(server_->is_valid());
  19897. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19898. std::string msg;
  19899. while (ws.read(msg)) {
  19900. ws.send(msg);
  19901. }
  19902. });
  19903. port_ = server_->bind_to_any_port("localhost");
  19904. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19905. server_->wait_until_ready();
  19906. }
  19907. void TearDown() override {
  19908. if (server_) { server_->stop(); }
  19909. if (server_thread_.joinable()) { server_thread_.join(); }
  19910. }
  19911. std::string url() const {
  19912. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19913. }
  19914. std::unique_ptr<SSLServer> server_;
  19915. std::thread server_thread_;
  19916. int port_ = 0;
  19917. };
  19918. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19919. // out and the connection is usable
  19920. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19921. Start(SERVER_CERT2_FILE);
  19922. ws::WebSocketClient client(url());
  19923. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19924. ASSERT_TRUE(client.connect());
  19925. ASSERT_TRUE(client.send("hello"));
  19926. std::string msg;
  19927. EXPECT_EQ(ws::Text, client.read(msg));
  19928. EXPECT_EQ("hello", msg);
  19929. client.close();
  19930. }
  19931. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19932. // while the identity check must still reject "localhost"
  19933. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19934. Start(SERVER_CERT_FILE);
  19935. ws::WebSocketClient client(url());
  19936. client.set_ca_cert_path(SERVER_CERT_FILE);
  19937. auto res = client.connect();
  19938. ASSERT_FALSE(res);
  19939. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19940. EXPECT_EQ(-1, res.status());
  19941. }
  19942. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19943. // disabled: the chain is still checked, only the identity check is skipped
  19944. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19945. Start(SERVER_CERT_FILE);
  19946. ws::WebSocketClient client(url());
  19947. client.set_ca_cert_path(SERVER_CERT_FILE);
  19948. client.enable_server_hostname_verification(false);
  19949. ASSERT_TRUE(client.connect());
  19950. ASSERT_TRUE(client.send("hello"));
  19951. std::string msg;
  19952. EXPECT_EQ(ws::Text, client.read(msg));
  19953. EXPECT_EQ("hello", msg);
  19954. client.close();
  19955. }
  19956. // A CA that did not sign the server certificate fails the chain, even though
  19957. // the name would match
  19958. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19959. Start(SERVER_CERT2_FILE);
  19960. ws::WebSocketClient client(url());
  19961. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19962. ASSERT_FALSE(client.connect());
  19963. }
  19964. // With verification disabled, neither the chain nor the name is checked
  19965. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19966. Start(SERVER_CERT_FILE);
  19967. ws::WebSocketClient client(url());
  19968. client.enable_server_certificate_verification(false);
  19969. ASSERT_TRUE(client.connect());
  19970. ASSERT_TRUE(client.send("hello"));
  19971. std::string msg;
  19972. EXPECT_EQ(ws::Text, client.read(msg));
  19973. EXPECT_EQ("hello", msg);
  19974. client.close();
  19975. }
  19976. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19977. protected:
  19978. void SetUp() override {
  19979. server_ = httplib::detail::make_unique<SSLServer>(
  19980. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19981. ASSERT_TRUE(server_->is_valid());
  19982. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19983. std::string msg;
  19984. while (ws.read(msg)) {
  19985. ws.send(msg);
  19986. }
  19987. });
  19988. port_ = server_->bind_to_any_port("localhost");
  19989. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19990. server_->wait_until_ready();
  19991. }
  19992. void TearDown() override {
  19993. server_->stop();
  19994. if (server_thread_.joinable()) { server_thread_.join(); }
  19995. }
  19996. std::string url() const {
  19997. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19998. }
  19999. void ConnectWithClientCert(const std::string &client_cert_file,
  20000. const std::string &client_private_key_file,
  20001. const char *private_key_password) {
  20002. std::string cert_pem, key_pem;
  20003. read_file(client_cert_file, cert_pem);
  20004. read_file(client_private_key_file, key_pem);
  20005. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20006. key_pem.c_str(), key_pem.size(),
  20007. private_key_password};
  20008. ws::WebSocketClient client(url(), pem);
  20009. ASSERT_TRUE(client.is_valid());
  20010. client.enable_server_certificate_verification(false);
  20011. ASSERT_TRUE(client.connect());
  20012. ASSERT_TRUE(client.send("hello"));
  20013. std::string msg;
  20014. EXPECT_EQ(ws::Text, client.read(msg));
  20015. EXPECT_EQ("hello", msg);
  20016. client.close();
  20017. }
  20018. std::unique_ptr<SSLServer> server_;
  20019. std::thread server_thread_;
  20020. int port_ = 0;
  20021. };
  20022. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20023. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20024. }
  20025. // Control for the tests above: the fixture's server really does require a
  20026. // client certificate, so it is the PEM the constructor installed that decides
  20027. // the outcome.
  20028. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20029. ws::WebSocketClient client(url());
  20030. ASSERT_TRUE(client.is_valid());
  20031. client.enable_server_certificate_verification(false);
  20032. EXPECT_FALSE(client.connect());
  20033. }
  20034. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20035. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20036. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20037. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20038. }
  20039. #endif
  20040. #if !defined(_WIN32)
  20041. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20042. auto secret_dir = std::string("./symlink_test_secret");
  20043. auto served_dir = std::string("./symlink_test_served");
  20044. auto secret_file = secret_dir + "/secret.txt";
  20045. auto symlink_path = served_dir + "/escape";
  20046. // Setup: create directories and files
  20047. mkdir(secret_dir.c_str(), 0755);
  20048. mkdir(served_dir.c_str(), 0755);
  20049. {
  20050. std::ofstream ofs(secret_file);
  20051. ofs << "SECRET_DATA";
  20052. }
  20053. // Create symlink using absolute path so it resolves correctly
  20054. #ifdef PATH_MAX
  20055. char abs_secret[PATH_MAX];
  20056. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20057. #else
  20058. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20059. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20060. ASSERT_NE(nullptr, abs_secret);
  20061. #endif
  20062. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20063. auto se = detail::scope_exit([&] {
  20064. unlink(symlink_path.c_str());
  20065. unlink(secret_file.c_str());
  20066. rmdir(served_dir.c_str());
  20067. rmdir(secret_dir.c_str());
  20068. });
  20069. Server svr;
  20070. svr.set_mount_point("/", served_dir);
  20071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20072. auto se2 = detail::scope_exit([&] {
  20073. svr.stop();
  20074. listen_thread.join();
  20075. });
  20076. svr.wait_until_ready();
  20077. Client cli("localhost", PORT);
  20078. // Symlink pointing outside base dir should be blocked
  20079. auto res = cli.Get("/escape/secret.txt");
  20080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20081. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20082. }
  20083. #endif
  20084. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20085. // A GET request with Content-Length to a static file handler must have its
  20086. // body drained before the keep-alive connection is reused. Otherwise the
  20087. // unread body bytes are interpreted as the next HTTP request.
  20088. //
  20089. // The body is sent AFTER receiving the first response (as in the original
  20090. // PoC) so that the stream_line_reader cannot buffer it together with the
  20091. // headers of the first request.
  20092. Server svr;
  20093. svr.set_mount_point("/", "./www");
  20094. std::atomic<int> smuggled_count(0);
  20095. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20096. smuggled_count++;
  20097. res.set_content("oops", "text/plain");
  20098. });
  20099. auto port = svr.bind_to_any_port("localhost");
  20100. thread t = thread([&] { svr.listen_after_bind(); });
  20101. auto se = detail::scope_exit([&] {
  20102. svr.stop();
  20103. t.join();
  20104. });
  20105. svr.wait_until_ready();
  20106. auto error = Error::Success;
  20107. auto sock = detail::create_client_socket(
  20108. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20109. /*connection_timeout_sec=*/2, 0,
  20110. /*read_timeout_sec=*/2, 0,
  20111. /*write_timeout_sec=*/2, 0, std::string(), error);
  20112. ASSERT_NE(INVALID_SOCKET, sock);
  20113. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20114. // The "smuggled" request will be sent as the body of the outer GET
  20115. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20116. "Host: localhost\r\n"
  20117. "Connection: close\r\n"
  20118. "\r\n";
  20119. // Step 1: Send only the outer request headers (no body yet)
  20120. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20121. "Host: localhost\r\n"
  20122. "Content-Length: " +
  20123. std::to_string(smuggled.size()) +
  20124. "\r\n"
  20125. "\r\n";
  20126. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20127. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20128. // Step 2: Read the first response (server serves file without reading body)
  20129. std::string first_response;
  20130. char buf[4096];
  20131. for (;;) {
  20132. auto n = recv(sock, buf, sizeof(buf), 0);
  20133. if (n <= 0) break;
  20134. first_response.append(buf, static_cast<size_t>(n));
  20135. // Stop once we have a complete response (headers + body)
  20136. auto hdr_end = first_response.find("\r\n\r\n");
  20137. if (hdr_end != std::string::npos) {
  20138. // Check for Content-Length to know when the body is complete
  20139. auto cl_pos = first_response.find("Content-Length:");
  20140. if (cl_pos != std::string::npos) {
  20141. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20142. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20143. auto cl = std::stoul(
  20144. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20145. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20146. } else {
  20147. break; // No Content-Length, assume headers-only response
  20148. }
  20149. }
  20150. }
  20151. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20152. // Step 3: Now send the body, which looks like a new HTTP request.
  20153. // On a vulnerable server the keep-alive loop reads this as a second request.
  20154. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20155. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20156. // Step 4: Try to read a second response (should NOT exist after fix)
  20157. std::string second_response;
  20158. for (;;) {
  20159. auto n = recv(sock, buf, sizeof(buf), 0);
  20160. if (n <= 0) break;
  20161. second_response.append(buf, static_cast<size_t>(n));
  20162. }
  20163. // The smuggled request must NOT have been processed
  20164. EXPECT_EQ(0, smuggled_count.load());
  20165. }
  20166. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20167. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20168. // must be rejected with 400 Bad Request.
  20169. Server svr;
  20170. svr.Post("/test", [&](const Request &, Response &res) {
  20171. res.set_content("ok", "text/plain");
  20172. });
  20173. thread t = thread([&] { svr.listen(HOST, PORT); });
  20174. auto se = detail::scope_exit([&] {
  20175. svr.stop();
  20176. t.join();
  20177. ASSERT_FALSE(svr.is_running());
  20178. });
  20179. svr.wait_until_ready();
  20180. // Exact "chunked"
  20181. {
  20182. auto req = "POST /test HTTP/1.1\r\n"
  20183. "Host: localhost\r\n"
  20184. "Content-Length: 5\r\n"
  20185. "Transfer-Encoding: chunked\r\n"
  20186. "Connection: close\r\n"
  20187. "\r\n"
  20188. "hello";
  20189. std::string response;
  20190. ASSERT_TRUE(send_request(1, req, &response));
  20191. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20192. response.substr(0, response.find("\r\n")));
  20193. }
  20194. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20195. {
  20196. auto req = "POST /test HTTP/1.1\r\n"
  20197. "Host: localhost\r\n"
  20198. "Content-Length: 5\r\n"
  20199. "Transfer-Encoding: gzip, chunked\r\n"
  20200. "Connection: close\r\n"
  20201. "\r\n"
  20202. "hello";
  20203. std::string response;
  20204. ASSERT_TRUE(send_request(1, req, &response));
  20205. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20206. response.substr(0, response.find("\r\n")));
  20207. }
  20208. }
  20209. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20210. Server svr;
  20211. svr.Post("/test", [&](const Request &, Response &res) {
  20212. res.set_content("ok", "text/plain");
  20213. });
  20214. thread t = thread([&] { svr.listen(HOST, PORT); });
  20215. auto se = detail::scope_exit([&] {
  20216. svr.stop();
  20217. t.join();
  20218. ASSERT_FALSE(svr.is_running());
  20219. });
  20220. svr.wait_until_ready();
  20221. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20222. // length cannot be determined, so the server must answer 400 and close
  20223. // rather than treat the request as bodyless and leave the body in the
  20224. // socket for the next request to pick up.
  20225. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20226. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20227. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20228. std::string response;
  20229. ASSERT_TRUE(send_request(1, req, &response));
  20230. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20231. response.substr(0, response.find("\r\n")))
  20232. << transfer_encoding;
  20233. }
  20234. // RFC 9110 5.3: the codings may also be split across several
  20235. // Transfer-Encoding lines, which combine in the order they were received.
  20236. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20237. // just like the single-line "chunked, gzip" above.
  20238. {
  20239. auto req = "POST /test HTTP/1.1\r\n"
  20240. "Host: localhost\r\n"
  20241. "Transfer-Encoding: chunked\r\n"
  20242. "Transfer-Encoding: gzip\r\n"
  20243. "\r\n"
  20244. "0\r\n\r\n";
  20245. std::string response;
  20246. ASSERT_TRUE(send_request(1, req, &response));
  20247. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20248. response.substr(0, response.find("\r\n")));
  20249. }
  20250. // A sequence ending in chunked stays valid.
  20251. auto req = "POST /test HTTP/1.1\r\n"
  20252. "Host: localhost\r\n"
  20253. "Transfer-Encoding: gzip, chunked\r\n"
  20254. "Connection: close\r\n"
  20255. "\r\n"
  20256. "0\r\n\r\n";
  20257. std::string response;
  20258. ASSERT_TRUE(send_request(1, req, &response));
  20259. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20260. // ...including when it is spread over several lines.
  20261. auto split_req = "POST /test HTTP/1.1\r\n"
  20262. "Host: localhost\r\n"
  20263. "Transfer-Encoding: gzip\r\n"
  20264. "Transfer-Encoding: chunked\r\n"
  20265. "Connection: close\r\n"
  20266. "\r\n"
  20267. "0\r\n\r\n";
  20268. std::string split_response;
  20269. ASSERT_TRUE(send_request(1, split_req, &split_response));
  20270. EXPECT_EQ("HTTP/1.1 200 OK",
  20271. split_response.substr(0, split_response.find("\r\n")));
  20272. }
  20273. // Regression for issue #2450: a DELETE without Content-Length on a
  20274. // keep-alive connection must not let the post-response drain consume the
  20275. // next request's bytes.
  20276. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  20277. Server svr;
  20278. std::atomic<int> delete_count(0);
  20279. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  20280. delete_count++;
  20281. res.status = StatusCode::NoContent_204;
  20282. });
  20283. auto port = svr.bind_to_any_port(HOST);
  20284. thread t = thread([&] { svr.listen_after_bind(); });
  20285. auto se = detail::scope_exit([&] {
  20286. svr.stop();
  20287. t.join();
  20288. });
  20289. svr.wait_until_ready();
  20290. auto error = Error::Success;
  20291. auto sock = detail::create_client_socket(
  20292. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20293. /*connection_timeout_sec=*/2, 0,
  20294. /*read_timeout_sec=*/2, 0,
  20295. /*write_timeout_sec=*/2, 0, std::string(), error);
  20296. ASSERT_NE(INVALID_SOCKET, sock);
  20297. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20298. auto send_request_and_read_response = [&](const std::string &req,
  20299. std::string &out) -> bool {
  20300. auto sent = send(sock, req.data(), req.size(), 0);
  20301. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  20302. char buf[4096];
  20303. for (;;) {
  20304. auto n = recv(sock, buf, sizeof(buf), 0);
  20305. if (n <= 0) { return !out.empty(); }
  20306. out.append(buf, static_cast<size_t>(n));
  20307. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  20308. }
  20309. };
  20310. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  20311. "Host: localhost\r\n"
  20312. "\r\n";
  20313. std::string resp1;
  20314. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  20315. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  20316. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  20317. "Host: localhost\r\n"
  20318. "Connection: close\r\n"
  20319. "\r\n";
  20320. std::string resp2;
  20321. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  20322. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  20323. EXPECT_EQ(2, delete_count.load());
  20324. }
  20325. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  20326. Server svr;
  20327. svr.Post("/ingest", [&](const Request &, Response &res,
  20328. const ContentReader &content_reader) {
  20329. auto consumed = content_reader([](const char *, size_t) { return false; });
  20330. EXPECT_FALSE(consumed);
  20331. res.status = StatusCode::Conflict_409;
  20332. res.set_header("Connection", "close");
  20333. });
  20334. auto port = svr.bind_to_any_port(HOST);
  20335. thread t = thread([&] { svr.listen_after_bind(); });
  20336. auto se = detail::scope_exit([&] {
  20337. svr.stop();
  20338. t.join();
  20339. });
  20340. svr.wait_until_ready();
  20341. auto error = Error::Success;
  20342. auto sock = detail::create_client_socket(
  20343. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20344. /*connection_timeout_sec=*/2, 0,
  20345. /*read_timeout_sec=*/1, 0,
  20346. /*write_timeout_sec=*/2, 0, std::string(), error);
  20347. ASSERT_NE(INVALID_SOCKET, sock);
  20348. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20349. std::string request = "POST /ingest HTTP/1.1\r\n"
  20350. "Host: localhost\r\n"
  20351. "Transfer-Encoding: chunked\r\n"
  20352. "\r\n"
  20353. "4\r\n"
  20354. "data\r\n";
  20355. auto sent = send(sock, request.data(), request.size(), 0);
  20356. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  20357. std::string response;
  20358. ssize_t received = 0;
  20359. do {
  20360. char buf[4096];
  20361. received = recv(sock, buf, sizeof(buf), 0);
  20362. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  20363. } while (received > 0);
  20364. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  20365. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  20366. EXPECT_EQ(0, received);
  20367. }
  20368. namespace no_proxy_test {
  20369. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  20370. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  20371. // calling listen().
  20372. class ScopedServer {
  20373. public:
  20374. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  20375. ~ScopedServer() {
  20376. svr_.stop();
  20377. if (th_.joinable()) { th_.join(); }
  20378. }
  20379. Server &svr() { return svr_; }
  20380. int port() const { return port_; }
  20381. void listen() {
  20382. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20383. svr_.wait_until_ready();
  20384. }
  20385. private:
  20386. Server svr_;
  20387. std::thread th_;
  20388. int port_ = 0;
  20389. };
  20390. class ProxyAndTargetServers {
  20391. public:
  20392. ProxyAndTargetServers() {
  20393. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  20394. proxy_hits_++;
  20395. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20396. res.set_content("via-proxy", "text/plain");
  20397. });
  20398. target_.Get(".*", [this](const Request &req, Response &res) {
  20399. target_hits_++;
  20400. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20401. res.set_content("direct", "text/plain");
  20402. });
  20403. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  20404. target_port_ = target_.bind_to_any_port("127.0.0.1");
  20405. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  20406. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  20407. proxy_mock_.wait_until_ready();
  20408. target_.wait_until_ready();
  20409. }
  20410. ~ProxyAndTargetServers() {
  20411. proxy_mock_.stop();
  20412. target_.stop();
  20413. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  20414. if (target_thread_.joinable()) { target_thread_.join(); }
  20415. }
  20416. Server &proxy_mock() { return proxy_mock_; }
  20417. Server &target() { return target_; }
  20418. int proxy_port() const { return proxy_port_; }
  20419. int target_port() const { return target_port_; }
  20420. int proxy_hits() const { return proxy_hits_.load(); }
  20421. int target_hits() const { return target_hits_.load(); }
  20422. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  20423. void reset_counters() {
  20424. proxy_hits_ = 0;
  20425. target_hits_ = 0;
  20426. last_had_proxy_authz_ = false;
  20427. }
  20428. private:
  20429. Server proxy_mock_;
  20430. Server target_;
  20431. std::thread proxy_thread_;
  20432. std::thread target_thread_;
  20433. int proxy_port_ = 0;
  20434. int target_port_ = 0;
  20435. std::atomic<int> proxy_hits_{0};
  20436. std::atomic<int> target_hits_{0};
  20437. std::atomic<bool> last_had_proxy_authz_{false};
  20438. };
  20439. inline std::unique_ptr<Client> make_client(const std::string &host,
  20440. ProxyAndTargetServers &s) {
  20441. auto cli = detail::make_unique<Client>(host, s.target_port());
  20442. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20443. cli->set_proxy("127.0.0.1", s.proxy_port());
  20444. return cli;
  20445. }
  20446. } // namespace no_proxy_test
  20447. using no_proxy_test::make_client;
  20448. using no_proxy_test::ProxyAndTargetServers;
  20449. TEST(NoProxyTest, ExactHostnameBypasses) {
  20450. ProxyAndTargetServers s;
  20451. auto cli = make_client("example.com", s);
  20452. cli->set_no_proxy({"example.com"});
  20453. auto res = cli->Get("/");
  20454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20455. EXPECT_EQ(0, s.proxy_hits());
  20456. EXPECT_EQ(1, s.target_hits());
  20457. }
  20458. TEST(NoProxyTest, SubdomainBypasses) {
  20459. ProxyAndTargetServers s;
  20460. auto cli = make_client("foo.example.com", s);
  20461. cli->set_no_proxy({"example.com"});
  20462. auto res = cli->Get("/");
  20463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20464. EXPECT_EQ(0, s.proxy_hits());
  20465. EXPECT_EQ(1, s.target_hits());
  20466. }
  20467. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20468. // Regression guard: "evilexample.com" must not be considered a subdomain
  20469. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20470. // check would let traffic bypass the proxy and leak credentials direct
  20471. // to the attacker host.
  20472. ProxyAndTargetServers s;
  20473. auto cli = make_client("evilexample.com", s);
  20474. cli->set_no_proxy({"example.com"});
  20475. auto res = cli->Get("/");
  20476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20477. EXPECT_GE(s.proxy_hits(), 1);
  20478. EXPECT_EQ(0, s.target_hits());
  20479. }
  20480. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20481. ProxyAndTargetServers s;
  20482. auto cli = make_client("example.com.evil.com", s);
  20483. cli->set_no_proxy({"example.com"});
  20484. auto res = cli->Get("/");
  20485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20486. EXPECT_GE(s.proxy_hits(), 1);
  20487. EXPECT_EQ(0, s.target_hits());
  20488. }
  20489. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20490. ProxyAndTargetServers s;
  20491. auto cli = make_client("example.com", s);
  20492. cli->set_no_proxy({".example.com"});
  20493. auto res = cli->Get("/");
  20494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20495. EXPECT_EQ(0, s.proxy_hits());
  20496. EXPECT_EQ(1, s.target_hits());
  20497. }
  20498. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20499. ProxyAndTargetServers s;
  20500. auto cli = make_client("Example.COM", s);
  20501. cli->set_no_proxy({"EXAMPLE.com"});
  20502. auto res = cli->Get("/");
  20503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20504. EXPECT_EQ(0, s.proxy_hits());
  20505. EXPECT_EQ(1, s.target_hits());
  20506. }
  20507. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20508. ProxyAndTargetServers s;
  20509. auto cli = make_client("example.com.", s);
  20510. cli->set_no_proxy({"example.com"});
  20511. auto res = cli->Get("/");
  20512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20513. EXPECT_EQ(0, s.proxy_hits());
  20514. EXPECT_EQ(1, s.target_hits());
  20515. }
  20516. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20517. // Trailing dots must be normalized on BOTH sides — host and entry.
  20518. // An implementation that only strips the host-side trailing dot would
  20519. // fail to match host "example.com" against entry "example.com." because
  20520. // a literal substring search would compare 11 chars against 12.
  20521. ProxyAndTargetServers s;
  20522. auto cli = make_client("example.com", s);
  20523. cli->set_no_proxy({"example.com."});
  20524. auto res = cli->Get("/");
  20525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20526. EXPECT_EQ(0, s.proxy_hits());
  20527. EXPECT_EQ(1, s.target_hits());
  20528. }
  20529. TEST(NoProxyTest, WildcardBypassesEverything) {
  20530. ProxyAndTargetServers s;
  20531. auto cli = make_client("anything.invalid.test", s);
  20532. cli->set_no_proxy({"*"});
  20533. auto res = cli->Get("/");
  20534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20535. EXPECT_EQ(0, s.proxy_hits());
  20536. EXPECT_EQ(1, s.target_hits());
  20537. }
  20538. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20539. ProxyAndTargetServers s;
  20540. Client cli("127.0.0.1", s.target_port());
  20541. cli.set_proxy("127.0.0.1", s.proxy_port());
  20542. cli.set_no_proxy({"127.0.0.1"});
  20543. auto res = cli.Get("/");
  20544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20545. EXPECT_EQ(0, s.proxy_hits());
  20546. EXPECT_EQ(1, s.target_hits());
  20547. }
  20548. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20549. ProxyAndTargetServers s;
  20550. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20551. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20552. cli.set_proxy("127.0.0.1", s.proxy_port());
  20553. cli.set_no_proxy({"::1"});
  20554. auto res = cli.Get("/");
  20555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20556. EXPECT_EQ(0, s.proxy_hits());
  20557. EXPECT_EQ(1, s.target_hits());
  20558. }
  20559. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20560. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20561. // must still be recognized as IPv6 for CIDR matching. Implementations
  20562. // that detect IPv6 only when the host begins with '[' would parse the
  20563. // host as a hostname and miss the match.
  20564. ProxyAndTargetServers s;
  20565. Client cli("fe80::1", s.target_port());
  20566. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20567. cli.set_proxy("127.0.0.1", s.proxy_port());
  20568. cli.set_no_proxy({"fe80::/10"});
  20569. auto res = cli.Get("/");
  20570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20571. EXPECT_EQ(0, s.proxy_hits());
  20572. EXPECT_EQ(1, s.target_hits());
  20573. }
  20574. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20575. ProxyAndTargetServers s;
  20576. Client cli("::1", s.target_port());
  20577. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20578. cli.set_proxy("127.0.0.1", s.proxy_port());
  20579. cli.set_no_proxy({"[::1]"});
  20580. auto res = cli.Get("/");
  20581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20582. EXPECT_EQ(0, s.proxy_hits());
  20583. EXPECT_EQ(1, s.target_hits());
  20584. }
  20585. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20586. ProxyAndTargetServers s;
  20587. Client cli("fe80::1", s.target_port());
  20588. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20589. cli.set_proxy("127.0.0.1", s.proxy_port());
  20590. cli.set_no_proxy({"[fe80::]/10"});
  20591. auto res = cli.Get("/");
  20592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20593. EXPECT_EQ(0, s.proxy_hits());
  20594. EXPECT_EQ(1, s.target_hits());
  20595. }
  20596. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20597. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20598. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20599. // tricks via address-family conversion.
  20600. ProxyAndTargetServers s;
  20601. Client cli("::ffff:127.0.0.1", s.target_port());
  20602. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20603. cli.set_proxy("127.0.0.1", s.proxy_port());
  20604. cli.set_no_proxy({"127.0.0.1"});
  20605. auto res = cli.Get("/");
  20606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20607. EXPECT_GE(s.proxy_hits(), 1);
  20608. EXPECT_EQ(0, s.target_hits());
  20609. }
  20610. TEST(NoProxyTest, IPv4CidrMatch) {
  20611. ProxyAndTargetServers s;
  20612. Client cli("127.0.0.1", s.target_port());
  20613. cli.set_proxy("127.0.0.1", s.proxy_port());
  20614. cli.set_no_proxy({"127.0.0.0/8"});
  20615. auto res = cli.Get("/");
  20616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20617. EXPECT_EQ(0, s.proxy_hits());
  20618. EXPECT_EQ(1, s.target_hits());
  20619. }
  20620. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20621. ProxyAndTargetServers s;
  20622. Client cli("127.0.0.1", s.target_port());
  20623. cli.set_proxy("127.0.0.1", s.proxy_port());
  20624. cli.set_no_proxy({"10.0.0.0/8"});
  20625. auto res = cli.Get("/");
  20626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20627. EXPECT_GE(s.proxy_hits(), 1);
  20628. EXPECT_EQ(0, s.target_hits());
  20629. }
  20630. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20631. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20632. // IPv4 target matches.
  20633. ProxyAndTargetServers s;
  20634. Client cli("127.0.0.1", s.target_port());
  20635. cli.set_proxy("127.0.0.1", s.proxy_port());
  20636. cli.set_no_proxy({"0.0.0.0/0"});
  20637. auto res = cli.Get("/");
  20638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20639. EXPECT_EQ(0, s.proxy_hits());
  20640. EXPECT_EQ(1, s.target_hits());
  20641. }
  20642. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20643. ProxyAndTargetServers s;
  20644. Client cli("127.0.0.1", s.target_port());
  20645. cli.set_proxy("127.0.0.1", s.proxy_port());
  20646. cli.set_no_proxy({"127.0.0.1"});
  20647. auto res = cli.Get("/");
  20648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20649. EXPECT_EQ(0, s.proxy_hits());
  20650. EXPECT_EQ(1, s.target_hits());
  20651. }
  20652. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20653. ProxyAndTargetServers s;
  20654. Client cli("127.0.0.1", s.target_port());
  20655. cli.set_proxy("127.0.0.1", s.proxy_port());
  20656. cli.set_no_proxy({"127.0.0.0/33"});
  20657. auto res = cli.Get("/");
  20658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20659. EXPECT_GE(s.proxy_hits(), 1);
  20660. EXPECT_EQ(0, s.target_hits());
  20661. }
  20662. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20663. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20664. ProxyAndTargetServers s;
  20665. Client cli("127.0.0.1", s.target_port());
  20666. cli.set_proxy("127.0.0.1", s.proxy_port());
  20667. cli.set_no_proxy({"127.0.0.1/"});
  20668. auto res = cli.Get("/");
  20669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20670. EXPECT_GE(s.proxy_hits(), 1);
  20671. EXPECT_EQ(0, s.target_hits());
  20672. }
  20673. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20674. ProxyAndTargetServers s;
  20675. auto cli = make_client("internal.corp", s);
  20676. cli->set_proxy_basic_auth("u", "p");
  20677. cli->set_no_proxy({"internal.corp"});
  20678. auto res = cli->Get("/");
  20679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20680. EXPECT_EQ(1, s.target_hits());
  20681. EXPECT_EQ(0, s.proxy_hits());
  20682. EXPECT_FALSE(s.last_had_proxy_authz())
  20683. << "Proxy-Authorization must not be sent direct to the target";
  20684. }
  20685. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20686. ProxyAndTargetServers s;
  20687. auto cli = make_client("public.example", s);
  20688. cli->set_proxy_basic_auth("u", "p");
  20689. cli->set_no_proxy({"internal.corp"}); // does not match
  20690. auto res = cli->Get("/");
  20691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20692. EXPECT_GE(s.proxy_hits(), 1);
  20693. EXPECT_TRUE(s.last_had_proxy_authz());
  20694. }
  20695. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20696. ProxyAndTargetServers s;
  20697. auto cli = make_client("anything.test", s);
  20698. auto res = cli->Get("/");
  20699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20700. EXPECT_GE(s.proxy_hits(), 1);
  20701. EXPECT_EQ(0, s.target_hits());
  20702. }
  20703. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20704. ProxyAndTargetServers s;
  20705. auto cli = make_client("example.com", s);
  20706. cli->set_no_proxy({"example.com:8080"});
  20707. auto res = cli->Get("/");
  20708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20709. EXPECT_GE(s.proxy_hits(), 1);
  20710. EXPECT_EQ(0, s.target_hits());
  20711. }
  20712. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20713. ProxyAndTargetServers s;
  20714. auto cli = make_client("anything.test", s);
  20715. cli->set_no_proxy({"", " ", "\t"});
  20716. auto res = cli->Get("/");
  20717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20718. EXPECT_GE(s.proxy_hits(), 1);
  20719. EXPECT_EQ(0, s.target_hits());
  20720. }
  20721. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20722. // An entry with leading/trailing whitespace must still match — env-style
  20723. // values are commonly pasted with stray spaces and an implementation
  20724. // that feeds the raw token directly to inet_pton would fail to match
  20725. // valid CIDRs because of the spaces.
  20726. ProxyAndTargetServers s;
  20727. Client cli("127.0.0.1", s.target_port());
  20728. cli.set_proxy("127.0.0.1", s.proxy_port());
  20729. cli.set_no_proxy({" 127.0.0.0/8 "});
  20730. auto res = cli.Get("/");
  20731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20732. EXPECT_EQ(0, s.proxy_hits());
  20733. EXPECT_EQ(1, s.target_hits());
  20734. }
  20735. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20736. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20737. // go direct and must NOT carry Proxy-Authorization.
  20738. std::atomic<int> proxy_hits{0};
  20739. std::atomic<int> target_hits{0};
  20740. std::atomic<bool> target_saw_authz{false};
  20741. no_proxy_test::ScopedServer proxy_mock, target;
  20742. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20743. proxy_hits++;
  20744. res.status = 302;
  20745. res.set_header("Location", "http://127.0.0.1:" +
  20746. std::to_string(target.port()) + "/landed");
  20747. });
  20748. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20749. target_hits++;
  20750. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20751. res.set_content("direct", "text/plain");
  20752. });
  20753. proxy_mock.listen();
  20754. target.listen();
  20755. Client cli("public.example", target.port());
  20756. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20757. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20758. cli.set_proxy_basic_auth("u", "p");
  20759. cli.set_no_proxy({"127.0.0.1"});
  20760. cli.set_follow_location(true);
  20761. auto res = cli.Get("/redir");
  20762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20763. EXPECT_GE(proxy_hits.load(), 1);
  20764. EXPECT_GE(target_hits.load(), 1);
  20765. EXPECT_FALSE(target_saw_authz.load());
  20766. }
  20767. #ifdef CPPHTTPLIB_SSL_ENABLED
  20768. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20769. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20770. // proxy creds would be sent to the (possibly hostile) origin.
  20771. std::atomic<int> target_hits{0};
  20772. std::atomic<bool> target_saw_proxy_authz{false};
  20773. no_proxy_test::ScopedServer target;
  20774. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20775. target_hits++;
  20776. if (req.has_header("Proxy-Authorization")) {
  20777. target_saw_proxy_authz = true;
  20778. }
  20779. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20780. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20781. "nonce=\"abc\", algorithm=MD5");
  20782. });
  20783. target.listen();
  20784. // The proxy address is set to the target's port: the bypass MUST kick in;
  20785. // if it doesn't, the test still routes "via proxy" to the same server and
  20786. // the Proxy-Authorization assertion below catches the leak.
  20787. Client cli("evil.example", target.port());
  20788. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20789. cli.set_proxy("127.0.0.1", target.port());
  20790. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20791. cli.set_no_proxy({"evil.example"});
  20792. auto res = cli.Get("/x");
  20793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20794. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20795. EXPECT_EQ(1, target_hits.load());
  20796. EXPECT_FALSE(target_saw_proxy_authz.load());
  20797. }
  20798. #endif
  20799. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20800. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20801. std::atomic<int> proxy_hits{0};
  20802. std::atomic<int> bypass_hits{0};
  20803. std::atomic<bool> proxy_saw_c_url{false};
  20804. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20805. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20806. proxy_hits++;
  20807. if (req.path.find("/start") != std::string::npos) {
  20808. res.status = 302;
  20809. res.set_header("Location", "http://127.0.0.1:" +
  20810. std::to_string(bypass_server.port()) +
  20811. "/middle");
  20812. return;
  20813. }
  20814. if (req.path.find("/end") != std::string::npos) {
  20815. proxy_saw_c_url = true;
  20816. res.set_content("c-via-proxy", "text/plain");
  20817. return;
  20818. }
  20819. res.set_content("unexpected", "text/plain");
  20820. });
  20821. // public.example's "advertised" port is arbitrary (the request never lands
  20822. // there — it goes through the proxy), but use a dynamic value to stay
  20823. // friendly with sharded parallel runs.
  20824. int public_port = bypass_server.port();
  20825. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20826. bypass_hits++;
  20827. res.status = 302;
  20828. res.set_header("Location", "http://public.example:" +
  20829. std::to_string(public_port) + "/end");
  20830. });
  20831. proxy_mock.listen();
  20832. bypass_server.listen();
  20833. Client cli("public.example", public_port);
  20834. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20835. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20836. cli.set_no_proxy({"127.0.0.1"});
  20837. cli.set_follow_location(true);
  20838. auto res = cli.Get("/start");
  20839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20840. EXPECT_EQ(StatusCode::OK_200, res->status);
  20841. EXPECT_EQ("c-via-proxy", res->body);
  20842. EXPECT_GE(proxy_hits.load(), 2);
  20843. EXPECT_GE(bypass_hits.load(), 1);
  20844. EXPECT_TRUE(proxy_saw_c_url.load());
  20845. }
  20846. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20847. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20848. // request reconnects to the correct endpoint.
  20849. std::atomic<int> proxy_hits{0};
  20850. std::atomic<int> target_hits{0};
  20851. no_proxy_test::ScopedServer proxy_mock, target;
  20852. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20853. proxy_hits++;
  20854. res.set_content("via-proxy", "text/plain");
  20855. });
  20856. target.svr().Get(".*", [&](const Request &, Response &res) {
  20857. target_hits++;
  20858. res.set_content("direct", "text/plain");
  20859. });
  20860. proxy_mock.listen();
  20861. target.listen();
  20862. Client cli("public.example", target.port());
  20863. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20864. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20865. cli.set_keep_alive(true);
  20866. auto res1 = cli.Get("/a");
  20867. ASSERT_TRUE(res1);
  20868. EXPECT_EQ("via-proxy", res1->body);
  20869. EXPECT_EQ(1, proxy_hits.load());
  20870. EXPECT_EQ(0, target_hits.load());
  20871. cli.set_no_proxy({"public.example"});
  20872. auto res2 = cli.Get("/b");
  20873. ASSERT_TRUE(res2);
  20874. EXPECT_EQ("direct", res2->body);
  20875. EXPECT_EQ(1, proxy_hits.load());
  20876. EXPECT_EQ(1, target_hits.load());
  20877. }
  20878. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20879. namespace proxy_tunnel_test {
  20880. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20881. class ScopedSSLServer {
  20882. public:
  20883. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20884. port_ = svr_.bind_to_any_port("127.0.0.1");
  20885. }
  20886. ~ScopedSSLServer() {
  20887. svr_.stop();
  20888. if (th_.joinable()) { th_.join(); }
  20889. }
  20890. SSLServer &svr() { return svr_; }
  20891. int port() const { return port_; }
  20892. void listen() {
  20893. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20894. svr_.wait_until_ready();
  20895. }
  20896. private:
  20897. SSLServer svr_;
  20898. std::thread th_;
  20899. int port_ = 0;
  20900. };
  20901. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20902. class ScopedConnectProxy {
  20903. public:
  20904. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20905. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20906. if (listen_fd_ < 0) { return; }
  20907. int yes = 1;
  20908. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20909. sockaddr_in a{};
  20910. a.sin_family = AF_INET;
  20911. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20912. a.sin_port = 0;
  20913. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20914. return;
  20915. }
  20916. socklen_t alen = sizeof(a);
  20917. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20918. 0) {
  20919. return;
  20920. }
  20921. port_ = ntohs(a.sin_port);
  20922. if (::listen(listen_fd_, 1) != 0) { return; }
  20923. th_ = std::thread([this] { run(); });
  20924. }
  20925. ~ScopedConnectProxy() {
  20926. stop_ = true;
  20927. if (listen_fd_ >= 0) {
  20928. ::shutdown(listen_fd_, SHUT_RDWR);
  20929. ::close(listen_fd_);
  20930. }
  20931. if (th_.joinable()) { th_.join(); }
  20932. }
  20933. int port() const { return port_; }
  20934. int connect_hits() const { return connect_hits_.load(); }
  20935. private:
  20936. void run() {
  20937. while (!stop_.load()) {
  20938. fd_set rfds;
  20939. FD_ZERO(&rfds);
  20940. FD_SET(listen_fd_, &rfds);
  20941. timeval tv{0, 100 * 1000};
  20942. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20943. if (sel <= 0) { continue; }
  20944. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20945. if (client_fd < 0) { continue; }
  20946. std::string req;
  20947. char buf[2048];
  20948. while (req.find("\r\n\r\n") == std::string::npos) {
  20949. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20950. if (n <= 0) { break; }
  20951. req.append(buf, static_cast<size_t>(n));
  20952. }
  20953. if (req.compare(0, 7, "CONNECT") != 0) {
  20954. ::close(client_fd);
  20955. continue;
  20956. }
  20957. connect_hits_++;
  20958. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20959. ::send(client_fd, ok, std::strlen(ok), 0);
  20960. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20961. sockaddr_in o{};
  20962. o.sin_family = AF_INET;
  20963. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20964. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20965. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20966. 0) {
  20967. ::close(client_fd);
  20968. ::close(origin_fd);
  20969. continue;
  20970. }
  20971. auto forward = [](int from, int to) {
  20972. char b[8192];
  20973. for (;;) {
  20974. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20975. if (n <= 0) { break; }
  20976. ssize_t off = 0;
  20977. while (off < n) {
  20978. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20979. if (s <= 0) {
  20980. off = n;
  20981. break;
  20982. }
  20983. off += s;
  20984. }
  20985. }
  20986. ::shutdown(to, SHUT_WR);
  20987. };
  20988. std::thread t1([&] { forward(client_fd, origin_fd); });
  20989. std::thread t2([&] { forward(origin_fd, client_fd); });
  20990. t1.join();
  20991. t2.join();
  20992. ::close(client_fd);
  20993. ::close(origin_fd);
  20994. }
  20995. }
  20996. int forward_port_ = -1;
  20997. int listen_fd_ = -1;
  20998. int port_ = 0;
  20999. std::thread th_;
  21000. std::atomic<bool> stop_{false};
  21001. std::atomic<int> connect_hits_{0};
  21002. };
  21003. } // namespace proxy_tunnel_test
  21004. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21005. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21006. // retry; otherwise proxy creds would be sent to the origin.
  21007. std::atomic<int> origin_hits{0};
  21008. std::atomic<bool> origin_saw_proxy_authz{false};
  21009. proxy_tunnel_test::ScopedSSLServer origin;
  21010. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21011. origin_hits++;
  21012. if (req.has_header("Proxy-Authorization")) {
  21013. origin_saw_proxy_authz = true;
  21014. }
  21015. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21016. res.set_header("Proxy-Authenticate",
  21017. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21018. "algorithm=MD5");
  21019. });
  21020. origin.listen();
  21021. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21022. ASSERT_NE(0, proxy.port());
  21023. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21024. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21025. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21026. // and answer with its own status, making this test flaky.
  21027. SSLClient cli("127.0.0.1", origin.port());
  21028. cli.enable_server_certificate_verification(false);
  21029. cli.set_proxy("127.0.0.1", proxy.port());
  21030. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21031. auto res = cli.Get("/x");
  21032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21033. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21034. EXPECT_EQ(1, origin_hits.load());
  21035. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21036. EXPECT_EQ(1, proxy.connect_hits());
  21037. }
  21038. #endif