test.cc 861 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639
  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. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  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("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges 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=0", 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=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  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(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  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. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. #endif
  2715. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2716. auto host = "google.com";
  2717. auto another_host = "example.com";
  2718. auto wrong_ip = "0.0.0.0";
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. SSLClient cli(host);
  2721. #else
  2722. Client cli(host);
  2723. #endif
  2724. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2725. auto res = cli.Get("/");
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2728. }
  2729. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2730. auto host = "google.com";
  2731. auto wrong_ip = "0.0.0.0";
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. SSLClient cli(host);
  2734. #else
  2735. Client cli(host);
  2736. #endif
  2737. cli.set_hostname_addr_map({{host, wrong_ip}});
  2738. auto res = cli.Get("/");
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Connection, res.error());
  2741. }
  2742. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2743. // A mapped value that is not an IP literal must be resolved. "localhost"
  2744. // resolves from the hosts file, so this test needs no external DNS.
  2745. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2746. auto host = "target.invalid";
  2747. Server svr;
  2748. std::string received_host;
  2749. svr.Get("/hi", [&](const Request &req, Response &res) {
  2750. received_host = req.get_header_value("Host");
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto port = svr.bind_to_any_port(HOST);
  2754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(host, port);
  2762. cli.set_hostname_addr_map({{host, HOST}});
  2763. auto res = cli.Get("/hi");
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. // The mapping only redirects the connection; the identity stays host_.
  2767. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2768. }
  2769. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2770. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2771. auto host = "target.invalid";
  2772. Server svr;
  2773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto port = svr.bind_to_any_port("127.0.0.1");
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(host, port);
  2785. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2786. auto res = cli.Get("/hi");
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::OK_200, res->status);
  2789. }
  2790. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2791. // An empty mapped value must leave host_ as the connection target. Without
  2792. // that guard the empty value would become the host argument, getaddrinfo
  2793. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2794. // loopback - silently connecting somewhere the caller never asked for.
  2795. // The server listens on loopback, so such a fallback would succeed and is
  2796. // therefore observable as a failure of this test.
  2797. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2798. Server svr;
  2799. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto port = svr.bind_to_any_port(HOST);
  2803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(blackhole, port);
  2811. cli.set_hostname_addr_map({{blackhole, ""}});
  2812. cli.set_connection_timeout(1);
  2813. auto res = cli.Get("/hi");
  2814. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2815. }
  2816. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto path = std::string{"/absolute-redirect/3"};
  2819. #ifdef CPPHTTPLIB_SSL_ENABLED
  2820. SSLClient cli(host);
  2821. #else
  2822. Client cli(host);
  2823. #endif
  2824. cli.set_follow_location(true);
  2825. auto res = cli.Get(path);
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. }
  2829. TEST(RedirectTest, Redirect_Online) {
  2830. auto host = "httpbingo.org";
  2831. auto path = std::string{"/redirect/3"};
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. SSLClient cli(host);
  2834. #else
  2835. Client cli(host);
  2836. #endif
  2837. cli.set_follow_location(true);
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. }
  2842. TEST(RelativeRedirectTest, Redirect_Online) {
  2843. auto host = "httpbingo.org";
  2844. auto path = std::string{"/relative-redirect/3"};
  2845. #ifdef CPPHTTPLIB_SSL_ENABLED
  2846. SSLClient cli(host);
  2847. #else
  2848. Client cli(host);
  2849. #endif
  2850. cli.set_follow_location(true);
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(TooManyRedirectTest, Redirect_Online) {
  2856. auto host = "httpbingo.org";
  2857. auto path = std::string{"/redirect/21"};
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. SSLClient cli(host);
  2860. #else
  2861. Client cli(host);
  2862. #endif
  2863. cli.set_follow_location(true);
  2864. auto res = cli.Get(path);
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2867. }
  2868. #ifdef CPPHTTPLIB_SSL_ENABLED
  2869. TEST(YahooRedirectTest, Redirect_Online) {
  2870. Client cli("yahoo.com");
  2871. auto res = cli.Get("/");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2874. cli.set_follow_location(true);
  2875. res = cli.Get("/");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2879. }
  2880. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2881. #define REDIR_HOST "httpbingo.org"
  2882. #define REDIR_PATH "/redirect-to"
  2883. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2884. SSLClient cli(REDIR_HOST);
  2885. cli.set_follow_location(true);
  2886. auto res =
  2887. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. params.emplace("status_code", "302");
  2897. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. }
  2901. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2902. SSLClient cli(REDIR_HOST);
  2903. cli.set_follow_location(true);
  2904. Params params;
  2905. params.emplace("url", "http://example.com");
  2906. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(UrlWithSpace, Redirect_Online) {
  2911. SSLClient cli("edge.forgecdn.net");
  2912. cli.set_follow_location(true);
  2913. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2917. }
  2918. #endif
  2919. #if !defined(_WIN32) && !defined(_WIN64)
  2920. TEST(ReceiveSignals, Signal) {
  2921. auto setupSignalHandlers = []() {
  2922. struct sigaction act;
  2923. sigemptyset(&act.sa_mask);
  2924. act.sa_flags = SA_SIGINFO;
  2925. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2926. switch (sig) {
  2927. case SIGINT:
  2928. default: break;
  2929. }
  2930. };
  2931. ::sigaction(SIGINT, &act, nullptr);
  2932. };
  2933. Server svr;
  2934. int port = 0;
  2935. auto thread = std::thread([&]() {
  2936. setupSignalHandlers();
  2937. port = svr.bind_to_any_port(HOST);
  2938. svr.listen_after_bind();
  2939. });
  2940. auto se = detail::scope_exit([&] {
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. ASSERT_TRUE(svr.is_running());
  2947. pthread_kill(thread.native_handle(), SIGINT);
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2949. ASSERT_TRUE(svr.is_running());
  2950. }
  2951. #endif
  2952. TEST(RedirectToDifferentPort, Redirect) {
  2953. Server svr1;
  2954. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. int svr1_port = 0;
  2958. auto thread1 = std::thread([&]() {
  2959. svr1_port = svr1.bind_to_any_port(HOST);
  2960. svr1.listen_after_bind();
  2961. });
  2962. Server svr2;
  2963. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2964. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2965. });
  2966. int svr2_port = 0;
  2967. auto thread2 = std::thread([&]() {
  2968. svr2_port = svr2.bind_to_any_port(HOST);
  2969. svr2.listen_after_bind();
  2970. });
  2971. auto se = detail::scope_exit([&] {
  2972. svr2.stop();
  2973. thread2.join();
  2974. svr1.stop();
  2975. thread1.join();
  2976. ASSERT_FALSE(svr2.is_running());
  2977. ASSERT_FALSE(svr1.is_running());
  2978. });
  2979. svr1.wait_until_ready();
  2980. svr2.wait_until_ready();
  2981. Client cli("localhost", svr2_port);
  2982. cli.set_follow_location(true);
  2983. auto res = cli.Get("/2");
  2984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2985. EXPECT_EQ(StatusCode::OK_200, res->status);
  2986. EXPECT_EQ("Hello World!", res->body);
  2987. }
  2988. static void
  2989. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2990. Server svr1;
  2991. std::string captured_authorization;
  2992. svr1.Get("/target", [&](const Request &req, Response &res) {
  2993. captured_authorization = req.get_header_value("Authorization");
  2994. res.set_content("OK", "text/plain");
  2995. });
  2996. int svr1_port = 0;
  2997. auto thread1 = std::thread([&]() {
  2998. svr1_port = svr1.bind_to_any_port(HOST);
  2999. svr1.listen_after_bind();
  3000. });
  3001. Server svr2;
  3002. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3003. res.set_redirect(
  3004. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3005. });
  3006. int svr2_port = 0;
  3007. auto thread2 = std::thread([&]() {
  3008. svr2_port = svr2.bind_to_any_port(HOST);
  3009. svr2.listen_after_bind();
  3010. });
  3011. auto se = detail::scope_exit([&] {
  3012. svr2.stop();
  3013. thread2.join();
  3014. svr1.stop();
  3015. thread1.join();
  3016. ASSERT_FALSE(svr2.is_running());
  3017. ASSERT_FALSE(svr1.is_running());
  3018. });
  3019. svr1.wait_until_ready();
  3020. svr2.wait_until_ready();
  3021. Client cli("localhost", svr2_port);
  3022. cli.set_follow_location(true);
  3023. set_auth(cli);
  3024. auto res = cli.Get("/redir");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::OK_200, res->status);
  3027. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3028. EXPECT_TRUE(captured_authorization.empty());
  3029. }
  3030. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3031. TestDoNotForwardCredentialsOnRedirect(
  3032. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3033. }
  3034. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3035. TestDoNotForwardCredentialsOnRedirect(
  3036. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3037. }
  3038. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3039. Server svr1;
  3040. std::string captured_cookie;
  3041. bool target_hit = false;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_cookie = req.get_header_value("Cookie");
  3044. target_hit = true;
  3045. res.set_content("OK", "text/plain");
  3046. });
  3047. int svr1_port = 0;
  3048. auto thread1 = std::thread([&]() {
  3049. svr1_port = svr1.bind_to_any_port(HOST);
  3050. svr1.listen_after_bind();
  3051. });
  3052. Server svr2;
  3053. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3054. res.set_redirect(
  3055. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3056. });
  3057. int svr2_port = 0;
  3058. auto thread2 = std::thread([&]() {
  3059. svr2_port = svr2.bind_to_any_port(HOST);
  3060. svr2.listen_after_bind();
  3061. });
  3062. auto se = detail::scope_exit([&] {
  3063. svr2.stop();
  3064. thread2.join();
  3065. svr1.stop();
  3066. thread1.join();
  3067. ASSERT_FALSE(svr2.is_running());
  3068. ASSERT_FALSE(svr1.is_running());
  3069. });
  3070. svr1.wait_until_ready();
  3071. svr2.wait_until_ready();
  3072. Client cli("localhost", svr2_port);
  3073. cli.set_follow_location(true);
  3074. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3075. auto res = cli.Get("/redir", headers);
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_TRUE(target_hit);
  3079. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3080. EXPECT_TRUE(captured_cookie.empty());
  3081. }
  3082. TEST(RedirectToSamePort, ForwardCookie) {
  3083. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3084. // header so that ordinary session flows keep working.
  3085. Server svr;
  3086. std::string captured_cookie;
  3087. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3088. res.set_redirect("/target", 302);
  3089. });
  3090. svr.Get("/target", [&](const Request &req, Response &res) {
  3091. captured_cookie = req.get_header_value("Cookie");
  3092. res.set_content("OK", "text/plain");
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_follow_location(true);
  3104. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3105. auto res = cli.Get("/redir", headers);
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3109. }
  3110. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3111. Server svr;
  3112. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3113. // Port number that overflows int — should not crash
  3114. res.set_redirect("http://localhost:99999999999999999999/target");
  3115. });
  3116. auto port = svr.bind_to_any_port(HOST);
  3117. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3118. auto se = detail::scope_exit([&] {
  3119. svr.stop();
  3120. thread.join();
  3121. ASSERT_FALSE(svr.is_running());
  3122. });
  3123. svr.wait_until_ready();
  3124. Client cli(HOST, port);
  3125. cli.set_follow_location(true);
  3126. auto res = cli.Get("/redir");
  3127. // Should fail gracefully, not crash (no valid response due to bad port)
  3128. EXPECT_FALSE(res);
  3129. }
  3130. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3131. Server svr;
  3132. auto port = svr.bind_to_any_port(HOST);
  3133. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3134. // The server's own port followed by junk must not be followed
  3135. res.set_redirect("http://" + std::string(HOST) + ":" +
  3136. std::to_string(port) + "junk/target");
  3137. });
  3138. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3139. res.set_content("target", "text/plain");
  3140. });
  3141. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3142. auto se = detail::scope_exit([&] {
  3143. svr.stop();
  3144. thread.join();
  3145. ASSERT_FALSE(svr.is_running());
  3146. });
  3147. svr.wait_until_ready();
  3148. Client cli(HOST, port);
  3149. cli.set_follow_location(true);
  3150. auto res = cli.Get("/redir");
  3151. EXPECT_FALSE(res);
  3152. }
  3153. TEST(RedirectFromPageWithContent, Redirect) {
  3154. Server svr;
  3155. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3156. res.set_content("___", "text/plain");
  3157. res.set_redirect("/2");
  3158. });
  3159. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3160. res.set_content("Hello World!", "text/plain");
  3161. });
  3162. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. th.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. {
  3170. Client cli("localhost", PORT);
  3171. cli.set_follow_location(true);
  3172. std::string body;
  3173. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3174. body.append(data, data_length);
  3175. return true;
  3176. });
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Hello World!", body);
  3180. }
  3181. {
  3182. Client cli("localhost", PORT);
  3183. std::string body;
  3184. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3185. body.append(data, data_length);
  3186. return true;
  3187. });
  3188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3189. EXPECT_EQ(StatusCode::Found_302, res->status);
  3190. EXPECT_EQ("___", body);
  3191. }
  3192. }
  3193. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3194. Server svr;
  3195. auto port_str = std::to_string(PORT);
  3196. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3197. auto expected_host = "[::1]:" + port_str;
  3198. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3199. res.set_content("___", "text/plain");
  3200. // res.set_redirect("/2");
  3201. res.set_redirect(redirect_url);
  3202. });
  3203. svr.Get("/2", [&](const Request &req, Response &res) {
  3204. auto host_header = req.headers.find("Host");
  3205. ASSERT_TRUE(host_header != req.headers.end());
  3206. EXPECT_EQ(expected_host, host_header->second);
  3207. res.set_content("Hello World!", "text/plain");
  3208. });
  3209. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3210. auto se = detail::scope_exit([&] {
  3211. svr.stop();
  3212. th.join();
  3213. ASSERT_FALSE(svr.is_running());
  3214. });
  3215. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3216. // actually starts anything, so the condition !svr.is_running() will
  3217. // always remain true, and the loop never stops.
  3218. // This basically counts how many milliseconds have passed since the
  3219. // call to svr.listen(), and if after 5 seconds nothing started yet
  3220. // aborts the test.
  3221. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3222. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3223. ASSERT_LT(milliseconds, 5000U);
  3224. }
  3225. {
  3226. Client cli("::1", PORT);
  3227. cli.set_follow_location(true);
  3228. std::string body;
  3229. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3230. body.append(data, data_length);
  3231. return true;
  3232. });
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. EXPECT_EQ("Hello World!", body);
  3236. }
  3237. {
  3238. Client cli("::1", PORT);
  3239. std::string body;
  3240. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3241. body.append(data, data_length);
  3242. return true;
  3243. });
  3244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3245. EXPECT_EQ(StatusCode::Found_302, res->status);
  3246. EXPECT_EQ("___", body);
  3247. }
  3248. }
  3249. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3250. Server svr;
  3251. svr.Get("/foo", [](const Request &req, Response &res) {
  3252. auto a = req.params.find("a");
  3253. if (a != req.params.end()) {
  3254. res.set_content((*a).second, "text/plain");
  3255. res.status = StatusCode::OK_200;
  3256. } else {
  3257. res.status = StatusCode::BadRequest_400;
  3258. }
  3259. });
  3260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3261. auto se = detail::scope_exit([&] {
  3262. svr.stop();
  3263. thread.join();
  3264. ASSERT_FALSE(svr.is_running());
  3265. });
  3266. svr.wait_until_ready();
  3267. {
  3268. Client cli(HOST, PORT);
  3269. cli.set_path_encode(false);
  3270. auto res = cli.Get("/foo?a=explicitly+encoded");
  3271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. // This expects it back with a space, as the `+` won't have been
  3274. // url-encoded, and server-side the params get decoded turning `+`
  3275. // into spaces.
  3276. EXPECT_EQ("explicitly encoded", res->body);
  3277. }
  3278. }
  3279. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3280. // When path encoding is disabled the client must transmit the supplied
  3281. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3282. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3283. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3284. // than a space (0x20). Assert on the raw wire target to catch this.
  3285. Server svr;
  3286. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3287. svr.Get("/foo", [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(expected_target, req.target);
  3289. res.status = StatusCode::OK_200;
  3290. });
  3291. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3292. auto se = detail::scope_exit([&] {
  3293. svr.stop();
  3294. thread.join();
  3295. ASSERT_FALSE(svr.is_running());
  3296. });
  3297. svr.wait_until_ready();
  3298. {
  3299. Client cli(HOST, PORT);
  3300. cli.set_path_encode(false);
  3301. auto res = cli.Get(expected_target.c_str());
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. }
  3305. }
  3306. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3307. // `open_stream()` used to skip the path encoding that the buffered send
  3308. // path applies, so the same `path` produced different bytes in the request
  3309. // line depending on which API was used. Assert the two agree.
  3310. Server svr;
  3311. std::string target;
  3312. svr.Get(".*", [&](const Request &req, Response &res) {
  3313. target = req.target;
  3314. res.status = StatusCode::OK_200;
  3315. });
  3316. auto port = svr.bind_to_any_port(HOST);
  3317. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3318. auto se = detail::scope_exit([&] {
  3319. svr.stop();
  3320. thread.join();
  3321. ASSERT_FALSE(svr.is_running());
  3322. });
  3323. svr.wait_until_ready();
  3324. struct {
  3325. const char *path;
  3326. const char *expected;
  3327. } cases[] = {
  3328. {"/a b?x=1", "/a%20b?x=1"},
  3329. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3330. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3331. };
  3332. for (const auto &c : cases) {
  3333. Client cli(HOST, port);
  3334. target.clear();
  3335. auto res = cli.Get(c.path);
  3336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3337. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3338. auto buffered_target = target;
  3339. target.clear();
  3340. auto handle = cli.open_stream("GET", c.path);
  3341. EXPECT_TRUE(handle.is_valid())
  3342. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3343. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3344. }
  3345. }
  3346. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3347. // The `set_path_encode(false)` contract — transmit the supplied target
  3348. // verbatim — must hold for the streaming API too.
  3349. Server svr;
  3350. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3351. std::string target;
  3352. svr.Get("/foo", [&](const Request &req, Response &res) {
  3353. target = req.target;
  3354. res.status = StatusCode::OK_200;
  3355. });
  3356. auto port = svr.bind_to_any_port(HOST);
  3357. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3358. auto se = detail::scope_exit([&] {
  3359. svr.stop();
  3360. thread.join();
  3361. ASSERT_FALSE(svr.is_running());
  3362. });
  3363. svr.wait_until_ready();
  3364. {
  3365. Client cli(HOST, port);
  3366. cli.set_path_encode(false);
  3367. auto handle = cli.open_stream("GET", expected_target);
  3368. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3369. EXPECT_EQ(expected_target, target);
  3370. }
  3371. }
  3372. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3373. // With path encoding enabled a CR/LF in the target is percent-encoded
  3374. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3375. // write_request_line still backstops `set_path_encode(false)`, which is
  3376. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3377. Server svr;
  3378. // Captured before routing: the decoded path contains a newline, which a
  3379. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3380. std::string target;
  3381. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3382. target = req.target;
  3383. res.status = StatusCode::OK_200;
  3384. return Server::HandlerResponse::Handled;
  3385. });
  3386. auto port = svr.bind_to_any_port(HOST);
  3387. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3388. auto se = detail::scope_exit([&] {
  3389. svr.stop();
  3390. thread.join();
  3391. ASSERT_FALSE(svr.is_running());
  3392. });
  3393. svr.wait_until_ready();
  3394. {
  3395. Client cli(HOST, port);
  3396. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3397. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3398. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3399. }
  3400. }
  3401. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3402. // Every control character is percent-encoded, not just CR/LF, so the target
  3403. // passes the request-target check in write_request_line.
  3404. Server svr;
  3405. std::string target;
  3406. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3407. target = req.target;
  3408. res.status = StatusCode::OK_200;
  3409. return Server::HandlerResponse::Handled;
  3410. });
  3411. auto port = svr.bind_to_any_port(HOST);
  3412. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3413. auto se = detail::scope_exit([&] {
  3414. svr.stop();
  3415. thread.join();
  3416. ASSERT_FALSE(svr.is_running());
  3417. });
  3418. svr.wait_until_ready();
  3419. {
  3420. Client cli(HOST, port);
  3421. auto res = cli.Get("/a\tb\x1b\x7f");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ("/a%09b%1B%7F", target);
  3424. }
  3425. }
  3426. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3427. // Nothing may reach the wire: a raw CR/LF target would split the request
  3428. // line and inject headers.
  3429. Server svr;
  3430. // Pre-routing so that "not called" means nothing reached the server at all,
  3431. // rather than merely failing to match a handler pattern.
  3432. auto handler_called = false;
  3433. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3434. handler_called = true;
  3435. res.status = StatusCode::OK_200;
  3436. return Server::HandlerResponse::Handled;
  3437. });
  3438. auto port = svr.bind_to_any_port(HOST);
  3439. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3440. auto se = detail::scope_exit([&] {
  3441. svr.stop();
  3442. thread.join();
  3443. ASSERT_FALSE(svr.is_running());
  3444. });
  3445. svr.wait_until_ready();
  3446. {
  3447. Client cli(HOST, port);
  3448. cli.set_path_encode(false);
  3449. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3450. EXPECT_FALSE(handle.is_valid());
  3451. EXPECT_EQ(Error::Write, handle.error);
  3452. EXPECT_FALSE(handler_called);
  3453. }
  3454. }
  3455. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3456. // Which of the two branches runs is decided by whether the query component
  3457. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3458. // an empty query and must still fall back to building one from
  3459. // `req.params`, while a non-empty query must win over `req.params`.
  3460. Server svr;
  3461. std::string target;
  3462. svr.Get("/foo", [&](const Request &req, Response &res) {
  3463. target = req.target;
  3464. res.status = StatusCode::OK_200;
  3465. });
  3466. auto port = svr.bind_to_any_port(HOST);
  3467. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3468. auto se = detail::scope_exit([&] {
  3469. svr.stop();
  3470. thread.join();
  3471. ASSERT_FALSE(svr.is_running());
  3472. });
  3473. svr.wait_until_ready();
  3474. {
  3475. // Trailing `?` -> empty query component -> `req.params` is used.
  3476. Client cli(HOST, port);
  3477. Request req;
  3478. req.method = "GET";
  3479. req.path = "/foo?";
  3480. req.params.emplace("a", "1");
  3481. target.clear();
  3482. auto res = cli.send(req);
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ("/foo?a=1", target);
  3485. }
  3486. {
  3487. // Non-empty query in `req.path` -> `req.params` is not appended.
  3488. Client cli(HOST, port);
  3489. Request req;
  3490. req.method = "GET";
  3491. req.path = "/foo?b=2";
  3492. req.params.emplace("a", "1");
  3493. target.clear();
  3494. auto res = cli.send(req);
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ("/foo?b=2", target);
  3497. }
  3498. }
  3499. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3500. Server svr;
  3501. svr.Get("/", [](const Request &req, Response &) {
  3502. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3503. });
  3504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. thread.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli(HOST, PORT);
  3513. cli.set_path_encode(false);
  3514. auto res = cli.Get("/?something=%0A");
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. EXPECT_EQ(StatusCode::OK_200, res->status);
  3517. }
  3518. }
  3519. TEST(BindServerTest, BindDualStack) {
  3520. Server svr;
  3521. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3522. res.set_content("Hello World!", "text/plain");
  3523. });
  3524. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3525. auto se = detail::scope_exit([&] {
  3526. svr.stop();
  3527. thread.join();
  3528. ASSERT_FALSE(svr.is_running());
  3529. });
  3530. svr.wait_until_ready();
  3531. {
  3532. Client cli("127.0.0.1", PORT);
  3533. auto res = cli.Get("/1");
  3534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3535. EXPECT_EQ(StatusCode::OK_200, res->status);
  3536. EXPECT_EQ("Hello World!", res->body);
  3537. }
  3538. {
  3539. Client cli("::1", PORT);
  3540. auto res = cli.Get("/1");
  3541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3542. EXPECT_EQ(StatusCode::OK_200, res->status);
  3543. EXPECT_EQ("Hello World!", res->body);
  3544. }
  3545. }
  3546. TEST(BindServerTest, BindAndListenSeparately) {
  3547. Server svr;
  3548. int port = svr.bind_to_any_port("0.0.0.0");
  3549. ASSERT_TRUE(svr.is_valid());
  3550. ASSERT_TRUE(port > 0);
  3551. svr.stop();
  3552. }
  3553. // Reports whether anything is still listening on a loopback port. A plain
  3554. // connect() is used instead of a Client request because a socket left bound by
  3555. // mistake accepts the connection into its backlog and never answers, which
  3556. // would hang the test instead of failing it.
  3557. static bool is_loopback_port_accepting(int port) {
  3558. sockaddr_in addr{};
  3559. addr.sin_family = AF_INET;
  3560. addr.sin_port = htons(static_cast<uint16_t>(port));
  3561. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3562. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3563. EXPECT_NE(sock, INVALID_SOCKET);
  3564. if (sock == INVALID_SOCKET) { return false; }
  3565. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3566. static_cast<socklen_t>(sizeof(addr)));
  3567. detail::close_socket(sock);
  3568. return ret == 0;
  3569. }
  3570. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3571. Server svr;
  3572. auto port = svr.bind_to_any_port("127.0.0.1");
  3573. ASSERT_TRUE(port > 0);
  3574. svr.stop();
  3575. // bind_to_any_port() already called listen(2), so until stop() closed the
  3576. // descriptor the port kept accepting connections into the backlog. ASSERT
  3577. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3578. // below blocks forever in the accept loop.
  3579. ASSERT_FALSE(is_loopback_port_accepting(port));
  3580. // Nothing is left to accept on, so listen_after_bind() must report failure
  3581. // instead of returning success without ever serving.
  3582. EXPECT_FALSE(svr.listen_after_bind());
  3583. // The failed listen marks the server decommissioned, so a waiter returns
  3584. // instead of spinning forever.
  3585. svr.wait_until_ready();
  3586. }
  3587. #ifdef CPPHTTPLIB_SSL_ENABLED
  3588. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3590. CLIENT_CA_CERT_DIR);
  3591. int port = svr.bind_to_any_port("0.0.0.0");
  3592. ASSERT_TRUE(svr.is_valid());
  3593. ASSERT_TRUE(port > 0);
  3594. svr.stop();
  3595. }
  3596. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3597. // or a rejected CustomRoute() registration would not stop the server binding.
  3598. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3600. CLIENT_CA_CERT_DIR);
  3601. ASSERT_TRUE(svr.is_valid());
  3602. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3603. EXPECT_FALSE(svr.is_valid());
  3604. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3605. }
  3606. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3607. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3608. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3609. int port = svr.bind_to_any_port("0.0.0.0");
  3610. ASSERT_TRUE(svr.is_valid());
  3611. ASSERT_TRUE(port > 0);
  3612. svr.stop();
  3613. }
  3614. TEST(BindServerTest, UpdateCertsPem) {
  3615. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3616. int port = svr.bind_to_any_port("0.0.0.0");
  3617. ASSERT_TRUE(svr.is_valid());
  3618. ASSERT_TRUE(port > 0);
  3619. // Read PEM files
  3620. std::string cert_pem, key_pem, ca_pem;
  3621. read_file(SERVER_CERT_FILE, cert_pem);
  3622. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3623. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3624. // Update server certificates using PEM API
  3625. ASSERT_TRUE(
  3626. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3627. ASSERT_TRUE(svr.is_valid());
  3628. svr.stop();
  3629. }
  3630. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3631. // Start server with client CA (enables client auth)
  3632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3633. ASSERT_TRUE(svr.is_valid());
  3634. bool handler_called = false;
  3635. svr.Get("/test", [&](const Request &req, Response &res) {
  3636. handler_called = true;
  3637. // Verify client certificate is present
  3638. auto cert = req.peer_cert();
  3639. EXPECT_TRUE(static_cast<bool>(cert));
  3640. res.set_content("ok", "text/plain");
  3641. });
  3642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3643. auto se = detail::scope_exit([&] {
  3644. svr.stop();
  3645. t.join();
  3646. ASSERT_FALSE(svr.is_running());
  3647. });
  3648. svr.wait_until_ready();
  3649. // Read PEM files
  3650. std::string cert_pem, key_pem, ca_pem;
  3651. read_file(SERVER_CERT_FILE, cert_pem);
  3652. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3653. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3654. // Update server certificates and client CA using PEM API while server running
  3655. ASSERT_TRUE(
  3656. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3657. // Connect with client certificate
  3658. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3659. cli.enable_server_certificate_verification(false);
  3660. cli.set_connection_timeout(30);
  3661. auto res = cli.Get("/test");
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. ASSERT_EQ(StatusCode::OK_200, res->status);
  3664. ASSERT_TRUE(handler_called);
  3665. EXPECT_EQ("ok", res->body);
  3666. }
  3667. #endif
  3668. TEST(ErrorHandlerTest, ContentLength) {
  3669. Server svr;
  3670. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3671. res.status = StatusCode::OK_200;
  3672. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3673. "text/html"); // <= Content-Length still 13
  3674. });
  3675. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3676. res.set_content("Hello World!\n", "text/plain");
  3677. res.status = 524;
  3678. });
  3679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3680. auto se = detail::scope_exit([&] {
  3681. svr.stop();
  3682. thread.join();
  3683. ASSERT_FALSE(svr.is_running());
  3684. });
  3685. svr.wait_until_ready();
  3686. {
  3687. Client cli(HOST, PORT);
  3688. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3690. EXPECT_EQ(StatusCode::OK_200, res->status);
  3691. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3692. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3693. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3694. }
  3695. }
  3696. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3697. TEST(ExceptionTest, WithoutExceptionHandler) {
  3698. Server svr;
  3699. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3700. throw std::runtime_error("exception...");
  3701. });
  3702. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3703. throw std::runtime_error("exception\r\n...");
  3704. });
  3705. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3706. auto se = detail::scope_exit([&] {
  3707. svr.stop();
  3708. listen_thread.join();
  3709. ASSERT_FALSE(svr.is_running());
  3710. });
  3711. svr.wait_until_ready();
  3712. Client cli("localhost", PORT);
  3713. {
  3714. auto res = cli.Get("/exception");
  3715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3716. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3717. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3718. }
  3719. {
  3720. auto res = cli.Get("/unknown");
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3723. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3724. }
  3725. }
  3726. TEST(ExceptionTest, WithExceptionHandler) {
  3727. Server svr;
  3728. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3729. std::exception_ptr ep) {
  3730. EXPECT_FALSE(ep == nullptr);
  3731. try {
  3732. std::rethrow_exception(ep);
  3733. } catch (std::exception &e) {
  3734. EXPECT_EQ("abc", std::string(e.what()));
  3735. } catch (...) {}
  3736. res.status = StatusCode::InternalServerError_500;
  3737. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3738. "text/html"); // <= Content-Length still 13 at this point
  3739. });
  3740. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3741. res.set_content("Hello World!\n", "text/plain");
  3742. throw std::runtime_error("abc");
  3743. });
  3744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3745. auto se = detail::scope_exit([&] {
  3746. svr.stop();
  3747. thread.join();
  3748. ASSERT_FALSE(svr.is_running());
  3749. });
  3750. svr.wait_until_ready();
  3751. for (size_t i = 0; i < 10; i++) {
  3752. Client cli(HOST, PORT);
  3753. for (size_t j = 0; j < 100; j++) {
  3754. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3757. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3758. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3759. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3760. }
  3761. cli.set_keep_alive(true);
  3762. for (size_t j = 0; j < 100; j++) {
  3763. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3766. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3767. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3768. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3769. }
  3770. }
  3771. }
  3772. TEST(ExceptionTest, AndErrorHandler) {
  3773. Server svr;
  3774. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3775. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3776. });
  3777. svr.set_exception_handler(
  3778. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3779. EXPECT_FALSE(ep == nullptr);
  3780. try {
  3781. std::rethrow_exception(ep);
  3782. } catch (std::exception &e) {
  3783. res.set_content(e.what(), "text/html");
  3784. } catch (...) {}
  3785. res.status = StatusCode::InternalServerError_500;
  3786. });
  3787. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3788. throw std::runtime_error("EXCEPTION");
  3789. });
  3790. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3791. res.set_content("ERROR", "text/html");
  3792. res.status = StatusCode::InternalServerError_500;
  3793. });
  3794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3795. auto se = detail::scope_exit([&] {
  3796. svr.stop();
  3797. thread.join();
  3798. ASSERT_FALSE(svr.is_running());
  3799. });
  3800. svr.wait_until_ready();
  3801. Client cli(HOST, PORT);
  3802. {
  3803. auto res = cli.Get("/exception");
  3804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3805. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("EXCEPTION", res->body);
  3807. }
  3808. {
  3809. auto res = cli.Get("/error");
  3810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3811. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3812. EXPECT_EQ("ERROR", res->body);
  3813. }
  3814. {
  3815. auto res = cli.Get("/invalid");
  3816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3818. EXPECT_EQ("NOT_FOUND", res->body);
  3819. }
  3820. }
  3821. #endif
  3822. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3823. // process_request() wraps only routing() in a try/catch, so an exception from
  3824. // any other user callback used to unwind into the task queue - which does not
  3825. // catch - and terminate the process. Each test below runs the server on a
  3826. // single worker thread: a guard that catches the exception but still loses the
  3827. // thread would otherwise be hidden by a spare worker serving the follow-up
  3828. // request. Note that a regression here aborts the whole test binary rather
  3829. // than failing one test.
  3830. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3831. Server svr;
  3832. svr.new_task_queue = [] { return new ThreadPool(1); };
  3833. std::atomic<int> reported{0};
  3834. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3835. if (err == Error::UserCallbackException) { reported++; }
  3836. });
  3837. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3838. res.set_content_provider(
  3839. 1024, "text/plain",
  3840. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3841. sink.write("hello", 5);
  3842. throw std::runtime_error("from the content provider");
  3843. });
  3844. });
  3845. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3846. res.set_content("ok", "text/plain");
  3847. });
  3848. auto port = svr.bind_to_any_port(HOST);
  3849. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3850. auto se = detail::scope_exit([&] {
  3851. svr.stop();
  3852. listen_thread.join();
  3853. ASSERT_FALSE(svr.is_running());
  3854. });
  3855. svr.wait_until_ready();
  3856. {
  3857. Client cli(HOST, port);
  3858. cli.set_read_timeout(5, 0);
  3859. EXPECT_FALSE(cli.Get("/throw"));
  3860. }
  3861. EXPECT_TRUE(svr.is_running());
  3862. EXPECT_EQ(1, reported.load());
  3863. // A request on a fresh connection is still served.
  3864. {
  3865. Client cli(HOST, port);
  3866. auto res = cli.Get("/ok");
  3867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3868. EXPECT_EQ(StatusCode::OK_200, res->status);
  3869. EXPECT_EQ("ok", res->body);
  3870. }
  3871. }
  3872. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3873. Server svr;
  3874. svr.new_task_queue = [] { return new ThreadPool(1); };
  3875. std::atomic<bool> should_throw{true};
  3876. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3877. res.set_content("hi", "text/plain");
  3878. });
  3879. svr.set_post_routing_handler(
  3880. [&](const Request & /*req*/, Response & /*res*/) {
  3881. if (should_throw) {
  3882. throw std::runtime_error("from the post-routing handler");
  3883. }
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. listen_thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. Client cli(HOST, port);
  3895. cli.set_read_timeout(5, 0);
  3896. EXPECT_FALSE(cli.Get("/hi"));
  3897. }
  3898. EXPECT_TRUE(svr.is_running());
  3899. should_throw = false;
  3900. {
  3901. Client cli(HOST, port);
  3902. auto res = cli.Get("/hi");
  3903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3904. EXPECT_EQ(StatusCode::OK_200, res->status);
  3905. EXPECT_EQ("hi", res->body);
  3906. }
  3907. }
  3908. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3909. // The guard reports the caught exception through the error logger, which is
  3910. // a user callback too. A logger that throws has to be contained as well, or
  3911. // the process would terminate from inside the catch.
  3912. Server svr;
  3913. svr.new_task_queue = [] { return new ThreadPool(1); };
  3914. std::atomic<int> reported{0};
  3915. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3916. if (err == Error::UserCallbackException) {
  3917. reported++;
  3918. throw std::runtime_error("from the error logger");
  3919. }
  3920. });
  3921. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3922. res.set_content_provider(
  3923. 1024, "text/plain",
  3924. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3925. sink.write("hello", 5);
  3926. throw std::runtime_error("from the content provider");
  3927. });
  3928. });
  3929. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3930. res.set_content("ok", "text/plain");
  3931. });
  3932. auto port = svr.bind_to_any_port(HOST);
  3933. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3934. auto se = detail::scope_exit([&] {
  3935. svr.stop();
  3936. listen_thread.join();
  3937. ASSERT_FALSE(svr.is_running());
  3938. });
  3939. svr.wait_until_ready();
  3940. {
  3941. Client cli(HOST, port);
  3942. cli.set_read_timeout(5, 0);
  3943. EXPECT_FALSE(cli.Get("/throw"));
  3944. }
  3945. EXPECT_TRUE(svr.is_running());
  3946. EXPECT_EQ(1, reported.load());
  3947. {
  3948. Client cli(HOST, port);
  3949. auto res = cli.Get("/ok");
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ("ok", res->body);
  3953. }
  3954. }
  3955. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3956. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3957. // so the exception unwinds through the ws::WebSocket object on its way to
  3958. // the guard. None of the HTTP cases above cross that.
  3959. Server svr;
  3960. svr.new_task_queue = [] { return new ThreadPool(1); };
  3961. std::atomic<int> reported{0};
  3962. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3963. if (err == Error::UserCallbackException) { reported++; }
  3964. });
  3965. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3966. throw std::runtime_error("from the WebSocket handler");
  3967. });
  3968. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3969. res.set_content("ok", "text/plain");
  3970. });
  3971. auto port = svr.bind_to_any_port(HOST);
  3972. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3973. auto se = detail::scope_exit([&] {
  3974. svr.stop();
  3975. listen_thread.join();
  3976. ASSERT_FALSE(svr.is_running());
  3977. });
  3978. svr.wait_until_ready();
  3979. {
  3980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3981. "/ws");
  3982. auto res = client.connect();
  3983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3984. // The server dropped the connection instead of dying.
  3985. std::string msg;
  3986. EXPECT_FALSE(client.read(msg));
  3987. client.close();
  3988. }
  3989. EXPECT_TRUE(svr.is_running());
  3990. EXPECT_EQ(1, reported.load());
  3991. {
  3992. Client cli(HOST, port);
  3993. auto res = cli.Get("/ok");
  3994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3995. EXPECT_EQ(StatusCode::OK_200, res->status);
  3996. EXPECT_EQ("ok", res->body);
  3997. }
  3998. }
  3999. #ifdef CPPHTTPLIB_SSL_ENABLED
  4000. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4001. // SSLServer::process_and_close_socket() is a separate overload with its own
  4002. // guard, so it is exercised on its own.
  4003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4004. ASSERT_TRUE(svr.is_valid());
  4005. svr.new_task_queue = [] { return new ThreadPool(1); };
  4006. std::atomic<int> reported{0};
  4007. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4008. if (err == Error::UserCallbackException) { reported++; }
  4009. });
  4010. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4011. res.set_content_provider(
  4012. 1024, "text/plain",
  4013. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4014. sink.write("hello", 5);
  4015. throw std::runtime_error("from the content provider");
  4016. });
  4017. });
  4018. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4019. res.set_content("ok", "text/plain");
  4020. });
  4021. auto port = svr.bind_to_any_port(HOST);
  4022. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. listen_thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. SSLClient cli(HOST, port);
  4031. cli.enable_server_certificate_verification(false);
  4032. cli.set_read_timeout(5, 0);
  4033. EXPECT_FALSE(cli.Get("/throw"));
  4034. }
  4035. EXPECT_TRUE(svr.is_running());
  4036. EXPECT_EQ(1, reported.load());
  4037. {
  4038. SSLClient cli(HOST, port);
  4039. cli.enable_server_certificate_verification(false);
  4040. auto res = cli.Get("/ok");
  4041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4042. EXPECT_EQ(StatusCode::OK_200, res->status);
  4043. EXPECT_EQ("ok", res->body);
  4044. }
  4045. }
  4046. #endif
  4047. #endif
  4048. TEST(NoContentTest, ContentLength) {
  4049. Server svr;
  4050. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4051. res.status = StatusCode::NoContent_204;
  4052. });
  4053. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4054. auto se = detail::scope_exit([&] {
  4055. svr.stop();
  4056. thread.join();
  4057. ASSERT_FALSE(svr.is_running());
  4058. });
  4059. svr.wait_until_ready();
  4060. {
  4061. Client cli(HOST, PORT);
  4062. auto res = cli.Get("/hi");
  4063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4064. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4065. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4066. }
  4067. }
  4068. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4069. #ifdef CPPHTTPLIB_SSL_ENABLED
  4070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4071. ASSERT_TRUE(svr.is_valid());
  4072. #else
  4073. Server svr;
  4074. #endif
  4075. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4076. if (req.path == "/routing_handler") {
  4077. res.set_header("PRE_ROUTING", "on");
  4078. res.set_content("Routing Handler", "text/plain");
  4079. return httplib::Server::HandlerResponse::Handled;
  4080. }
  4081. return httplib::Server::HandlerResponse::Unhandled;
  4082. });
  4083. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4084. res.set_content("Error", "text/html");
  4085. });
  4086. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4087. if (req.path == "/routing_handler") {
  4088. res.set_header("POST_ROUTING", "on");
  4089. }
  4090. });
  4091. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4092. res.set_content("Hello World!\n", "text/plain");
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. {
  4102. #ifdef CPPHTTPLIB_SSL_ENABLED
  4103. SSLClient cli(HOST, PORT);
  4104. cli.enable_server_certificate_verification(false);
  4105. #else
  4106. Client cli(HOST, PORT);
  4107. #endif
  4108. auto res = cli.Get("/routing_handler");
  4109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4110. EXPECT_EQ(StatusCode::OK_200, res->status);
  4111. EXPECT_EQ("Routing Handler", res->body);
  4112. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4113. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4114. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4115. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4116. }
  4117. {
  4118. #ifdef CPPHTTPLIB_SSL_ENABLED
  4119. SSLClient cli(HOST, PORT);
  4120. cli.enable_server_certificate_verification(false);
  4121. #else
  4122. Client cli(HOST, PORT);
  4123. #endif
  4124. auto res = cli.Get("/hi");
  4125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("Hello World!\n", res->body);
  4128. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4129. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4130. }
  4131. {
  4132. #ifdef CPPHTTPLIB_SSL_ENABLED
  4133. SSLClient cli(HOST, PORT);
  4134. cli.enable_server_certificate_verification(false);
  4135. #else
  4136. Client cli(HOST, PORT);
  4137. #endif
  4138. auto res = cli.Get("/aaa");
  4139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4140. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4141. EXPECT_EQ("Error", res->body);
  4142. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4143. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4144. }
  4145. }
  4146. TEST(RequestHandlerTest, PreRequestHandler) {
  4147. auto route_path = "/user/:user";
  4148. Server svr;
  4149. svr.Get("/hi", [](const Request &, Response &res) {
  4150. res.set_content("hi", "text/plain");
  4151. });
  4152. svr.Get(route_path, [](const Request &req, Response &res) {
  4153. res.set_content(req.path_params.at("user"), "text/plain");
  4154. });
  4155. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4156. if (req.matched_route == route_path) {
  4157. auto user = req.path_params.at("user");
  4158. if (user != "john") {
  4159. res.status = StatusCode::Forbidden_403;
  4160. res.set_content("error", "text/html");
  4161. return Server::HandlerResponse::Handled;
  4162. }
  4163. }
  4164. return Server::HandlerResponse::Unhandled;
  4165. });
  4166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4167. auto se = detail::scope_exit([&] {
  4168. svr.stop();
  4169. thread.join();
  4170. ASSERT_FALSE(svr.is_running());
  4171. });
  4172. svr.wait_until_ready();
  4173. Client cli(HOST, PORT);
  4174. {
  4175. auto res = cli.Get("/hi");
  4176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4177. EXPECT_EQ(StatusCode::OK_200, res->status);
  4178. EXPECT_EQ("hi", res->body);
  4179. }
  4180. {
  4181. auto res = cli.Get("/user/john");
  4182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4183. EXPECT_EQ(StatusCode::OK_200, res->status);
  4184. EXPECT_EQ("john", res->body);
  4185. }
  4186. {
  4187. auto res = cli.Get("/user/invalid-user");
  4188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4189. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4190. EXPECT_EQ("error", res->body);
  4191. }
  4192. }
  4193. // The pre-request handler must run before the request body is read, so a
  4194. // rejected request never forces the server to buffer a (potentially large)
  4195. // body. Here the posted body is larger than the payload limit: if the body
  4196. // were read first the server would answer 413, but because the pre-request
  4197. // handler runs first it answers 403 and the body is never read.
  4198. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4199. Server svr;
  4200. svr.set_payload_max_length(8);
  4201. auto handler_ran = false;
  4202. svr.Post("/reject", [&](const Request &req, Response &res) {
  4203. handler_ran = true;
  4204. res.set_content(req.body, "text/plain");
  4205. });
  4206. svr.Post("/accept", [](const Request &req, Response &res) {
  4207. res.set_content(req.body, "text/plain");
  4208. });
  4209. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4210. if (req.matched_route == "/reject") {
  4211. res.status = StatusCode::Forbidden_403;
  4212. res.set_content("denied", "text/plain");
  4213. return Server::HandlerResponse::Handled;
  4214. }
  4215. return Server::HandlerResponse::Unhandled;
  4216. });
  4217. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. thread.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. Client cli(HOST, PORT);
  4225. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4226. // rejects with 403 before the body is read, so 413 is never reached.
  4227. {
  4228. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4230. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4231. EXPECT_EQ("denied", res->body);
  4232. EXPECT_FALSE(handler_ran);
  4233. }
  4234. // An approved route still reads the body and enforces the payload limit.
  4235. {
  4236. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4238. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4239. }
  4240. }
  4241. TEST(UserDataTest, BasicOperations) {
  4242. httplib::UserData ud;
  4243. // Initially empty
  4244. EXPECT_FALSE(ud.has("key"));
  4245. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4246. // set and get
  4247. ud.set("key", 42);
  4248. EXPECT_TRUE(ud.has("key"));
  4249. auto *p = ud.get<int>("key");
  4250. ASSERT_NE(nullptr, p);
  4251. EXPECT_EQ(42, *p);
  4252. // Type mismatch → nullptr
  4253. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4254. // Overwrite with different type
  4255. ud.set("key", std::string("hello"));
  4256. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4257. auto *s = ud.get<std::string>("key");
  4258. ASSERT_NE(nullptr, s);
  4259. EXPECT_EQ("hello", *s);
  4260. // erase
  4261. ud.erase("key");
  4262. EXPECT_FALSE(ud.has("key"));
  4263. // clear
  4264. ud.set("a", 1);
  4265. ud.set("b", 2);
  4266. ud.clear();
  4267. EXPECT_FALSE(ud.has("a"));
  4268. EXPECT_FALSE(ud.has("b"));
  4269. }
  4270. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4271. struct AuthCtx {
  4272. std::string user_id;
  4273. };
  4274. Server svr;
  4275. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4276. res.user_data.set("auth", AuthCtx{"alice"});
  4277. return Server::HandlerResponse::Unhandled;
  4278. });
  4279. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4280. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4281. ASSERT_NE(nullptr, ctx);
  4282. res.set_content("Hello " + ctx->user_id, "text/plain");
  4283. });
  4284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4285. auto se = detail::scope_exit([&] {
  4286. svr.stop();
  4287. thread.join();
  4288. ASSERT_FALSE(svr.is_running());
  4289. });
  4290. svr.wait_until_ready();
  4291. Client cli(HOST, PORT);
  4292. auto res = cli.Get("/me");
  4293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4294. EXPECT_EQ(StatusCode::OK_200, res->status);
  4295. EXPECT_EQ("Hello alice", res->body);
  4296. }
  4297. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4298. struct RoleCtx {
  4299. std::string role;
  4300. };
  4301. Server svr;
  4302. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4303. res.user_data.set("role", RoleCtx{"admin"});
  4304. return Server::HandlerResponse::Unhandled;
  4305. });
  4306. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4307. auto *ctx = res.user_data.get<RoleCtx>("role");
  4308. ASSERT_NE(nullptr, ctx);
  4309. res.set_content(ctx->role, "text/plain");
  4310. });
  4311. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4312. auto se = detail::scope_exit([&] {
  4313. svr.stop();
  4314. thread.join();
  4315. ASSERT_FALSE(svr.is_running());
  4316. });
  4317. svr.wait_until_ready();
  4318. Client cli(HOST, PORT);
  4319. auto res = cli.Get("/role");
  4320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4321. EXPECT_EQ(StatusCode::OK_200, res->status);
  4322. EXPECT_EQ("admin", res->body);
  4323. }
  4324. TEST(InvalidFormatTest, StatusCode) {
  4325. Server svr;
  4326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4327. res.set_content("Hello World!\n", "text/plain");
  4328. res.status = 9999; // Status should be a three-digit code...
  4329. });
  4330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4331. auto se = detail::scope_exit([&] {
  4332. svr.stop();
  4333. thread.join();
  4334. ASSERT_FALSE(svr.is_running());
  4335. });
  4336. svr.wait_until_ready();
  4337. {
  4338. Client cli(HOST, PORT);
  4339. auto res = cli.Get("/hi");
  4340. ASSERT_FALSE(res);
  4341. }
  4342. }
  4343. TEST(URLFragmentTest, WithFragment) {
  4344. Server svr;
  4345. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4346. EXPECT_TRUE(req.target == "/hi");
  4347. });
  4348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4349. auto se = detail::scope_exit([&] {
  4350. svr.stop();
  4351. thread.join();
  4352. ASSERT_FALSE(svr.is_running());
  4353. });
  4354. svr.wait_until_ready();
  4355. {
  4356. Client cli(HOST, PORT);
  4357. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4358. EXPECT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::OK_200, res->status);
  4360. res = cli.Get("/hi%23key1=val1=key2=val2");
  4361. EXPECT_TRUE(res);
  4362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4363. }
  4364. }
  4365. TEST(HeaderWriter, SetHeaderWriter) {
  4366. Server svr;
  4367. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4368. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4369. return detail::write_headers(strm, hdrs);
  4370. });
  4371. svr.Get("/hi", [](const Request &req, Response &res) {
  4372. auto it = req.headers.find("CustomClientHeader");
  4373. EXPECT_TRUE(it != req.headers.end());
  4374. EXPECT_EQ(it->second, "CustomClientValue");
  4375. res.set_content("Hello World!\n", "text/plain");
  4376. });
  4377. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4378. auto se = detail::scope_exit([&] {
  4379. svr.stop();
  4380. thread.join();
  4381. ASSERT_FALSE(svr.is_running());
  4382. });
  4383. svr.wait_until_ready();
  4384. {
  4385. Client cli(HOST, PORT);
  4386. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4387. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4388. return detail::write_headers(strm, hdrs);
  4389. });
  4390. auto res = cli.Get("/hi");
  4391. EXPECT_TRUE(res);
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. auto it = res->headers.find("CustomServerHeader");
  4394. EXPECT_TRUE(it != res->headers.end());
  4395. EXPECT_EQ(it->second, "CustomServerValue");
  4396. }
  4397. }
  4398. class ServerTest : public ::testing::Test {
  4399. protected:
  4400. ServerTest()
  4401. : cli_(HOST, PORT)
  4402. #ifdef CPPHTTPLIB_SSL_ENABLED
  4403. ,
  4404. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4405. #endif
  4406. {
  4407. #ifdef CPPHTTPLIB_SSL_ENABLED
  4408. cli_.enable_server_certificate_verification(false);
  4409. #endif
  4410. // Allow LARGE_DATA (100MB) responses
  4411. cli_.set_payload_max_length(200 * 1024 * 1024);
  4412. }
  4413. virtual void SetUp() {
  4414. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4415. svr_.set_payload_max_length(200 * 1024 * 1024);
  4416. svr_.set_mount_point("/", "./www");
  4417. svr_.set_mount_point("/mount", "./www2");
  4418. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4419. svr_.Get("/hi",
  4420. [&](const Request & /*req*/, Response &res) {
  4421. res.set_content("Hello World!", "text/plain");
  4422. })
  4423. .Get("/file_content",
  4424. [&](const Request & /*req*/, Response &res) {
  4425. res.set_file_content("./www/dir/test.html");
  4426. })
  4427. .Get("/file_content_with_content_type",
  4428. [&](const Request & /*req*/, Response &res) {
  4429. res.set_file_content("./www/file", "text/plain");
  4430. })
  4431. .Get("/invalid_file_content",
  4432. [&](const Request & /*req*/, Response &res) {
  4433. res.set_file_content("./www/dir/invalid_file_path");
  4434. })
  4435. .Get("/http_response_splitting",
  4436. [&](const Request & /*req*/, Response &res) {
  4437. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4438. EXPECT_EQ(0U, res.headers.size());
  4439. EXPECT_FALSE(res.has_header("a"));
  4440. res.set_header("a", "1\nSet-Cookie: a=1");
  4441. EXPECT_EQ(0U, res.headers.size());
  4442. EXPECT_FALSE(res.has_header("a"));
  4443. res.set_header("a", "1\rSet-Cookie: a=1");
  4444. EXPECT_EQ(0U, res.headers.size());
  4445. EXPECT_FALSE(res.has_header("a"));
  4446. res.set_header("a\r\nb", "0");
  4447. EXPECT_EQ(0U, res.headers.size());
  4448. EXPECT_FALSE(res.has_header("a"));
  4449. res.set_header("a\rb", "0");
  4450. EXPECT_EQ(0U, res.headers.size());
  4451. EXPECT_FALSE(res.has_header("a"));
  4452. res.set_header("a\nb", "0");
  4453. EXPECT_EQ(0U, res.headers.size());
  4454. EXPECT_FALSE(res.has_header("a"));
  4455. res.set_redirect("1\r\nSet-Cookie: a=1");
  4456. EXPECT_EQ(0U, res.headers.size());
  4457. EXPECT_FALSE(res.has_header("Location"));
  4458. })
  4459. .Get("/slow",
  4460. [&](const Request & /*req*/, Response &res) {
  4461. std::this_thread::sleep_for(std::chrono::seconds(4));
  4462. res.set_content("slow", "text/plain");
  4463. })
  4464. #if 0
  4465. .Post("/slowpost",
  4466. [&](const Request & /*req*/, Response &res) {
  4467. std::this_thread::sleep_for(std::chrono::seconds(2));
  4468. res.set_content("slow", "text/plain");
  4469. })
  4470. #endif
  4471. .Get("/remote_addr",
  4472. [&](const Request &req, Response &res) {
  4473. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4474. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4475. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4476. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4477. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4478. #endif
  4479. res.set_content(req.remote_addr, "text/plain");
  4480. })
  4481. .Get("/local_addr",
  4482. [&](const Request &req, Response &res) {
  4483. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4484. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4485. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4486. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4487. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4488. #endif
  4489. auto local_addr = req.local_addr;
  4490. auto local_port = std::to_string(req.local_port);
  4491. res.set_content(local_addr.append(":").append(local_port),
  4492. "text/plain");
  4493. })
  4494. .Get("/endwith%",
  4495. [&](const Request & /*req*/, Response &res) {
  4496. res.set_content("Hello World!", "text/plain");
  4497. })
  4498. .Get("/a\\+\\+b",
  4499. [&](const Request &req, Response &res) {
  4500. ASSERT_TRUE(req.has_param("a +b"));
  4501. auto val = req.get_param_value("a +b");
  4502. res.set_content(val, "text/plain");
  4503. })
  4504. .Get("/", [&](const Request & /*req*/,
  4505. Response &res) { res.set_redirect("/hi"); })
  4506. .Post("/1",
  4507. [](const Request & /*req*/, Response &res) {
  4508. res.set_redirect("/2", StatusCode::SeeOther_303);
  4509. })
  4510. .Get("/2",
  4511. [](const Request & /*req*/, Response &res) {
  4512. res.set_content("redirected.", "text/plain");
  4513. res.status = StatusCode::OK_200;
  4514. })
  4515. .Post("/person",
  4516. [&](const Request &req, Response &res) {
  4517. if (req.has_param("name") && req.has_param("note")) {
  4518. persons_[req.get_param_value("name")] =
  4519. req.get_param_value("note");
  4520. } else {
  4521. res.status = StatusCode::BadRequest_400;
  4522. }
  4523. })
  4524. .Put("/person",
  4525. [&](const Request &req, Response &res) {
  4526. if (req.has_param("name") && req.has_param("note")) {
  4527. persons_[req.get_param_value("name")] =
  4528. req.get_param_value("note");
  4529. } else {
  4530. res.status = StatusCode::BadRequest_400;
  4531. }
  4532. })
  4533. .Get("/person/(.*)",
  4534. [&](const Request &req, Response &res) {
  4535. string name = req.matches[1];
  4536. if (persons_.find(name) != persons_.end()) {
  4537. auto note = persons_[name];
  4538. res.set_content(note, "text/plain");
  4539. } else {
  4540. res.status = StatusCode::NotFound_404;
  4541. }
  4542. })
  4543. .Delete("/person",
  4544. [&](const Request &req, Response &res) {
  4545. if (req.has_param("name")) {
  4546. string name = req.get_param_value("name");
  4547. if (persons_.find(name) != persons_.end()) {
  4548. persons_.erase(name);
  4549. res.set_content("DELETED", "text/plain");
  4550. } else {
  4551. res.status = StatusCode::NotFound_404;
  4552. }
  4553. } else {
  4554. res.status = StatusCode::BadRequest_400;
  4555. }
  4556. })
  4557. .Post("/x-www-form-urlencoded-json",
  4558. [&](const Request &req, Response &res) {
  4559. auto json = req.get_param_value("json");
  4560. ASSERT_EQ(JSON_DATA, json);
  4561. res.set_content(json, "appliation/json");
  4562. res.status = StatusCode::OK_200;
  4563. })
  4564. .Get("/streamed-chunked",
  4565. [&](const Request & /*req*/, Response &res) {
  4566. res.set_chunked_content_provider(
  4567. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4568. sink.os << "123";
  4569. sink.os << "456";
  4570. sink.os << "789";
  4571. sink.done();
  4572. return true;
  4573. });
  4574. })
  4575. .Get("/streamed-chunked-with-prohibited-trailer",
  4576. [&](const Request & /*req*/, Response &res) {
  4577. auto i = new int(0);
  4578. // Declare both a prohibited trailer (Content-Length) and an
  4579. // allowed one
  4580. res.set_header("Trailer", "Content-Length, X-Allowed");
  4581. res.set_chunked_content_provider(
  4582. "text/plain",
  4583. [i](size_t /*offset*/, DataSink &sink) {
  4584. switch (*i) {
  4585. case 0: sink.os << "123"; break;
  4586. case 1: sink.os << "456"; break;
  4587. case 2: sink.os << "789"; break;
  4588. case 3: {
  4589. sink.done_with_trailer(
  4590. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4591. } break;
  4592. }
  4593. (*i)++;
  4594. return true;
  4595. },
  4596. [i](bool success) {
  4597. EXPECT_TRUE(success);
  4598. delete i;
  4599. });
  4600. })
  4601. .Get("/streamed-chunked2",
  4602. [&](const Request & /*req*/, Response &res) {
  4603. auto i = new int(0);
  4604. res.set_chunked_content_provider(
  4605. "text/plain",
  4606. [i](size_t /*offset*/, DataSink &sink) {
  4607. switch (*i) {
  4608. case 0: sink.os << "123"; break;
  4609. case 1: sink.os << "456"; break;
  4610. case 2: sink.os << "789"; break;
  4611. case 3: sink.done(); break;
  4612. }
  4613. (*i)++;
  4614. return true;
  4615. },
  4616. [i](bool success) {
  4617. EXPECT_TRUE(success);
  4618. delete i;
  4619. });
  4620. })
  4621. .Get("/streamed-chunked-with-trailer",
  4622. [&](const Request & /*req*/, Response &res) {
  4623. auto i = new int(0);
  4624. res.set_header("Trailer", "Dummy1, Dummy2");
  4625. res.set_chunked_content_provider(
  4626. "text/plain",
  4627. [i](size_t /*offset*/, DataSink &sink) {
  4628. switch (*i) {
  4629. case 0: sink.os << "123"; break;
  4630. case 1: sink.os << "456"; break;
  4631. case 2: sink.os << "789"; break;
  4632. case 3: {
  4633. sink.done_with_trailer(
  4634. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4635. } break;
  4636. }
  4637. (*i)++;
  4638. return true;
  4639. },
  4640. [i](bool success) {
  4641. EXPECT_TRUE(success);
  4642. delete i;
  4643. });
  4644. })
  4645. .Get("/streamed",
  4646. [&](const Request & /*req*/, Response &res) {
  4647. res.set_content_provider(
  4648. 6, "text/plain",
  4649. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4650. sink.os << (offset < 3 ? "a" : "b");
  4651. return true;
  4652. });
  4653. })
  4654. .Get("/streamed-without-length",
  4655. [&](const Request & /*req*/, Response &res) {
  4656. auto data = new std::string("abcdefg");
  4657. res.set_content_provider(
  4658. "text/plain",
  4659. [data](size_t offset, DataSink &sink) {
  4660. if (offset < data->size()) {
  4661. sink.os << data->substr(offset);
  4662. }
  4663. sink.done();
  4664. return true;
  4665. },
  4666. [data](bool success) {
  4667. EXPECT_TRUE(success);
  4668. delete data;
  4669. });
  4670. })
  4671. .Get("/streamed-with-range",
  4672. [&](const Request &req, Response &res) {
  4673. auto data = new std::string("abcdefg");
  4674. // An explicit status keeps the server from picking the 206 it
  4675. // would otherwise choose for a ranged request, so the response
  4676. // is not a partial representation.
  4677. auto status = req.get_param_value("status");
  4678. if (status == "200") {
  4679. res.status = StatusCode::OK_200;
  4680. } else if (status == "403") {
  4681. res.status = StatusCode::Forbidden_403;
  4682. }
  4683. res.set_content_provider(
  4684. data->size(), "text/plain",
  4685. [data](size_t offset, size_t length, DataSink &sink) {
  4686. size_t DATA_CHUNK_SIZE = 4;
  4687. const auto &d = *data;
  4688. auto out_len =
  4689. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4690. auto ret =
  4691. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4692. EXPECT_TRUE(ret);
  4693. return true;
  4694. },
  4695. [data, &req](bool success) {
  4696. EXPECT_EQ(success, !req.has_param("error"));
  4697. delete data;
  4698. });
  4699. })
  4700. .Get("/streamed-cancel",
  4701. [&](const Request & /*req*/, Response &res) {
  4702. res.set_content_provider(
  4703. size_t(-1), "text/plain",
  4704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4705. sink.os << "data_chunk";
  4706. return true;
  4707. });
  4708. })
  4709. .Get("/regex-with-delimiter",
  4710. [&](const Request &req, Response & /*res*/) {
  4711. ASSERT_TRUE(req.has_param("key"));
  4712. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4713. })
  4714. .Get("/with-range",
  4715. [&](const Request & /*req*/, Response &res) {
  4716. res.set_content("abcdefg", "text/plain");
  4717. })
  4718. .Get("/test-start-time",
  4719. [&](const Request &req, Response & /*res*/) {
  4720. EXPECT_NE(req.start_time_,
  4721. std::chrono::steady_clock::time_point::min());
  4722. })
  4723. .Get("/with-range-customized-response",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. res.status = StatusCode::BadRequest_400;
  4726. res.set_content(JSON_DATA, "application/json");
  4727. })
  4728. .Post("/chunked",
  4729. [&](const Request &req, Response & /*res*/) {
  4730. EXPECT_EQ(req.body, "dechunked post body");
  4731. })
  4732. .Post("/large-chunked",
  4733. [&](const Request &req, Response & /*res*/) {
  4734. std::string expected(6 * 30 * 1024u, 'a');
  4735. EXPECT_EQ(req.body, expected);
  4736. })
  4737. .Post("/multipart",
  4738. [&](const Request &req, Response & /*res*/) {
  4739. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4740. req.form.get_field_count("text2") +
  4741. req.form.get_field_count("file3") +
  4742. req.form.get_field_count("file4"));
  4743. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4744. req.form.get_file_count("file2"));
  4745. ASSERT_TRUE(!req.form.has_file("???"));
  4746. ASSERT_TRUE(!req.form.has_field("???"));
  4747. ASSERT_TRUE(req.body.empty());
  4748. {
  4749. const auto &text = req.form.get_field("text1");
  4750. EXPECT_EQ("text default", text);
  4751. }
  4752. {
  4753. const auto &text = req.form.get_field("text2");
  4754. EXPECT_EQ("aωb", text);
  4755. }
  4756. {
  4757. const auto &file = req.form.get_file("file1");
  4758. EXPECT_EQ("hello.txt", file.filename);
  4759. EXPECT_EQ("text/plain", file.content_type);
  4760. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4761. }
  4762. {
  4763. const auto &file = req.form.get_file("file2");
  4764. EXPECT_EQ("world.json", file.filename);
  4765. EXPECT_EQ("application/json", file.content_type);
  4766. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4767. }
  4768. {
  4769. const auto &text = req.form.get_field("file3");
  4770. EXPECT_EQ(0u, text.size());
  4771. }
  4772. {
  4773. const auto &text = req.form.get_field("file4");
  4774. EXPECT_EQ(0u, text.size());
  4775. }
  4776. })
  4777. .Post("/multipart/multi_file_values",
  4778. [&](const Request &req, Response & /*res*/) {
  4779. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4780. req.form.get_field_count("multi_text1"));
  4781. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4782. ASSERT_TRUE(!req.form.has_file("???"));
  4783. ASSERT_TRUE(!req.form.has_field("???"));
  4784. ASSERT_TRUE(req.body.empty());
  4785. {
  4786. const auto &text = req.form.get_field("text");
  4787. EXPECT_EQ("default text", text);
  4788. }
  4789. {
  4790. const auto &text1_values = req.form.get_fields("multi_text1");
  4791. EXPECT_EQ(2u, text1_values.size());
  4792. EXPECT_EQ("aaaaa", text1_values[0]);
  4793. EXPECT_EQ("bbbbb", text1_values[1]);
  4794. }
  4795. {
  4796. const auto &file1_values = req.form.get_files("multi_file1");
  4797. EXPECT_EQ(2u, file1_values.size());
  4798. auto file1 = file1_values[0];
  4799. EXPECT_EQ(file1.filename, "hello.txt");
  4800. EXPECT_EQ(file1.content_type, "text/plain");
  4801. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4802. auto file2 = file1_values[1];
  4803. EXPECT_EQ(file2.filename, "world.json");
  4804. EXPECT_EQ(file2.content_type, "application/json");
  4805. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4806. }
  4807. })
  4808. .Post("/empty",
  4809. [&](const Request &req, Response &res) {
  4810. EXPECT_EQ(req.body, "");
  4811. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4812. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4813. res.set_content("empty", "text/plain");
  4814. })
  4815. .Post("/empty-no-content-type",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, "");
  4818. EXPECT_FALSE(req.has_header("Content-Type"));
  4819. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4820. res.set_content("empty-no-content-type", "text/plain");
  4821. })
  4822. .Post("/path-only",
  4823. [&](const Request &req, Response &res) {
  4824. EXPECT_EQ(req.body, "");
  4825. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4826. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4827. res.set_content("path-only", "text/plain");
  4828. })
  4829. .Post("/path-headers-only",
  4830. [&](const Request &req, Response &res) {
  4831. EXPECT_EQ(req.body, "");
  4832. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4833. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4834. EXPECT_EQ("world", req.get_header_value("hello"));
  4835. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4836. res.set_content("path-headers-only", "text/plain");
  4837. })
  4838. .Post("/post-large",
  4839. [&](const Request &req, Response &res) {
  4840. EXPECT_EQ(req.body, LARGE_DATA);
  4841. res.set_content(req.body, "text/plain");
  4842. })
  4843. .Post("/post-loopback",
  4844. [&](const Request &, Response &res,
  4845. ContentReader const &content_reader) {
  4846. std::string body;
  4847. content_reader([&](const char *data, size_t data_length) {
  4848. body.append(data, data_length);
  4849. return true;
  4850. });
  4851. res.set_content(body, "text/plain");
  4852. })
  4853. .Put("/put-loopback",
  4854. [&](const Request &, Response &res,
  4855. ContentReader const &content_reader) {
  4856. std::string body;
  4857. content_reader([&](const char *data, size_t data_length) {
  4858. body.append(data, data_length);
  4859. return true;
  4860. });
  4861. res.set_content(body, "text/plain");
  4862. })
  4863. .Patch("/patch-loopback",
  4864. [&](const Request &, Response &res,
  4865. ContentReader const &content_reader) {
  4866. std::string body;
  4867. content_reader([&](const char *data, size_t data_length) {
  4868. body.append(data, data_length);
  4869. return true;
  4870. });
  4871. res.set_content(body, "text/plain");
  4872. })
  4873. .Put("/empty-no-content-type",
  4874. [&](const Request &req, Response &res) {
  4875. EXPECT_EQ(req.body, "");
  4876. EXPECT_FALSE(req.has_header("Content-Type"));
  4877. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4878. res.set_content("empty-no-content-type", "text/plain");
  4879. })
  4880. .Put("/put",
  4881. [&](const Request &req, Response &res) {
  4882. EXPECT_EQ(req.body, "PUT");
  4883. res.set_content(req.body, "text/plain");
  4884. })
  4885. .Put("/put-large",
  4886. [&](const Request &req, Response &res) {
  4887. EXPECT_EQ(req.body, LARGE_DATA);
  4888. res.set_content(req.body, "text/plain");
  4889. })
  4890. .Patch("/patch",
  4891. [&](const Request &req, Response &res) {
  4892. EXPECT_EQ(req.body, "PATCH");
  4893. res.set_content(req.body, "text/plain");
  4894. })
  4895. .Delete("/delete",
  4896. [&](const Request & /*req*/, Response &res) {
  4897. res.set_content("DELETE", "text/plain");
  4898. })
  4899. .Delete("/delete-body",
  4900. [&](const Request &req, Response &res) {
  4901. EXPECT_EQ(req.body, "content");
  4902. res.set_content(req.body, "text/plain");
  4903. })
  4904. .Options(R"(\*)",
  4905. [&](const Request & /*req*/, Response &res) {
  4906. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4907. })
  4908. .CustomRoute("PROPFIND", "/dav/:id",
  4909. [&](const Request &req, Response &res) {
  4910. res.set_header("x-body-size",
  4911. std::to_string(req.body.size()));
  4912. res.set_header("x-matched-route", req.matched_route);
  4913. res.set_header("x-dav-id", req.path_params.at("id"));
  4914. res.status = StatusCode::MultiStatus_207;
  4915. res.set_content(req.body, "application/xml");
  4916. })
  4917. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4918. [&](const Request &req, Response &res) {
  4919. res.set_header("x-dav-match", req.matches[1]);
  4920. res.status = StatusCode::MultiStatus_207;
  4921. })
  4922. .CustomRoute("MKCOL", "/dav-mkcol",
  4923. [&](const Request &req, Response &res) {
  4924. EXPECT_TRUE(req.body.empty());
  4925. res.status = StatusCode::Created_201;
  4926. })
  4927. .CustomRoute(
  4928. "REPORT", "/dav-report",
  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. res.set_header("x-body-size", std::to_string(body.size()));
  4937. res.status = StatusCode::MultiStatus_207;
  4938. res.set_content(body, "application/xml");
  4939. })
  4940. .Get("/request-target",
  4941. [&](const Request &req, Response & /*res*/) {
  4942. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4943. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4944. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4945. })
  4946. .Get("/long-query-value",
  4947. [&](const Request &req, Response & /*res*/) {
  4948. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4949. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4950. })
  4951. .Get("/too-long-query-value",
  4952. [&](const Request &req, Response & /*res*/) {
  4953. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4954. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4955. })
  4956. .Get("/array-param",
  4957. [&](const Request &req, Response & /*res*/) {
  4958. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4959. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4960. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4961. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4962. })
  4963. .Get("/array-param-values",
  4964. [&](const Request &req, Response & /*res*/) {
  4965. auto values = req.get_param_values("array");
  4966. EXPECT_EQ(3u, values.size());
  4967. EXPECT_EQ("value1", values[0]);
  4968. EXPECT_EQ("value2", values[1]);
  4969. EXPECT_EQ("value3", values[2]);
  4970. auto empty = req.get_param_values("nonexistent");
  4971. EXPECT_TRUE(empty.empty());
  4972. })
  4973. .Post("/validate-no-multiple-headers",
  4974. [&](const Request &req, Response & /*res*/) {
  4975. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4976. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4977. })
  4978. .Post("/content_receiver",
  4979. [&](const Request &req, Response &res,
  4980. const ContentReader &content_reader) {
  4981. if (req.is_multipart_form_data()) {
  4982. std::vector<FormData> items;
  4983. content_reader(
  4984. [&](const FormData &file) {
  4985. items.push_back(file);
  4986. return true;
  4987. },
  4988. [&](const char *data, size_t data_length) {
  4989. items.back().content.append(data, data_length);
  4990. return true;
  4991. });
  4992. EXPECT_EQ(5u, items.size());
  4993. {
  4994. const auto &file = get_file_value(items, "text1");
  4995. EXPECT_TRUE(file.filename.empty());
  4996. EXPECT_EQ("text default", file.content);
  4997. }
  4998. {
  4999. const auto &file = get_file_value(items, "text2");
  5000. EXPECT_TRUE(file.filename.empty());
  5001. EXPECT_EQ("aωb", file.content);
  5002. }
  5003. {
  5004. const auto &file = get_file_value(items, "file1");
  5005. EXPECT_EQ("hello.txt", file.filename);
  5006. EXPECT_EQ("text/plain", file.content_type);
  5007. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5008. }
  5009. {
  5010. const auto &file = get_file_value(items, "file2");
  5011. EXPECT_EQ("world.json", file.filename);
  5012. EXPECT_EQ("application/json", file.content_type);
  5013. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5014. }
  5015. {
  5016. const auto &file = get_file_value(items, "file3");
  5017. EXPECT_TRUE(file.filename.empty());
  5018. EXPECT_EQ("application/octet-stream", file.content_type);
  5019. EXPECT_EQ(0u, file.content.size());
  5020. }
  5021. } else {
  5022. std::string body;
  5023. content_reader([&](const char *data, size_t data_length) {
  5024. EXPECT_EQ(7U, data_length);
  5025. body.append(data, data_length);
  5026. return true;
  5027. });
  5028. EXPECT_EQ(body, "content");
  5029. res.set_content(body, "text/plain");
  5030. }
  5031. })
  5032. .Put("/content_receiver",
  5033. [&](const Request & /*req*/, Response &res,
  5034. const ContentReader &content_reader) {
  5035. std::string body;
  5036. content_reader([&](const char *data, size_t data_length) {
  5037. body.append(data, data_length);
  5038. return true;
  5039. });
  5040. EXPECT_EQ(body, "content");
  5041. res.set_content(body, "text/plain");
  5042. })
  5043. .Patch("/content_receiver",
  5044. [&](const Request & /*req*/, Response &res,
  5045. const ContentReader &content_reader) {
  5046. std::string body;
  5047. content_reader([&](const char *data, size_t data_length) {
  5048. body.append(data, data_length);
  5049. return true;
  5050. });
  5051. EXPECT_EQ(body, "content");
  5052. res.set_content(body, "text/plain");
  5053. })
  5054. .Post("/query-string-and-body",
  5055. [&](const Request &req, Response & /*res*/) {
  5056. ASSERT_TRUE(req.has_param("key"));
  5057. EXPECT_EQ(req.get_param_value("key"), "value");
  5058. EXPECT_EQ(req.body, "content");
  5059. })
  5060. .Get("/last-request",
  5061. [&](const Request &req, Response & /*res*/) {
  5062. EXPECT_EQ("close", req.get_header_value("Connection"));
  5063. })
  5064. .Get(R"(/redirect/(\d+))",
  5065. [&](const Request &req, Response &res) {
  5066. auto num = std::stoi(req.matches[1]) + 1;
  5067. std::string url = "/redirect/" + std::to_string(num);
  5068. res.set_redirect(url);
  5069. })
  5070. .Post("/binary",
  5071. [&](const Request &req, Response &res) {
  5072. EXPECT_EQ(4U, req.body.size());
  5073. EXPECT_EQ("application/octet-stream",
  5074. req.get_header_value("Content-Type"));
  5075. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5076. res.set_content(req.body, "application/octet-stream");
  5077. })
  5078. .Put("/binary",
  5079. [&](const Request &req, Response &res) {
  5080. EXPECT_EQ(4U, req.body.size());
  5081. EXPECT_EQ("application/octet-stream",
  5082. req.get_header_value("Content-Type"));
  5083. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5084. res.set_content(req.body, "application/octet-stream");
  5085. })
  5086. .Patch("/binary",
  5087. [&](const Request &req, Response &res) {
  5088. EXPECT_EQ(4U, req.body.size());
  5089. EXPECT_EQ("application/octet-stream",
  5090. req.get_header_value("Content-Type"));
  5091. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5092. res.set_content(req.body, "application/octet-stream");
  5093. })
  5094. .Delete("/binary",
  5095. [&](const Request &req, Response &res) {
  5096. EXPECT_EQ(4U, req.body.size());
  5097. EXPECT_EQ("application/octet-stream",
  5098. req.get_header_value("Content-Type"));
  5099. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5100. res.set_content(req.body, "application/octet-stream");
  5101. })
  5102. .Get("/issue1772",
  5103. [&](const Request & /*req*/, Response &res) {
  5104. res.status = 401;
  5105. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5106. })
  5107. .Delete("/issue609",
  5108. [](const httplib::Request &, httplib::Response &res,
  5109. const httplib::ContentReader &) {
  5110. res.set_content("ok", "text/plain");
  5111. })
  5112. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5113. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5114. .Get("/compress",
  5115. [&](const Request & /*req*/, Response &res) {
  5116. res.set_content(
  5117. "12345678901234567890123456789012345678901234567890123456789"
  5118. "01234567890123456789012345678901234567890",
  5119. "text/plain");
  5120. })
  5121. .Get("/compress-with-charset",
  5122. [&](const Request & /*req*/, Response &res) {
  5123. res.set_content(
  5124. "12345678901234567890123456789012345678901234567890123456789"
  5125. "01234567890123456789012345678901234567890",
  5126. "application/json; charset=utf-8");
  5127. })
  5128. .Get("/nocompress",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.set_content(
  5131. "12345678901234567890123456789012345678901234567890123456789"
  5132. "01234567890123456789012345678901234567890",
  5133. "application/octet-stream");
  5134. })
  5135. .Post("/compress-multipart",
  5136. [&](const Request &req, Response & /*res*/) {
  5137. EXPECT_EQ(2u, req.form.fields.size());
  5138. ASSERT_TRUE(!req.form.has_field("???"));
  5139. {
  5140. const auto &text = req.form.get_field("key1");
  5141. EXPECT_EQ("test", text);
  5142. }
  5143. {
  5144. const auto &text = req.form.get_field("key2");
  5145. EXPECT_EQ("--abcdefg123", text);
  5146. }
  5147. })
  5148. #endif
  5149. ;
  5150. persons_["john"] = "programmer";
  5151. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5152. svr_.wait_until_ready();
  5153. }
  5154. virtual void TearDown() {
  5155. svr_.stop();
  5156. if (!request_threads_.empty()) {
  5157. std::this_thread::sleep_for(std::chrono::seconds(1));
  5158. for (auto &t : request_threads_) {
  5159. t.join();
  5160. }
  5161. }
  5162. t_.join();
  5163. }
  5164. map<string, string> persons_;
  5165. #ifdef CPPHTTPLIB_SSL_ENABLED
  5166. SSLClient cli_;
  5167. SSLServer svr_;
  5168. #else
  5169. Client cli_;
  5170. Server svr_;
  5171. #endif
  5172. thread t_;
  5173. std::vector<thread> request_threads_;
  5174. };
  5175. TEST_F(ServerTest, GetMethod200) {
  5176. auto res = cli_.Get("/hi");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ("HTTP/1.1", res->version);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("OK", res->reason);
  5181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5182. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5183. EXPECT_EQ("Hello World!", res->body);
  5184. }
  5185. TEST_F(ServerTest, GetEmptyFile) {
  5186. auto res = cli_.Get("/empty_file");
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::OK_200, res->status);
  5189. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5190. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5191. EXPECT_EQ("", res->body);
  5192. }
  5193. TEST_F(ServerTest, GetFileContent) {
  5194. auto res = cli_.Get("/file_content");
  5195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5198. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5199. EXPECT_EQ("test.html", res->body);
  5200. }
  5201. TEST_F(ServerTest, GetFileContentWithRange) {
  5202. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5205. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5206. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5207. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5208. EXPECT_EQ("est", res->body);
  5209. }
  5210. TEST_F(ServerTest, GetFileContentWithContentType) {
  5211. auto res = cli_.Get("/file_content_with_content_type");
  5212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5213. EXPECT_EQ(StatusCode::OK_200, res->status);
  5214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5215. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5216. EXPECT_EQ("file\n", res->body);
  5217. }
  5218. TEST_F(ServerTest, GetInvalidFileContent) {
  5219. auto res = cli_.Get("/invalid_file_content");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5222. }
  5223. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5224. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ("HTTP/1.1", res->version);
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5229. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5230. EXPECT_EQ("Hello World!", res->body);
  5231. }
  5232. TEST_F(ServerTest, GetMethod302) {
  5233. auto res = cli_.Get("/");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::Found_302, res->status);
  5236. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5237. }
  5238. TEST_F(ServerTest, GetMethod302Redirect) {
  5239. cli_.set_follow_location(true);
  5240. auto res = cli_.Get("/");
  5241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. EXPECT_EQ("Hello World!", res->body);
  5244. EXPECT_EQ("/hi", res->location);
  5245. }
  5246. TEST_F(ServerTest, GetMethod404) {
  5247. auto res = cli_.Get("/invalid");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5250. }
  5251. TEST_F(ServerTest, HeadMethod200) {
  5252. auto res = cli_.Head("/hi");
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. EXPECT_EQ(StatusCode::OK_200, res->status);
  5255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5256. EXPECT_TRUE(res->body.empty());
  5257. }
  5258. TEST_F(ServerTest, HeadMethod200Static) {
  5259. auto res = cli_.Head("/mount/dir/index.html");
  5260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5263. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5264. EXPECT_TRUE(res->body.empty());
  5265. }
  5266. TEST_F(ServerTest, HeadMethod404) {
  5267. auto res = cli_.Head("/invalid");
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5270. EXPECT_TRUE(res->body.empty());
  5271. }
  5272. TEST_F(ServerTest, GetMethodPersonJohn) {
  5273. auto res = cli_.Get("/person/john");
  5274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5275. EXPECT_EQ(StatusCode::OK_200, res->status);
  5276. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5277. EXPECT_EQ("programmer", res->body);
  5278. }
  5279. TEST_F(ServerTest, PostMethod1) {
  5280. auto res = cli_.Get("/person/john1");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5283. res = cli_.Post("/person", "name=john1&note=coder",
  5284. "application/x-www-form-urlencoded");
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. res = cli_.Get("/person/john1");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::OK_200, res->status);
  5290. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5291. ASSERT_EQ("coder", res->body);
  5292. }
  5293. TEST_F(ServerTest, PostMethod2) {
  5294. auto res = cli_.Get("/person/john2");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5297. Params params;
  5298. params.emplace("name", "john2");
  5299. params.emplace("note", "coder");
  5300. res = cli_.Post("/person", params);
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. ASSERT_EQ(StatusCode::OK_200, res->status);
  5303. res = cli_.Get("/person/john2");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::OK_200, res->status);
  5306. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5307. ASSERT_EQ("coder", res->body);
  5308. }
  5309. TEST_F(ServerTest, PutMethod3) {
  5310. auto res = cli_.Get("/person/john3");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5313. Params params;
  5314. params.emplace("name", "john3");
  5315. params.emplace("note", "coder");
  5316. res = cli_.Put("/person", params);
  5317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5318. ASSERT_EQ(StatusCode::OK_200, res->status);
  5319. res = cli_.Get("/person/john3");
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5323. ASSERT_EQ("coder", res->body);
  5324. }
  5325. TEST_F(ServerTest, DeleteMethod1) {
  5326. auto res = cli_.Get("/person/john4");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5329. Params params;
  5330. params.emplace("name", "john4");
  5331. params.emplace("note", "coder");
  5332. res = cli_.Post("/person", params);
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. ASSERT_EQ(StatusCode::OK_200, res->status);
  5335. res = cli_.Get("/person/john4");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. ASSERT_EQ(StatusCode::OK_200, res->status);
  5338. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. ASSERT_EQ("coder", res->body);
  5340. Params delete_params;
  5341. delete_params.emplace("name", "john4");
  5342. res = cli_.Delete("/person", delete_params);
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::OK_200, res->status);
  5345. ASSERT_EQ("DELETED", res->body);
  5346. res = cli_.Get("/person/john4");
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5349. }
  5350. TEST_F(ServerTest, DeleteMethod2) {
  5351. auto res = cli_.Get("/person/john5");
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5354. Params params;
  5355. params.emplace("name", "john5");
  5356. params.emplace("note", "developer");
  5357. res = cli_.Post("/person", params);
  5358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5359. ASSERT_EQ(StatusCode::OK_200, res->status);
  5360. res = cli_.Get("/person/john5");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::OK_200, res->status);
  5363. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5364. ASSERT_EQ("developer", res->body);
  5365. Params delete_params;
  5366. delete_params.emplace("name", "john5");
  5367. Headers headers;
  5368. headers.emplace("Custom-Header", "test-value");
  5369. res = cli_.Delete("/person", headers, delete_params);
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. ASSERT_EQ(StatusCode::OK_200, res->status);
  5372. ASSERT_EQ("DELETED", res->body);
  5373. res = cli_.Get("/person/john5");
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5376. }
  5377. TEST_F(ServerTest, DeleteMethod3) {
  5378. auto res = cli_.Get("/person/john6");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5381. Params params;
  5382. params.emplace("name", "john6");
  5383. params.emplace("note", "tester");
  5384. res = cli_.Post("/person", params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. res = cli_.Get("/person/john6");
  5388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5389. ASSERT_EQ(StatusCode::OK_200, res->status);
  5390. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5391. ASSERT_EQ("tester", res->body);
  5392. Params delete_params;
  5393. delete_params.emplace("name", "john6");
  5394. Headers headers;
  5395. headers.emplace("Custom-Header", "test-value");
  5396. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::OK_200, res->status);
  5399. ASSERT_EQ("DELETED", res->body);
  5400. res = cli_.Get("/person/john6");
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5403. }
  5404. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5405. Params params;
  5406. params.emplace("json", JSON_DATA);
  5407. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5409. ASSERT_EQ(StatusCode::OK_200, res->status);
  5410. ASSERT_EQ(JSON_DATA, res->body);
  5411. }
  5412. TEST_F(ServerTest, PostEmptyContent) {
  5413. auto res = cli_.Post("/empty", "", "text/plain");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. ASSERT_EQ(StatusCode::OK_200, res->status);
  5416. ASSERT_EQ("empty", res->body);
  5417. }
  5418. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5419. auto res = cli_.Post("/empty-no-content-type");
  5420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5421. ASSERT_EQ(StatusCode::OK_200, res->status);
  5422. ASSERT_EQ("empty-no-content-type", res->body);
  5423. }
  5424. TEST_F(ServerTest, PostPathOnly) {
  5425. auto res = cli_.Post("/path-only");
  5426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5427. ASSERT_EQ(StatusCode::OK_200, res->status);
  5428. ASSERT_EQ("path-only", res->body);
  5429. }
  5430. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5431. auto res = cli_.Post("/path-headers-only",
  5432. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. ASSERT_EQ(StatusCode::OK_200, res->status);
  5435. ASSERT_EQ("path-headers-only", res->body);
  5436. }
  5437. TEST_F(ServerTest, PostLarge) {
  5438. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. EXPECT_EQ(LARGE_DATA, res->body);
  5442. }
  5443. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5444. auto res = cli_.Put("/empty-no-content-type");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. ASSERT_EQ(StatusCode::OK_200, res->status);
  5447. ASSERT_EQ("empty-no-content-type", res->body);
  5448. }
  5449. TEST_F(ServerTest, GetMethodDir) {
  5450. auto res = cli_.Get("/dir/");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5454. auto body = R"(<html>
  5455. <head>
  5456. </head>
  5457. <body>
  5458. <a href="/dir/test.html">Test</a>
  5459. <a href="/hi">hi</a>
  5460. </body>
  5461. </html>
  5462. )";
  5463. EXPECT_EQ(body, res->body);
  5464. }
  5465. TEST_F(ServerTest, GetMethodDirTest) {
  5466. auto res = cli_.Get("/dir/test.html");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5470. EXPECT_EQ("test.html", res->body);
  5471. }
  5472. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5473. auto res = cli_.Get("/dir/../dir/test.html");
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::OK_200, res->status);
  5476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5477. EXPECT_EQ("test.html", res->body);
  5478. }
  5479. TEST_F(ServerTest, GetMethodInvalidPath) {
  5480. auto res = cli_.Get("/dir/../test.html");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5483. }
  5484. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5485. auto res = cli_.Get("/../www/dir/test.html");
  5486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5488. }
  5489. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5490. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5493. }
  5494. TEST_F(ServerTest, GetMethodDirMountTest) {
  5495. auto res = cli_.Get("/mount/dir/test.html");
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5499. EXPECT_EQ("test.html", res->body);
  5500. }
  5501. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5502. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("test.html", res->body);
  5507. }
  5508. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5509. auto res = cli_.Get("/mount/dir/../test.html");
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5512. }
  5513. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5514. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5517. }
  5518. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5519. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5522. }
  5523. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5524. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5527. }
  5528. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5529. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5532. }
  5533. TEST_F(ServerTest, PostMethod303) {
  5534. auto res = cli_.Post("/1", "body", "text/plain");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5537. EXPECT_EQ("/2", res->get_header_value("Location"));
  5538. }
  5539. TEST_F(ServerTest, PostMethod303Redirect) {
  5540. cli_.set_follow_location(true);
  5541. auto res = cli_.Post("/1", "body", "text/plain");
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. EXPECT_EQ("redirected.", res->body);
  5545. EXPECT_EQ("/2", res->location);
  5546. }
  5547. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5548. auto res = cli_.Get("/dir/test.abcde");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("abcde", res->body);
  5553. }
  5554. TEST_F(ServerTest, StaticFileRange) {
  5555. auto res =
  5556. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5559. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5560. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5561. EXPECT_EQ(true, res->has_header("Content-Range"));
  5562. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5563. EXPECT_EQ(std::string("cd"), res->body);
  5564. }
  5565. TEST_F(ServerTest, StaticFileRanges) {
  5566. auto res = cli_.Get("/dir/test.abcde",
  5567. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5570. EXPECT_TRUE(
  5571. res->get_header_value("Content-Type")
  5572. .find(
  5573. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5574. 0);
  5575. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5576. }
  5577. TEST_F(ServerTest, StaticFileRangeHead) {
  5578. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5581. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5582. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5583. EXPECT_EQ(true, res->has_header("Content-Range"));
  5584. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5585. }
  5586. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5587. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5592. EXPECT_EQ(true, res->has_header("Content-Range"));
  5593. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5594. res->get_header_value("Content-Range"));
  5595. EXPECT_EQ("LAST\n", res->body);
  5596. }
  5597. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5598. auto res =
  5599. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5602. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ(true, res->has_header("Content-Range"));
  5605. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5606. }
  5607. TEST_F(ServerTest, StaticFileBigFile) {
  5608. auto res = cli_.Get("/dir/1MB.txt");
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. EXPECT_EQ(StatusCode::OK_200, res->status);
  5611. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5612. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5613. }
  5614. TEST_F(ServerTest, InvalidBaseDirMount) {
  5615. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5616. }
  5617. TEST_F(ServerTest, Binary) {
  5618. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5619. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5620. "application/octet-stream");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. ASSERT_EQ(StatusCode::OK_200, res->status);
  5623. ASSERT_EQ(4U, res->body.size());
  5624. res = cli_.Put("/binary", binary.data(), binary.size(),
  5625. "application/octet-stream");
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. ASSERT_EQ(4U, res->body.size());
  5629. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5630. "application/octet-stream");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. ASSERT_EQ(StatusCode::OK_200, res->status);
  5633. ASSERT_EQ(4U, res->body.size());
  5634. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5635. "application/octet-stream");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ(4U, res->body.size());
  5639. }
  5640. TEST_F(ServerTest, BinaryString) {
  5641. auto binary = std::string("\x00\x01\x02\x03", 4);
  5642. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::OK_200, res->status);
  5645. ASSERT_EQ(4U, res->body.size());
  5646. res = cli_.Put("/binary", binary, "application/octet-stream");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::OK_200, res->status);
  5649. ASSERT_EQ(4U, res->body.size());
  5650. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. ASSERT_EQ(StatusCode::OK_200, res->status);
  5653. ASSERT_EQ(4U, res->body.size());
  5654. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. ASSERT_EQ(StatusCode::OK_200, res->status);
  5657. ASSERT_EQ(4U, res->body.size());
  5658. }
  5659. TEST_F(ServerTest, EmptyRequest) {
  5660. auto res = cli_.Get("");
  5661. ASSERT_TRUE(!res);
  5662. EXPECT_EQ(Error::Connection, res.error());
  5663. }
  5664. TEST_F(ServerTest, LongRequest) {
  5665. std::string request;
  5666. for (size_t i = 0; i < 545; i++) {
  5667. request += "/TooLongRequest";
  5668. }
  5669. request += "OK";
  5670. auto res = cli_.Get(request.c_str());
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5673. }
  5674. TEST_F(ServerTest, TooLongRequest) {
  5675. std::string request;
  5676. for (size_t i = 0; i < 546; i++) {
  5677. request += "/TooLongRequest";
  5678. }
  5679. request += "_NG";
  5680. auto start = std::chrono::high_resolution_clock::now();
  5681. cli_.set_keep_alive(true);
  5682. auto res = cli_.Get(request.c_str());
  5683. auto end = std::chrono::high_resolution_clock::now();
  5684. auto elapsed =
  5685. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5686. .count();
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5689. EXPECT_LE(elapsed, 1000);
  5690. EXPECT_EQ("close", res->get_header_value("Connection"));
  5691. EXPECT_FALSE(cli_.is_socket_open());
  5692. }
  5693. TEST_F(ServerTest, AlmostTooLongRequest) {
  5694. // test for #2046 - URI length check shouldn't include other content on req
  5695. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5696. // leading /, space, HTTP/1.1)
  5697. std::string request =
  5698. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5699. auto res = cli_.Get(request.c_str());
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5702. }
  5703. TEST_F(ServerTest, LongHeader) {
  5704. Request req;
  5705. req.method = "GET";
  5706. req.path = "/hi";
  5707. std::string host_and_port;
  5708. host_and_port += HOST;
  5709. host_and_port += ":";
  5710. host_and_port += std::to_string(PORT);
  5711. req.headers.emplace("Host", host_and_port.c_str());
  5712. req.headers.emplace("Accept", "*/*");
  5713. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5714. req.headers.emplace(
  5715. "Header-Name",
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@");
  5745. auto res = std::make_shared<Response>();
  5746. auto error = Error::Success;
  5747. auto ret = cli_.send(req, *res, error);
  5748. ASSERT_TRUE(ret);
  5749. EXPECT_EQ(StatusCode::OK_200, res->status);
  5750. }
  5751. TEST_F(ServerTest, LongQueryValue) {
  5752. auto start = std::chrono::high_resolution_clock::now();
  5753. cli_.set_keep_alive(true);
  5754. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5755. auto end = std::chrono::high_resolution_clock::now();
  5756. auto elapsed =
  5757. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5758. .count();
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5761. EXPECT_LE(elapsed, 1000);
  5762. EXPECT_EQ("close", res->get_header_value("Connection"));
  5763. EXPECT_FALSE(cli_.is_socket_open());
  5764. }
  5765. TEST_F(ServerTest, TooLongQueryValue) {
  5766. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5767. ASSERT_FALSE(res);
  5768. EXPECT_EQ(Error::Read, res.error());
  5769. }
  5770. TEST_F(ServerTest, TooLongHeader) {
  5771. Request req;
  5772. req.method = "GET";
  5773. req.path = "/hi";
  5774. std::string host_and_port;
  5775. host_and_port += HOST;
  5776. host_and_port += ":";
  5777. host_and_port += std::to_string(PORT);
  5778. req.headers.emplace("Host", host_and_port.c_str());
  5779. req.headers.emplace("Accept", "*/*");
  5780. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5781. req.headers.emplace(
  5782. "Header-Name",
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5811. "@@@@@@@@@@@@@@@@@");
  5812. auto res = std::make_shared<Response>();
  5813. auto error = Error::Success;
  5814. auto ret = cli_.send(req, *res, error);
  5815. ASSERT_TRUE(ret);
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. }
  5818. TEST_F(ServerTest, HeaderCountAtLimit) {
  5819. // Test with headers just under the 100 limit
  5820. httplib::Headers headers;
  5821. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5822. // This should keep us just under the 100 header limit
  5823. for (int i = 0; i < 95; i++) {
  5824. std::string name = "X-Test-Header-" + std::to_string(i);
  5825. std::string value = "value" + std::to_string(i);
  5826. headers.emplace(name, value);
  5827. }
  5828. // This should work fine as we're under the limit
  5829. auto res = cli_.Get("/hi", headers);
  5830. EXPECT_TRUE(res);
  5831. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5832. }
  5833. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5834. // Test with many headers to exceed the 100 limit
  5835. httplib::Headers headers;
  5836. // Add 150 headers to definitely exceed the 100 limit
  5837. for (int i = 0; i < 150; i++) {
  5838. std::string name = "X-Test-Header-" + std::to_string(i);
  5839. std::string value = "value" + std::to_string(i);
  5840. headers.emplace(name, value);
  5841. }
  5842. // This should fail due to exceeding header count limit
  5843. cli_.set_keep_alive(true);
  5844. auto res = cli_.Get("/hi", headers);
  5845. // The server should respond with 400 Bad Request
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5848. EXPECT_EQ("close", res->get_header_value("Connection"));
  5849. EXPECT_FALSE(cli_.is_socket_open());
  5850. }
  5851. TEST_F(ServerTest, PercentEncoding) {
  5852. auto res = cli_.Get("/e%6edwith%");
  5853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5854. EXPECT_EQ(StatusCode::OK_200, res->status);
  5855. }
  5856. TEST_F(ServerTest, PercentEncodingUnicode) {
  5857. auto res = cli_.Get("/e%u006edwith%");
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. }
  5861. TEST_F(ServerTest, InvalidPercentEncoding) {
  5862. auto res = cli_.Get("/%endwith%");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5865. }
  5866. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5867. auto res = cli_.Get("/%uendwith%");
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5870. }
  5871. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5872. auto res = cli_.Get("/hello?aaa=bbb%");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5875. }
  5876. TEST_F(ServerTest, PlusSignEncoding) {
  5877. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::OK_200, res->status);
  5880. EXPECT_EQ("a +b", res->body);
  5881. }
  5882. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5883. // This test simulates a potential DoS attack using many headers
  5884. // to verify our security fix prevents memory exhaustion
  5885. httplib::Headers attack_headers;
  5886. // Attempt to add many headers like an attacker would (200 headers to far
  5887. // exceed limit)
  5888. for (int i = 0; i < 200; i++) {
  5889. std::string name = "X-Attack-Header-" + std::to_string(i);
  5890. std::string value = "attack_payload_" + std::to_string(i);
  5891. attack_headers.emplace(name, value);
  5892. }
  5893. // Try to POST with excessive headers
  5894. cli_.set_keep_alive(true);
  5895. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5896. // Should either fail or return 400 Bad Request due to security limit
  5897. if (res) {
  5898. // If we get a response, it should be 400 Bad Request
  5899. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5900. EXPECT_EQ("close", res->get_header_value("Connection"));
  5901. }
  5902. EXPECT_FALSE(cli_.is_socket_open());
  5903. }
  5904. TEST_F(ServerTest, MultipartFormData) {
  5905. UploadFormDataItems items = {
  5906. {"text1", "text default", "", ""},
  5907. {"text2", "aωb", "", ""},
  5908. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5909. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5910. {"file3", "", "", "application/octet-stream"},
  5911. {"file4", "", "", " application/json tmp-string "}};
  5912. auto res = cli_.Post("/multipart", items);
  5913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. }
  5916. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5917. UploadFormDataItems items = {
  5918. {"text", "default text", "", ""},
  5919. {"multi_text1", "aaaaa", "", ""},
  5920. {"multi_text1", "bbbbb", "", ""},
  5921. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5922. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5923. "application/json"},
  5924. };
  5925. auto res = cli_.Post("/multipart/multi_file_values", items);
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. }
  5929. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5930. auto res = cli_.Get("/hi");
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::OK_200, res->status);
  5933. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5934. EXPECT_EQ("Hello World!", res->body);
  5935. }
  5936. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5937. Request req;
  5938. req.method = "POST";
  5939. req.path = "/chunked";
  5940. std::string host_and_port;
  5941. host_and_port += HOST;
  5942. host_and_port += ":";
  5943. host_and_port += std::to_string(PORT);
  5944. req.headers.emplace("Host", host_and_port.c_str());
  5945. req.headers.emplace("Accept", "*/*");
  5946. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5947. req.headers.emplace("Content-Type", "text/plain");
  5948. req.headers.emplace("Content-Length", "0");
  5949. req.headers.emplace(
  5950. "Transfer-Encoding",
  5951. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5952. // Client does not chunk, so make a chunked body manually.
  5953. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5954. auto res = std::make_shared<Response>();
  5955. auto error = Error::Success;
  5956. auto ret = cli_.send(req, *res, error);
  5957. ASSERT_TRUE(ret);
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. }
  5960. template <typename ClientT>
  5961. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5962. int expected_status) {
  5963. Request req;
  5964. req.method = "POST";
  5965. req.path = "/chunked";
  5966. std::string host_and_port;
  5967. host_and_port += HOST;
  5968. host_and_port += ":";
  5969. host_and_port += std::to_string(PORT);
  5970. req.headers.emplace("Host", host_and_port.c_str());
  5971. req.headers.emplace("Content-Length", "0");
  5972. req.headers.emplace("Transfer-Encoding", "chunked");
  5973. req.body = body;
  5974. auto res = std::make_shared<Response>();
  5975. auto error = Error::Success;
  5976. ASSERT_TRUE(cli.send(req, *res, error));
  5977. EXPECT_EQ(expected_status, res->status);
  5978. }
  5979. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5980. // rather than treat them as valid lengths.
  5981. template <typename ClientT>
  5982. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5983. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5984. }
  5985. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5986. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5987. }
  5988. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5989. expect_chunked_body_rejected(
  5990. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5991. }
  5992. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5993. // chunk-size line carries no CR, LF or other control character ahead of its
  5994. // terminator. Such a line must be refused rather than read as extension text.
  5995. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5996. expect_chunked_body_rejected(
  5997. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5998. }
  5999. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6000. expect_chunked_body_rejected(
  6001. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6002. }
  6003. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6004. expect_chunked_body_rejected(
  6005. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6006. }
  6007. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6008. // The literal stays split: a hex escape consumes every hex digit that
  6009. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6010. expect_chunked_body_rejected(
  6011. cli_, "4;a\x01"
  6012. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6013. }
  6014. TEST_F(ServerTest, AcceptsChunkExtension) {
  6015. expect_chunked_body_status(cli_,
  6016. "4;name=value\r\ndech\r\n"
  6017. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6018. "0;last\r\n\r\n",
  6019. StatusCode::OK_200);
  6020. }
  6021. TEST_F(ServerTest, GetStreamed2) {
  6022. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6025. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6026. EXPECT_EQ(true, res->has_header("Content-Range"));
  6027. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6028. EXPECT_EQ(std::string("ab"), res->body);
  6029. }
  6030. TEST_F(ServerTest, GetStreamed) {
  6031. auto res = cli_.Get("/streamed");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::OK_200, res->status);
  6034. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6035. EXPECT_EQ(std::string("aaabbb"), res->body);
  6036. }
  6037. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6038. auto res = cli_.Get("/streamed-without-length",
  6039. Headers{make_range_header({{0, -1}})});
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ(false, res->has_header("Content-Length"));
  6043. EXPECT_EQ(false, res->has_header("Content-Range"));
  6044. EXPECT_EQ(std::string("abcdefg"), res->body);
  6045. }
  6046. TEST_F(ServerTest, GetStreamedWithRange1) {
  6047. auto res =
  6048. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6051. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6052. EXPECT_EQ(true, res->has_header("Content-Range"));
  6053. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6054. EXPECT_EQ(std::string("def"), res->body);
  6055. }
  6056. TEST_F(ServerTest, GetStreamedWithRange2) {
  6057. auto res =
  6058. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6061. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6062. EXPECT_EQ(true, res->has_header("Content-Range"));
  6063. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6064. EXPECT_EQ(std::string("bcdefg"), res->body);
  6065. }
  6066. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6067. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6070. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6071. EXPECT_EQ(true, res->has_header("Content-Range"));
  6072. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6073. EXPECT_EQ(std::string("efg"), res->body);
  6074. }
  6075. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6076. auto res =
  6077. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6081. EXPECT_EQ(false, res->has_header("Content-Range"));
  6082. EXPECT_EQ(0U, res->body.size());
  6083. }
  6084. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6085. // Only a 206 is served as a partial representation. Under any other status
  6086. // `apply_ranges()` reported the full content length, so the body must match
  6087. // that header, and the content provider must never be asked for an offset
  6088. // outside the representation.
  6089. auto check = [&](int status, const char *range) {
  6090. auto path =
  6091. std::string("/streamed-with-range?status=") + std::to_string(status);
  6092. auto ctx = path + " Range: " + range;
  6093. auto res = cli_.Get(path, Headers{{"Range", range}});
  6094. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6095. EXPECT_EQ(status, res->status) << ctx;
  6096. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6098. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6099. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6100. };
  6101. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6102. check(403, "bytes=3-5");
  6103. // The offset is far past the representation.
  6104. check(403, "bytes=100000-100200");
  6105. // `first_pos` is still -1 here, and the bounds asserts in
  6106. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6107. check(403, "bytes=-3");
  6108. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6109. // multipart branch would have written one that is empty.
  6110. check(403, "bytes=1-2, 4-5");
  6111. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6112. // covers the whole representation.
  6113. check(200, "bytes=3-5");
  6114. check(200, "bytes=1-2, 4-5");
  6115. }
  6116. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6117. auto res =
  6118. cli_.Get("/streamed-with-range",
  6119. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6120. "92233720368547758079223372036854775807"}});
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6123. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6124. EXPECT_EQ(false, res->has_header("Content-Range"));
  6125. EXPECT_EQ(0U, res->body.size());
  6126. }
  6127. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6128. auto res = cli_.Get(
  6129. "/with-range",
  6130. Headers{{"Range",
  6131. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6132. {"Accept-Encoding", ""}});
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6135. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6136. EXPECT_EQ(true, res->has_header("Content-Range"));
  6137. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6138. EXPECT_EQ(std::string("abcdefg"), res->body);
  6139. }
  6140. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6141. auto res = cli_.Get("/with-range", Headers{
  6142. {"Range", "bytes=0-"},
  6143. {"Accept-Encoding", ""},
  6144. });
  6145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6147. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ(true, res->has_header("Content-Range"));
  6149. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6150. EXPECT_EQ(std::string("abcdefg"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6153. auto res = cli_.Get("/streamed-with-range",
  6154. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6157. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6158. EXPECT_EQ(false, res->has_header("Content-Range"));
  6159. EXPECT_EQ(267U, res->body.size());
  6160. // Check that both range contents are present
  6161. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6162. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6163. // Check that Content-Range headers are present for both ranges
  6164. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6165. std::string::npos);
  6166. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6167. std::string::npos);
  6168. }
  6169. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6170. Ranges ranges;
  6171. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6172. ranges.emplace_back(0, -1);
  6173. }
  6174. auto res = cli_.Get("/streamed-with-range?error",
  6175. Headers{{make_range_header(ranges)}});
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6178. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ(false, res->has_header("Content-Range"));
  6180. EXPECT_EQ(0U, res->body.size());
  6181. }
  6182. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6183. auto res = cli_.Get("/streamed-with-range",
  6184. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6187. EXPECT_EQ(5U, res->body.size());
  6188. // Check that overlapping ranges are coalesced into a single range
  6189. EXPECT_EQ("bcdef", res->body);
  6190. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6191. // Should be single range, not multipart
  6192. EXPECT_TRUE(res->has_header("Content-Range"));
  6193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6194. }
  6195. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6196. auto res = cli_.Get("/streamed-with-range",
  6197. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6200. EXPECT_EQ(268U, res->body.size());
  6201. // Check that both range contents are present
  6202. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6203. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6204. // Check that Content-Range headers are present for both ranges
  6205. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6206. std::string::npos);
  6207. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6208. std::string::npos);
  6209. }
  6210. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6211. auto res = cli_.Get("/streamed-with-range",
  6212. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6215. EXPECT_EQ(269U, res->body.size());
  6216. // Check that both duplicate range contents are present
  6217. size_t first_abc = res->body.find("abc\r\n");
  6218. EXPECT_TRUE(first_abc != std::string::npos);
  6219. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6220. EXPECT_TRUE(second_abc != std::string::npos);
  6221. // Check that Content-Range headers are present for both ranges
  6222. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6223. EXPECT_TRUE(first_range != std::string::npos);
  6224. size_t second_range =
  6225. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6226. EXPECT_TRUE(second_range != std::string::npos);
  6227. }
  6228. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6229. auto res =
  6230. cli_.Get("/streamed-with-range?error",
  6231. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6234. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6235. EXPECT_EQ(false, res->has_header("Content-Range"));
  6236. EXPECT_EQ(0U, res->body.size());
  6237. }
  6238. TEST_F(ServerTest, GetStreamedEndless) {
  6239. uint64_t offset = 0;
  6240. auto res = cli_.Get("/streamed-cancel",
  6241. [&](const char * /*data*/, uint64_t data_length) {
  6242. if (offset < 100) {
  6243. offset += data_length;
  6244. return true;
  6245. }
  6246. return false;
  6247. });
  6248. ASSERT_TRUE(!res);
  6249. EXPECT_EQ(Error::Canceled, res.error());
  6250. }
  6251. TEST_F(ServerTest, ClientStop) {
  6252. std::atomic_size_t count{4};
  6253. std::vector<std::thread> threads;
  6254. for (auto i = count.load(); i != 0; --i) {
  6255. threads.emplace_back([&]() {
  6256. auto res = cli_.Get("/streamed-cancel",
  6257. [&](const char *, uint64_t) { return true; });
  6258. --count;
  6259. ASSERT_TRUE(!res);
  6260. EXPECT_TRUE(res.error() == Error::Canceled ||
  6261. res.error() == Error::Read || res.error() == Error::Write);
  6262. });
  6263. }
  6264. std::this_thread::sleep_for(std::chrono::seconds(2));
  6265. while (count != 0) {
  6266. cli_.stop();
  6267. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6268. }
  6269. for (auto &t : threads) {
  6270. t.join();
  6271. }
  6272. }
  6273. TEST_F(ServerTest, GetWithRange1) {
  6274. auto res = cli_.Get("/with-range", Headers{
  6275. make_range_header({{3, 5}}),
  6276. {"Accept-Encoding", ""},
  6277. });
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6280. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6281. EXPECT_EQ(true, res->has_header("Content-Range"));
  6282. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6283. EXPECT_EQ(std::string("def"), res->body);
  6284. }
  6285. TEST_F(ServerTest, GetWithRange2) {
  6286. auto res = cli_.Get("/with-range", Headers{
  6287. make_range_header({{1, -1}}),
  6288. {"Accept-Encoding", ""},
  6289. });
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6292. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6293. EXPECT_EQ(true, res->has_header("Content-Range"));
  6294. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6295. EXPECT_EQ(std::string("bcdefg"), res->body);
  6296. }
  6297. TEST_F(ServerTest, GetWithRange3) {
  6298. auto res = cli_.Get("/with-range", Headers{
  6299. make_range_header({{0, 0}}),
  6300. {"Accept-Encoding", ""},
  6301. });
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6304. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6305. EXPECT_EQ(true, res->has_header("Content-Range"));
  6306. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6307. EXPECT_EQ(std::string("a"), res->body);
  6308. }
  6309. TEST_F(ServerTest, GetWithRange4) {
  6310. auto res = cli_.Get("/with-range", Headers{
  6311. make_range_header({{-1, 2}}),
  6312. {"Accept-Encoding", ""},
  6313. });
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6316. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6317. EXPECT_EQ(true, res->has_header("Content-Range"));
  6318. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6319. EXPECT_EQ(std::string("fg"), res->body);
  6320. }
  6321. TEST_F(ServerTest, GetWithRange5) {
  6322. auto res = cli_.Get("/with-range", Headers{
  6323. make_range_header({{0, 5}}),
  6324. {"Accept-Encoding", ""},
  6325. });
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6328. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6329. EXPECT_EQ(true, res->has_header("Content-Range"));
  6330. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6331. EXPECT_EQ(std::string("abcdef"), res->body);
  6332. }
  6333. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6334. auto res =
  6335. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6338. }
  6339. TEST_F(ServerTest, GetWithRangeMultipart) {
  6340. auto res =
  6341. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6344. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6345. EXPECT_EQ(false, res->has_header("Content-Range"));
  6346. EXPECT_EQ(267U, res->body.size());
  6347. }
  6348. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6349. auto res = cli_.Get("/with-range",
  6350. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6353. }
  6354. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6355. auto res = cli_.Get("/with-range-customized-response",
  6356. Headers{{make_range_header({{1, 2}})}});
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6359. EXPECT_EQ(true, res->has_header("Content-Length"));
  6360. EXPECT_EQ(false, res->has_header("Content-Range"));
  6361. EXPECT_EQ(JSON_DATA, res->body);
  6362. }
  6363. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6364. auto res = cli_.Get("/with-range-customized-response",
  6365. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6368. EXPECT_EQ(true, res->has_header("Content-Length"));
  6369. EXPECT_EQ(false, res->has_header("Content-Range"));
  6370. EXPECT_EQ(JSON_DATA, res->body);
  6371. }
  6372. TEST_F(ServerTest, Issue1772) {
  6373. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6376. }
  6377. TEST_F(ServerTest, Issue609) {
  6378. auto res = cli_.Delete("/issue609");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::OK_200, res->status);
  6381. EXPECT_EQ(std::string("ok"), res->body);
  6382. }
  6383. TEST_F(ServerTest, GetStreamedChunked) {
  6384. auto res = cli_.Get("/streamed-chunked");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. EXPECT_EQ(std::string("123456789"), res->body);
  6388. }
  6389. TEST_F(ServerTest, GetStreamedChunked2) {
  6390. auto res = cli_.Get("/streamed-chunked2");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. EXPECT_EQ(std::string("123456789"), res->body);
  6394. }
  6395. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6396. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ(StatusCode::OK_200, res->status);
  6399. EXPECT_EQ(std::string("123456789"), res->body);
  6400. EXPECT_TRUE(res->has_header("Trailer"));
  6401. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6402. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6403. // Trailers are now stored separately from headers (security fix)
  6404. EXPECT_EQ(2U, res->trailers.size());
  6405. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6406. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6407. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6408. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6409. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6410. // Verify trailers are NOT in headers (security verification)
  6411. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6412. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6413. }
  6414. TEST_F(ServerTest, LargeChunkedPost) {
  6415. Request req;
  6416. req.method = "POST";
  6417. req.path = "/large-chunked";
  6418. std::string host_and_port;
  6419. host_and_port += HOST;
  6420. host_and_port += ":";
  6421. host_and_port += std::to_string(PORT);
  6422. req.headers.emplace("Host", host_and_port.c_str());
  6423. req.headers.emplace("Accept", "*/*");
  6424. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6425. req.headers.emplace("Content-Type", "text/plain");
  6426. req.headers.emplace("Content-Length", "0");
  6427. req.headers.emplace("Transfer-Encoding", "chunked");
  6428. std::string long_string(30 * 1024u, 'a');
  6429. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6430. // Attempt to make a large enough post to exceed OS buffers, to test that
  6431. // the server handles short reads if the full chunk data isn't available.
  6432. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6433. auto res = std::make_shared<Response>();
  6434. auto error = Error::Success;
  6435. auto ret = cli_.send(req, *res, error);
  6436. ASSERT_TRUE(ret);
  6437. EXPECT_EQ(StatusCode::OK_200, res->status);
  6438. }
  6439. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6440. auto res = cli_.Get("/remote_addr");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6444. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6445. }
  6446. TEST_F(ServerTest, GetMethodLocalAddr) {
  6447. auto res = cli_.Get("/local_addr");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6451. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6452. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6453. }
  6454. TEST_F(ServerTest, HTTPResponseSplitting) {
  6455. auto res = cli_.Get("/http_response_splitting");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. }
  6459. TEST_F(ServerTest, SlowRequest) {
  6460. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6461. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6462. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6463. }
  6464. #if 0
  6465. TEST_F(ServerTest, SlowPost) {
  6466. char buffer[64 * 1024];
  6467. memset(buffer, 0x42, sizeof(buffer));
  6468. auto res = cli_.Post(
  6469. "/slowpost", 64 * 1024 * 1024,
  6470. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6471. auto ret = sink.write(buffer, sizeof(buffer));
  6472. EXPECT_TRUE(ret);
  6473. return true;
  6474. },
  6475. "text/plain");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::OK_200, res->status);
  6478. }
  6479. TEST_F(ServerTest, SlowPostFail) {
  6480. char buffer[64 * 1024];
  6481. memset(buffer, 0x42, sizeof(buffer));
  6482. cli_.set_write_timeout(std::chrono::seconds(0));
  6483. auto res = cli_.Post(
  6484. "/slowpost", 64 * 1024 * 1024,
  6485. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6486. sink.write(buffer, sizeof(buffer));
  6487. return true;
  6488. },
  6489. "text/plain");
  6490. ASSERT_TRUE(!res);
  6491. EXPECT_EQ(Error::Write, res.error());
  6492. }
  6493. #endif
  6494. TEST_F(ServerTest, Put) {
  6495. auto res = cli_.Put("/put", "PUT", "text/plain");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. EXPECT_EQ("PUT", res->body);
  6499. }
  6500. TEST_F(ServerTest, PutWithContentProvider) {
  6501. auto res = cli_.Put(
  6502. "/put", 3,
  6503. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6504. sink.os << "PUT";
  6505. return true;
  6506. },
  6507. "text/plain");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::OK_200, res->status);
  6510. EXPECT_EQ("PUT", res->body);
  6511. }
  6512. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6513. auto res = cli_.Post(
  6514. "/post", 42,
  6515. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6516. return false;
  6517. },
  6518. "text/plain");
  6519. ASSERT_TRUE(!res);
  6520. EXPECT_EQ(Error::Canceled, res.error());
  6521. }
  6522. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6523. auto res = cli_.Put(
  6524. "/put",
  6525. [](size_t /*offset*/, DataSink &sink) {
  6526. sink.os << "PUT";
  6527. sink.done();
  6528. return true;
  6529. },
  6530. "text/plain");
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. EXPECT_EQ("PUT", res->body);
  6534. }
  6535. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6536. auto res = cli_.Post(
  6537. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6538. "text/plain");
  6539. ASSERT_TRUE(!res);
  6540. EXPECT_EQ(Error::Canceled, res.error());
  6541. }
  6542. TEST_F(ServerTest, PostLoopBack) {
  6543. std::string body;
  6544. auto res = cli_.Post(
  6545. "/post-loopback", 9,
  6546. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6547. EXPECT_EQ(9u, length);
  6548. sink.write("123", 3);
  6549. sink.write("456", 3);
  6550. sink.write("789", 3);
  6551. return true;
  6552. },
  6553. "text/plain",
  6554. [&body](const char *data, size_t data_length) {
  6555. body.append(data, data_length);
  6556. return true;
  6557. });
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. EXPECT_EQ(StatusCode::OK_200, res->status);
  6560. EXPECT_EQ("123456789", body);
  6561. }
  6562. TEST_F(ServerTest, PutLoopBack) {
  6563. std::string body;
  6564. auto res = cli_.Put(
  6565. "/put-loopback", 9,
  6566. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6567. EXPECT_EQ(9u, length);
  6568. sink.write("123", 3);
  6569. sink.write("456", 3);
  6570. sink.write("789", 3);
  6571. return true;
  6572. },
  6573. "text/plain",
  6574. [&body](const char *data, size_t data_length) {
  6575. body.append(data, data_length);
  6576. return true;
  6577. });
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::OK_200, res->status);
  6580. EXPECT_EQ("123456789", body);
  6581. }
  6582. TEST_F(ServerTest, PatchLoopBack) {
  6583. std::string body;
  6584. auto res = cli_.Patch(
  6585. "/patch-loopback", 9,
  6586. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6587. EXPECT_EQ(9u, length);
  6588. sink.write("123", 3);
  6589. sink.write("456", 3);
  6590. sink.write("789", 3);
  6591. return true;
  6592. },
  6593. "text/plain",
  6594. [&body](const char *data, size_t data_length) {
  6595. body.append(data, data_length);
  6596. return true;
  6597. });
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. EXPECT_EQ("123456789", body);
  6601. }
  6602. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6603. std::string body;
  6604. auto res = cli_.Post(
  6605. "/post-loopback",
  6606. [](size_t /*offset*/, DataSink &sink) {
  6607. sink.write("123", 3);
  6608. sink.write("456", 3);
  6609. sink.write("789", 3);
  6610. sink.done();
  6611. return true;
  6612. },
  6613. "text/plain",
  6614. [&body](const char *data, size_t data_length) {
  6615. body.append(data, data_length);
  6616. return true;
  6617. });
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. EXPECT_EQ(StatusCode::OK_200, res->status);
  6620. EXPECT_EQ("123456789", body);
  6621. }
  6622. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6623. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6624. cli_.set_compress(true);
  6625. auto res = cli_.Put(
  6626. "/put", 3,
  6627. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6628. sink.os << "PUT";
  6629. return true;
  6630. },
  6631. "text/plain");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("PUT", res->body);
  6635. }
  6636. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6637. cli_.set_compress(true);
  6638. auto res = cli_.Post(
  6639. "/post", 42,
  6640. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6641. return false;
  6642. },
  6643. "text/plain");
  6644. ASSERT_TRUE(!res);
  6645. EXPECT_EQ(Error::Canceled, res.error());
  6646. }
  6647. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6648. cli_.set_compress(true);
  6649. auto res = cli_.Put(
  6650. "/put",
  6651. [](size_t /*offset*/, DataSink &sink) {
  6652. sink.os << "PUT";
  6653. sink.done();
  6654. return true;
  6655. },
  6656. "text/plain");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("PUT", res->body);
  6660. }
  6661. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6662. cli_.set_compress(true);
  6663. auto res = cli_.Post(
  6664. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6665. "text/plain");
  6666. ASSERT_TRUE(!res);
  6667. EXPECT_EQ(Error::Canceled, res.error());
  6668. }
  6669. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6670. cli_.set_compress(true);
  6671. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::OK_200, res->status);
  6674. EXPECT_EQ(LARGE_DATA, res->body);
  6675. }
  6676. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6677. #ifdef CPPHTTPLIB_SSL_ENABLED
  6678. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6679. Client cli(s.c_str());
  6680. cli.enable_server_certificate_verification(false);
  6681. #else
  6682. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6683. Client cli(s.c_str());
  6684. #endif
  6685. cli.set_compress(true);
  6686. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. EXPECT_EQ(LARGE_DATA, res->body);
  6690. // The compressed size should be less than a 10th of the original. May vary
  6691. // depending on the zlib library.
  6692. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6693. static_cast<uint64_t>(10 * 1024 * 1024));
  6694. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6695. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6696. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6697. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6698. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6699. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6700. #endif
  6701. }
  6702. TEST_F(ServerTest, PutContentWithDeflate) {
  6703. cli_.set_compress(false);
  6704. Headers headers;
  6705. headers.emplace("Content-Encoding", "deflate");
  6706. // PUT in deflate format:
  6707. auto res = cli_.Put("/put", headers,
  6708. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("PUT", res->body);
  6712. }
  6713. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6714. Headers headers;
  6715. headers.emplace("Accept-Encoding", "gzip, deflate");
  6716. auto res = cli_.Get("/streamed-chunked", headers);
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::OK_200, res->status);
  6719. EXPECT_EQ(std::string("123456789"), res->body);
  6720. }
  6721. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6722. Headers headers;
  6723. headers.emplace("Accept-Encoding", "gzip, deflate");
  6724. auto res = cli_.Get("/streamed-chunked2", headers);
  6725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. EXPECT_EQ(std::string("123456789"), res->body);
  6728. }
  6729. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6730. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. }
  6734. TEST(GzipDecompressor, ChunkedDecompression) {
  6735. std::string data;
  6736. for (size_t i = 0; i < 32 * 1024; ++i) {
  6737. data.push_back(static_cast<char>('a' + i % 26));
  6738. }
  6739. std::string compressed_data;
  6740. {
  6741. httplib::detail::gzip_compressor compressor;
  6742. bool result = compressor.compress(
  6743. data.data(), data.size(),
  6744. /*last=*/true,
  6745. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6746. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6747. compressed_data_size);
  6748. return true;
  6749. });
  6750. ASSERT_TRUE(result);
  6751. }
  6752. std::string decompressed_data;
  6753. {
  6754. httplib::detail::gzip_decompressor decompressor;
  6755. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6756. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6757. size_t chunk_size = 130;
  6758. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6759. chunk_begin += chunk_size) {
  6760. size_t current_chunk_size =
  6761. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6762. bool result = decompressor.decompress(
  6763. compressed_data.data() + chunk_begin, current_chunk_size,
  6764. [&](const char *decompressed_data_chunk,
  6765. size_t decompressed_data_chunk_size) {
  6766. decompressed_data.insert(decompressed_data.size(),
  6767. decompressed_data_chunk,
  6768. decompressed_data_chunk_size);
  6769. return true;
  6770. });
  6771. ASSERT_TRUE(result);
  6772. }
  6773. }
  6774. ASSERT_EQ(data, decompressed_data);
  6775. }
  6776. TEST(GzipDecompressor, DeflateDecompression) {
  6777. std::string original_text = "Raw deflate without gzip";
  6778. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6782. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6783. std::string decompressed_data;
  6784. {
  6785. httplib::detail::gzip_decompressor decompressor;
  6786. bool result = decompressor.decompress(
  6787. compressed_data.data(), compressed_data.size(),
  6788. [&](const char *decompressed_data_chunk,
  6789. size_t decompressed_data_chunk_size) {
  6790. decompressed_data.insert(decompressed_data.size(),
  6791. decompressed_data_chunk,
  6792. decompressed_data_chunk_size);
  6793. return true;
  6794. });
  6795. ASSERT_TRUE(result);
  6796. }
  6797. ASSERT_EQ(original_text, decompressed_data);
  6798. }
  6799. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6800. std::string original_text = "Raw deflate without gzip";
  6801. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6802. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6803. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6804. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6805. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6806. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6807. std::string decompressed_data;
  6808. {
  6809. httplib::detail::gzip_decompressor decompressor;
  6810. bool result = decompressor.decompress(
  6811. compressed_data.data(), compressed_data.size(),
  6812. [&](const char *decompressed_data_chunk,
  6813. size_t decompressed_data_chunk_size) {
  6814. decompressed_data.insert(decompressed_data.size(),
  6815. decompressed_data_chunk,
  6816. decompressed_data_chunk_size);
  6817. return true;
  6818. });
  6819. ASSERT_TRUE(result);
  6820. }
  6821. ASSERT_EQ(original_text, decompressed_data);
  6822. }
  6823. #endif
  6824. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6825. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6826. Headers headers;
  6827. headers.emplace("Accept-Encoding", "br");
  6828. auto res = cli_.Get("/streamed-chunked", headers);
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::OK_200, res->status);
  6831. EXPECT_EQ(std::string("123456789"), res->body);
  6832. }
  6833. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6834. Headers headers;
  6835. headers.emplace("Accept-Encoding", "br");
  6836. auto res = cli_.Get("/streamed-chunked2", headers);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. EXPECT_EQ(std::string("123456789"), res->body);
  6840. }
  6841. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6842. cli_.set_compress(true);
  6843. auto res = cli_.Put(
  6844. "/put", 3,
  6845. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6846. sink.os << "PUT";
  6847. return true;
  6848. },
  6849. "text/plain");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. EXPECT_EQ("PUT", res->body);
  6853. }
  6854. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6855. cli_.set_compress(true);
  6856. auto res = cli_.Put(
  6857. "/put",
  6858. [](size_t /*offset*/, DataSink &sink) {
  6859. sink.os << "PUT";
  6860. sink.done();
  6861. return true;
  6862. },
  6863. "text/plain");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("PUT", res->body);
  6867. }
  6868. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6869. cli_.set_compress(true);
  6870. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(LARGE_DATA, res->body);
  6874. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6875. }
  6876. #endif
  6877. TEST_F(ServerTest, Patch) {
  6878. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("PATCH", res->body);
  6882. }
  6883. TEST_F(ServerTest, Delete) {
  6884. auto res = cli_.Delete("/delete");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. EXPECT_EQ("DELETE", res->body);
  6888. }
  6889. TEST_F(ServerTest, DeleteContentReceiver) {
  6890. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::OK_200, res->status);
  6893. EXPECT_EQ("content", res->body);
  6894. }
  6895. TEST_F(ServerTest, Options) {
  6896. auto res = cli_.Options("*");
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. EXPECT_EQ(StatusCode::OK_200, res->status);
  6899. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6900. EXPECT_TRUE(res->body.empty());
  6901. }
  6902. TEST_F(ServerTest, URL) {
  6903. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. }
  6907. TEST_F(ServerTest, ArrayParam) {
  6908. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, ArrayParamValues) {
  6913. auto res =
  6914. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::OK_200, res->status);
  6917. }
  6918. TEST_F(ServerTest, NoMultipleHeaders) {
  6919. Headers headers = {{"Content-Length", "5"}};
  6920. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6921. "text/plain");
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. }
  6925. TEST_F(ServerTest, PostContentReceiver) {
  6926. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::OK_200, res->status);
  6929. ASSERT_EQ("content", res->body);
  6930. }
  6931. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6932. UploadFormDataItems items = {
  6933. {"text1", "text default", "", ""},
  6934. {"text2", "aωb", "", ""},
  6935. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6936. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6937. {"file3", "", "", "application/octet-stream"},
  6938. };
  6939. auto res = cli_.Post("/content_receiver", items);
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. EXPECT_EQ(StatusCode::OK_200, res->status);
  6942. }
  6943. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6944. UploadFormDataItems items = {
  6945. {"text1", "text default", "", ""},
  6946. {"text2", "aωb", "", ""},
  6947. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6948. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6949. {"file3", "", "", "application/octet-stream"},
  6950. };
  6951. auto boundary = std::string("+++++");
  6952. std::string body;
  6953. for (const auto &item : items) {
  6954. body += "--" + boundary + "\r\n";
  6955. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6956. if (!item.filename.empty()) {
  6957. body += "; filename=\"" + item.filename + "\"";
  6958. }
  6959. body += "\r\n";
  6960. if (!item.content_type.empty()) {
  6961. body += "Content-Type: " + item.content_type + "\r\n";
  6962. }
  6963. body += "\r\n";
  6964. body += item.content + "\r\n";
  6965. }
  6966. body += "--" + boundary + "--\r\n";
  6967. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6968. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::OK_200, res->status);
  6971. }
  6972. TEST(MultipartFormDataTest, FieldEscaping) {
  6973. Server svr;
  6974. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6975. const ContentReader &content_reader) {
  6976. ASSERT_TRUE(req.is_multipart_form_data());
  6977. std::vector<FormData> received;
  6978. content_reader(
  6979. [&](const FormData &file) {
  6980. received.push_back(file);
  6981. return true;
  6982. },
  6983. [&](const char *data, size_t data_length) {
  6984. received.back().content.append(data, data_length);
  6985. return true;
  6986. });
  6987. // '"', CR and LF in names and filenames are escaped following the
  6988. // WHATWG HTML standard, so each part still parses as a single part
  6989. // with no injected headers. Content types get CR/LF escaped too,
  6990. // while '"' (legal there, e.g. quoted charset) is preserved.
  6991. ASSERT_EQ(4U, received.size());
  6992. EXPECT_EQ("na%22me", received[0].name);
  6993. EXPECT_EQ("quoted name", received[0].content);
  6994. EXPECT_EQ("file", received[1].name);
  6995. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6996. received[1].filename);
  6997. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6998. EXPECT_EQ("injected", received[1].content);
  6999. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7000. EXPECT_EQ("my%22file.txt", received[2].filename);
  7001. EXPECT_EQ("cr lf name", received[2].content);
  7002. EXPECT_EQ("typed", received[3].name);
  7003. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7004. received[3].content_type);
  7005. EXPECT_EQ("typed content", received[3].content);
  7006. });
  7007. auto port = svr.bind_to_any_port("localhost");
  7008. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7009. auto se = detail::scope_exit([&] {
  7010. svr.stop();
  7011. t.join();
  7012. ASSERT_FALSE(svr.is_running());
  7013. });
  7014. svr.wait_until_ready();
  7015. Client cli("localhost", port);
  7016. UploadFormDataItems items = {
  7017. {"na\"me", "quoted name", "", ""},
  7018. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7019. "application/octet-stream"},
  7020. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7021. {"typed", "typed content", "",
  7022. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7023. };
  7024. auto res = cli.Post("/post", items);
  7025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. }
  7028. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7029. const UploadFormDataItems items = {
  7030. {"name1", "Content 1", "", ""},
  7031. {"name2", "Content 2", "file2.txt", "text/plain"},
  7032. };
  7033. Server svr;
  7034. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7035. const ContentReader &content_reader) {
  7036. ASSERT_TRUE(req.is_multipart_form_data());
  7037. std::vector<FormData> received;
  7038. content_reader(
  7039. [&](const FormData &file) {
  7040. received.push_back(file);
  7041. return true;
  7042. },
  7043. [&](const char *data, size_t data_length) {
  7044. received.back().content.append(data, data_length);
  7045. return true;
  7046. });
  7047. ASSERT_EQ(2U, received.size());
  7048. EXPECT_EQ("name1", received[0].name);
  7049. EXPECT_EQ("Content 1", received[0].content);
  7050. EXPECT_EQ("name2", received[1].name);
  7051. EXPECT_EQ("Content 2", received[1].content);
  7052. EXPECT_EQ("file2.txt", received[1].filename);
  7053. EXPECT_EQ("text/plain", received[1].content_type);
  7054. });
  7055. auto port = svr.bind_to_any_port("localhost");
  7056. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7057. auto se = detail::scope_exit([&] {
  7058. svr.stop();
  7059. t.join();
  7060. ASSERT_FALSE(svr.is_running());
  7061. });
  7062. svr.wait_until_ready();
  7063. Client cli("localhost", port);
  7064. // Whole-body serialization with a generated boundary
  7065. {
  7066. MultipartFormDataWriter writer;
  7067. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7068. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7069. writer.content_type());
  7070. auto body = writer.serialize(items);
  7071. EXPECT_EQ(body.size(), writer.content_length(items));
  7072. auto res = cli.Post("/post", body, writer.content_type());
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::OK_200, res->status);
  7075. }
  7076. // Per-part framing with a custom boundary via a content provider
  7077. {
  7078. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7079. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7080. MultipartFormDataWriter writer("custom-boundary_123");
  7081. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7082. std::string body;
  7083. for (const auto &item : items) {
  7084. body += writer.item_begin(item);
  7085. body += item.content;
  7086. body += MultipartFormDataWriter::item_end();
  7087. }
  7088. body += writer.finish();
  7089. EXPECT_EQ(body.size(), writer.content_length(items));
  7090. auto res = cli.Post(
  7091. "/post", body.size(),
  7092. [&](size_t offset, size_t length, DataSink &sink) {
  7093. sink.write(body.data() + offset, length);
  7094. return true;
  7095. },
  7096. writer.content_type());
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. }
  7100. }
  7101. TEST_F(ServerTest, PostContentReceiverGzip) {
  7102. cli_.set_compress(true);
  7103. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7105. ASSERT_EQ(StatusCode::OK_200, res->status);
  7106. ASSERT_EQ("content", res->body);
  7107. }
  7108. TEST_F(ServerTest, PutContentReceiver) {
  7109. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. ASSERT_EQ(StatusCode::OK_200, res->status);
  7112. ASSERT_EQ("content", res->body);
  7113. }
  7114. TEST_F(ServerTest, PatchContentReceiver) {
  7115. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. ASSERT_EQ(StatusCode::OK_200, res->status);
  7118. ASSERT_EQ("content", res->body);
  7119. }
  7120. template <typename ClientType>
  7121. void TestWithHeadersAndContentReceiver(
  7122. ClientType &cli,
  7123. std::function<Result(ClientType &, const std::string &, const Headers &,
  7124. const std::string &, const std::string &,
  7125. ContentReceiver, DownloadProgress)>
  7126. request_func) {
  7127. Headers headers;
  7128. headers.emplace("X-Custom-Header", "test-value");
  7129. std::string received_body;
  7130. auto res = request_func(
  7131. cli, "/content_receiver", headers, "content", "application/json",
  7132. [&](const char *data, size_t data_length) {
  7133. received_body.append(data, data_length);
  7134. return true;
  7135. },
  7136. nullptr);
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("content", received_body);
  7140. }
  7141. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7142. #ifdef CPPHTTPLIB_SSL_ENABLED
  7143. using ClientT = SSLClient;
  7144. #else
  7145. using ClientT = Client;
  7146. #endif
  7147. TestWithHeadersAndContentReceiver<ClientT>(
  7148. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7149. const std::string &body, const std::string &content_type,
  7150. ContentReceiver receiver, DownloadProgress progress) {
  7151. return cli.Post(path, headers, body, content_type, receiver, progress);
  7152. });
  7153. }
  7154. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7155. #ifdef CPPHTTPLIB_SSL_ENABLED
  7156. using ClientT = SSLClient;
  7157. #else
  7158. using ClientT = Client;
  7159. #endif
  7160. TestWithHeadersAndContentReceiver<ClientT>(
  7161. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7162. const std::string &body, const std::string &content_type,
  7163. ContentReceiver receiver, DownloadProgress progress) {
  7164. return cli.Put(path, headers, body, content_type, receiver, progress);
  7165. });
  7166. }
  7167. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7168. #ifdef CPPHTTPLIB_SSL_ENABLED
  7169. using ClientT = SSLClient;
  7170. #else
  7171. using ClientT = Client;
  7172. #endif
  7173. TestWithHeadersAndContentReceiver<ClientT>(
  7174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7175. const std::string &body, const std::string &content_type,
  7176. ContentReceiver receiver, DownloadProgress progress) {
  7177. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7178. });
  7179. }
  7180. template <typename ClientType>
  7181. void TestWithHeadersAndContentReceiverWithProgress(
  7182. ClientType &cli,
  7183. std::function<Result(ClientType &, const std::string &, const Headers &,
  7184. const std::string &, const std::string &,
  7185. ContentReceiver, DownloadProgress)>
  7186. request_func) {
  7187. Headers headers;
  7188. headers.emplace("X-Test-Header", "progress-test");
  7189. std::string received_body;
  7190. auto progress_called = false;
  7191. auto res = request_func(
  7192. cli, "/content_receiver", headers, "content", "text/plain",
  7193. [&](const char *data, size_t data_length) {
  7194. received_body.append(data, data_length);
  7195. return true;
  7196. },
  7197. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7198. progress_called = true;
  7199. return true;
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. EXPECT_EQ("content", received_body);
  7204. EXPECT_TRUE(progress_called);
  7205. }
  7206. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7207. #ifdef CPPHTTPLIB_SSL_ENABLED
  7208. using ClientT = SSLClient;
  7209. #else
  7210. using ClientT = Client;
  7211. #endif
  7212. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7213. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7214. const std::string &body, const std::string &content_type,
  7215. ContentReceiver receiver, DownloadProgress progress) {
  7216. return cli.Post(path, headers, body, content_type, receiver, progress);
  7217. });
  7218. }
  7219. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7220. #ifdef CPPHTTPLIB_SSL_ENABLED
  7221. using ClientT = SSLClient;
  7222. #else
  7223. using ClientT = Client;
  7224. #endif
  7225. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7227. const std::string &body, const std::string &content_type,
  7228. ContentReceiver receiver, DownloadProgress progress) {
  7229. return cli.Put(path, headers, body, content_type, receiver, progress);
  7230. });
  7231. }
  7232. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7233. #ifdef CPPHTTPLIB_SSL_ENABLED
  7234. using ClientT = SSLClient;
  7235. #else
  7236. using ClientT = Client;
  7237. #endif
  7238. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7240. const std::string &body, const std::string &content_type,
  7241. ContentReceiver receiver, DownloadProgress progress) {
  7242. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7243. });
  7244. }
  7245. template <typename ClientType>
  7246. void TestWithHeadersAndContentReceiverError(
  7247. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7248. const Headers &, const std::string &,
  7249. const std::string &, ContentReceiver)>
  7250. request_func) {
  7251. Headers headers;
  7252. headers.emplace("X-Error-Test", "true");
  7253. std::string received_body;
  7254. auto receiver_failed = false;
  7255. auto res =
  7256. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7257. [&](const char *data, size_t data_length) {
  7258. received_body.append(data, data_length);
  7259. receiver_failed = true;
  7260. return false;
  7261. });
  7262. ASSERT_FALSE(res);
  7263. EXPECT_TRUE(receiver_failed);
  7264. }
  7265. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7266. #ifdef CPPHTTPLIB_SSL_ENABLED
  7267. using ClientT = SSLClient;
  7268. #else
  7269. using ClientT = Client;
  7270. #endif
  7271. TestWithHeadersAndContentReceiverError<ClientT>(
  7272. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7273. const std::string &body, const std::string &content_type,
  7274. ContentReceiver receiver) {
  7275. return cli.Post(path, headers, body, content_type, receiver);
  7276. });
  7277. }
  7278. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7279. #ifdef CPPHTTPLIB_SSL_ENABLED
  7280. using ClientT = SSLClient;
  7281. #else
  7282. using ClientT = Client;
  7283. #endif
  7284. TestWithHeadersAndContentReceiverError<ClientT>(
  7285. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7286. const std::string &body, const std::string &content_type,
  7287. ContentReceiver receiver) {
  7288. return cli.Put(path, headers, body, content_type, receiver);
  7289. });
  7290. }
  7291. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7292. #ifdef CPPHTTPLIB_SSL_ENABLED
  7293. using ClientT = SSLClient;
  7294. #else
  7295. using ClientT = Client;
  7296. #endif
  7297. TestWithHeadersAndContentReceiverError<ClientT>(
  7298. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7299. const std::string &body, const std::string &content_type,
  7300. ContentReceiver receiver) {
  7301. return cli.Patch(path, headers, body, content_type, receiver);
  7302. });
  7303. }
  7304. TEST_F(ServerTest, PostQueryStringAndBody) {
  7305. auto res =
  7306. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. ASSERT_EQ(StatusCode::OK_200, res->status);
  7309. }
  7310. TEST_F(ServerTest, HTTP2Magic) {
  7311. Request req;
  7312. req.method = "PRI";
  7313. req.path = "*";
  7314. req.body = "SM";
  7315. auto res = std::make_shared<Response>();
  7316. auto error = Error::Success;
  7317. auto ret = cli_.send(req, *res, error);
  7318. ASSERT_TRUE(ret);
  7319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7320. }
  7321. TEST_F(ServerTest, KeepAlive) {
  7322. auto res = cli_.Get("/hi");
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::OK_200, res->status);
  7325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7326. EXPECT_EQ("Hello World!", res->body);
  7327. res = cli_.Get("/hi");
  7328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7329. EXPECT_EQ(StatusCode::OK_200, res->status);
  7330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7331. EXPECT_EQ("Hello World!", res->body);
  7332. res = cli_.Get("/hi");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7336. EXPECT_EQ("Hello World!", res->body);
  7337. res = cli_.Get("/not-exist");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7340. res = cli_.Post("/empty", "", "text/plain");
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7344. EXPECT_EQ("empty", res->body);
  7345. EXPECT_EQ("close", res->get_header_value("Connection"));
  7346. res = cli_.Post(
  7347. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7348. "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7352. EXPECT_EQ("empty", res->body);
  7353. cli_.set_keep_alive(false);
  7354. res = cli_.Get("/last-request");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. EXPECT_EQ("close", res->get_header_value("Connection"));
  7358. }
  7359. TEST_F(ServerTest, TooManyRedirect) {
  7360. cli_.set_follow_location(true);
  7361. auto res = cli_.Get("/redirect/0");
  7362. ASSERT_TRUE(!res);
  7363. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7364. }
  7365. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7366. Request req;
  7367. req.method = "FOOBAR";
  7368. req.path = "/hi";
  7369. cli_.set_keep_alive(true);
  7370. auto res = cli_.send(req);
  7371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7373. EXPECT_EQ("close", res->get_header_value("Connection"));
  7374. EXPECT_FALSE(cli_.is_socket_open());
  7375. }
  7376. TEST_F(ServerTest, CustomRouteReadsBody) {
  7377. const std::string xml =
  7378. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7379. Request req;
  7380. req.method = "PROPFIND";
  7381. req.path = "/dav/dir";
  7382. req.set_header("Depth", "1");
  7383. req.body = xml;
  7384. auto res = cli_.send(req);
  7385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7386. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7387. EXPECT_EQ(xml, res->body);
  7388. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7389. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7390. }
  7391. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7392. Request req;
  7393. req.method = "PROPFIND";
  7394. req.path = "/dav/42";
  7395. auto res = cli_.send(req);
  7396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7397. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7398. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7399. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7400. }
  7401. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7402. Request req;
  7403. req.method = "PROPFIND";
  7404. req.path = "/dav-re/123";
  7405. auto res = cli_.send(req);
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7408. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7409. }
  7410. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7411. Request req;
  7412. req.method = "MKCOL";
  7413. req.path = "/dav-mkcol";
  7414. auto res = cli_.send(req);
  7415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7416. EXPECT_EQ(StatusCode::Created_201, res->status);
  7417. }
  7418. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7419. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7420. Request req;
  7421. req.method = "REPORT";
  7422. req.path = "/dav-report";
  7423. req.body = xml;
  7424. auto res = cli_.send(req);
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7427. EXPECT_EQ(xml, res->body);
  7428. }
  7429. // A content reader route must fire even when the request carries no body,
  7430. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7431. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7432. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7433. Request req;
  7434. req.method = "REPORT";
  7435. req.path = "/dav-report";
  7436. auto res = cli_.send(req);
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7439. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7440. }
  7441. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7442. Request req;
  7443. req.method = "PROPFIND";
  7444. req.path = "/not-dav";
  7445. auto res = cli_.send(req);
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7448. }
  7449. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7450. Request req;
  7451. req.method = "UNLOCK";
  7452. req.path = "/dav/dir";
  7453. cli_.set_keep_alive(true);
  7454. auto res = cli_.send(req);
  7455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7456. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7457. EXPECT_EQ("close", res->get_header_value("Connection"));
  7458. EXPECT_FALSE(cli_.is_socket_open());
  7459. }
  7460. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7461. // The mount point serves this path, but only for GET and HEAD.
  7462. auto get_res = cli_.Get("/dir/index.html");
  7463. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7464. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7465. Request req;
  7466. req.method = "PROPFIND";
  7467. req.path = "/dir/index.html";
  7468. auto res = cli_.send(req);
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7471. }
  7472. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7473. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7474. cli_.set_keep_alive(true);
  7475. for (auto i = 0; i < 2; i++) {
  7476. Request req;
  7477. req.method = "PROPFIND";
  7478. req.path = "/dav/dir";
  7479. req.body = xml;
  7480. auto res = cli_.send(req);
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7483. EXPECT_EQ(xml, res->body);
  7484. EXPECT_TRUE(cli_.is_socket_open());
  7485. }
  7486. // A built-in method must still be served on the same connection.
  7487. cli_.set_keep_alive(false);
  7488. auto res = cli_.Get("/hi");
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ("close", res->get_header_value("Connection"));
  7492. }
  7493. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7494. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7495. Request req;
  7496. req.method = "PROPFIND";
  7497. req.path = "/dav/dir";
  7498. req.set_header("Expect", "100-continue");
  7499. req.body = xml;
  7500. auto res = cli_.send(req);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7503. EXPECT_EQ(xml, res->body);
  7504. }
  7505. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7506. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7507. TEST_F(ServerTest, Gzip) {
  7508. Headers headers;
  7509. headers.emplace("Accept-Encoding", "gzip, deflate");
  7510. auto res = cli_.Get("/compress", headers);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7513. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7514. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7515. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7516. "7890123456789012345678901234567890",
  7517. res->body);
  7518. EXPECT_EQ(StatusCode::OK_200, res->status);
  7519. }
  7520. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7521. Headers headers;
  7522. headers.emplace("Accept-Encoding", "gzip, deflate");
  7523. auto res = cli_.Get("/compress-with-charset", headers);
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7526. EXPECT_EQ("application/json; charset=utf-8",
  7527. res->get_header_value("Content-Type"));
  7528. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7529. "7890123456789012345678901234567890",
  7530. res->body);
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. }
  7533. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7534. Headers headers;
  7535. headers.emplace("Accept-Encoding", "");
  7536. auto res = cli_.Get("/compress", headers);
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7540. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7541. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7542. "7890123456789012345678901234567890",
  7543. res->body);
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. TEST_F(ServerTest, GzipWithContentReceiver) {
  7547. Headers headers;
  7548. headers.emplace("Accept-Encoding", "gzip, deflate");
  7549. std::string body;
  7550. auto res = cli_.Get("/compress", headers,
  7551. [&](const char *data, uint64_t data_length) {
  7552. EXPECT_EQ(100U, data_length);
  7553. body.append(data, data_length);
  7554. return true;
  7555. });
  7556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7557. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7558. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7559. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7560. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7561. "7890123456789012345678901234567890",
  7562. body);
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. }
  7565. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7566. Headers headers;
  7567. headers.emplace("Accept-Encoding", "gzip, deflate");
  7568. cli_.set_decompress(false);
  7569. auto res = cli_.Get("/compress", headers);
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7572. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7573. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7574. EXPECT_EQ(33U, res->body.size());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7578. Headers headers;
  7579. headers.emplace("Accept-Encoding", "");
  7580. std::string body;
  7581. auto res = cli_.Get("/compress", headers,
  7582. [&](const char *data, uint64_t data_length) {
  7583. EXPECT_EQ(100U, data_length);
  7584. body.append(data, data_length);
  7585. return true;
  7586. });
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7590. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7592. "7890123456789012345678901234567890",
  7593. body);
  7594. EXPECT_EQ(StatusCode::OK_200, res->status);
  7595. }
  7596. TEST_F(ServerTest, NoGzip) {
  7597. Headers headers;
  7598. headers.emplace("Accept-Encoding", "gzip, deflate");
  7599. auto res = cli_.Get("/nocompress", headers);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7602. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7603. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7604. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7605. "7890123456789012345678901234567890",
  7606. res->body);
  7607. EXPECT_EQ(StatusCode::OK_200, res->status);
  7608. }
  7609. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7610. Headers headers;
  7611. headers.emplace("Accept-Encoding", "gzip, deflate");
  7612. std::string body;
  7613. auto res = cli_.Get("/nocompress", headers,
  7614. [&](const char *data, uint64_t data_length) {
  7615. EXPECT_EQ(100U, data_length);
  7616. body.append(data, data_length);
  7617. return true;
  7618. });
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7621. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7622. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7623. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7624. "7890123456789012345678901234567890",
  7625. body);
  7626. EXPECT_EQ(StatusCode::OK_200, res->status);
  7627. }
  7628. TEST_F(ServerTest, MultipartFormDataGzip) {
  7629. UploadFormDataItems items = {
  7630. {"key1", "test", "", ""},
  7631. {"key2", "--abcdefg123", "", ""},
  7632. };
  7633. cli_.set_compress(true);
  7634. auto res = cli_.Post("/compress-multipart", items);
  7635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. #endif
  7639. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7640. // Static file compression is opt-in, so these run their own server rather than
  7641. // flipping it on for the shared ServerTest fixture, which would silently
  7642. // rewrite what every other static file test is asserting.
  7643. class StaticFileCompressionTest : public ::testing::Test {
  7644. protected:
  7645. void TearDown() override {
  7646. if (t_.joinable()) {
  7647. svr_.stop();
  7648. t_.join();
  7649. }
  7650. }
  7651. int start(const std::function<void(Server &)> &configure = nullptr) {
  7652. // Serves the same tree as a directory of build-time compressed assets
  7653. // would be served: the mount point names the coding the files are already
  7654. // stored in. Registered before "/" so it is the one that matches.
  7655. svr_.set_mount_point("/pre-encoded", "./www",
  7656. {{"Content-Encoding", "gzip"}});
  7657. svr_.set_mount_point("/", "./www");
  7658. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7659. res.set_file_content("./www/dir/index.html", "text/html");
  7660. });
  7661. svr_.Get("/pre-encoded-file-content",
  7662. [](const Request & /*req*/, Response &res) {
  7663. res.set_header("Content-Encoding", "gzip");
  7664. res.set_file_content("./www/dir/index.html", "text/html");
  7665. });
  7666. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7667. res.set_content_provider(
  7668. 6, "text/plain",
  7669. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7670. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7671. return true;
  7672. });
  7673. });
  7674. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7675. res.set_content_provider(
  7676. 1000, "text/plain",
  7677. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7678. if (offset < 100) {
  7679. std::string data(100, 'A');
  7680. sink.write(data.data(), data.size());
  7681. return true;
  7682. }
  7683. std::this_thread::sleep_for(std::chrono::seconds(2));
  7684. std::string data(900, 'B');
  7685. sink.write(data.data(), data.size());
  7686. return true;
  7687. });
  7688. });
  7689. if (configure) { configure(svr_); }
  7690. auto port = svr_.bind_to_any_port(HOST);
  7691. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7692. svr_.wait_until_ready();
  7693. return port;
  7694. }
  7695. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7696. // Every file under ./www except 1MB.txt is smaller than the default
  7697. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7698. // it out of the way.
  7699. static void enable_without_floor(Server &svr) {
  7700. svr.set_static_file_compression(true);
  7701. svr.set_static_file_compression_min_length(0);
  7702. }
  7703. Server svr_;
  7704. std::thread t_;
  7705. };
  7706. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7707. auto port = start();
  7708. Client cli(HOST, port);
  7709. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7713. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7714. EXPECT_EQ(1048576U, res->body.size());
  7715. }
  7716. TEST_F(StaticFileCompressionTest, MountPoint) {
  7717. auto port = start(enable);
  7718. Client cli(HOST, port);
  7719. cli.set_decompress(false);
  7720. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7724. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7725. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7726. // The response stays self-delimiting: a length, not a chunked body.
  7727. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7728. EXPECT_EQ(std::to_string(res->body.size()),
  7729. res->get_header_value("Content-Length"));
  7730. EXPECT_LT(res->body.size(), 1048576U);
  7731. EXPECT_FALSE(res->body.empty());
  7732. }
  7733. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7734. auto port = start(enable);
  7735. Client cli(HOST, port);
  7736. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7740. EXPECT_EQ(1048576U, res->body.size());
  7741. }
  7742. TEST_F(StaticFileCompressionTest, FileContent) {
  7743. auto port = start(enable_without_floor);
  7744. Client cli(HOST, port);
  7745. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7749. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7750. EXPECT_EQ(104U, res->body.size());
  7751. }
  7752. // A handler that serves an already-encoded file names the coding itself. The
  7753. // file-backed path decided its coding from Accept-Encoding and the content
  7754. // type alone, so it compressed the stored bytes a second time and appended a
  7755. // second Content-Encoding field line.
  7756. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7757. auto port = start(enable_without_floor);
  7758. Client cli(HOST, port);
  7759. cli.set_decompress(false);
  7760. auto res = cli.Get("/pre-encoded-file-content",
  7761. Headers{{"Accept-Encoding", "gzip"}});
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7765. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7766. // Vary belongs to a coding the server chose, and it chose none here.
  7767. EXPECT_FALSE(res->has_header("Vary"));
  7768. // The file travels exactly as it is stored on disk.
  7769. EXPECT_EQ(104U, res->body.size());
  7770. }
  7771. // The 1MB file clears the default floor, so this one runs the configuration a
  7772. // deployment would actually have.
  7773. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7774. auto port = start(enable);
  7775. Client cli(HOST, port);
  7776. cli.set_decompress(false);
  7777. auto res =
  7778. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7782. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7783. EXPECT_FALSE(res->has_header("Vary"));
  7784. EXPECT_EQ(1048576U, res->body.size());
  7785. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7786. }
  7787. TEST_F(StaticFileCompressionTest, Head) {
  7788. auto port = start(enable);
  7789. Client cli(HOST, port);
  7790. cli.set_decompress(false);
  7791. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7792. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7793. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7795. EXPECT_EQ(StatusCode::OK_200, res->status);
  7796. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7797. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7798. // HEAD still reports the size a GET would return.
  7799. EXPECT_EQ(get->get_header_value("Content-Length"),
  7800. res->get_header_value("Content-Length"));
  7801. EXPECT_TRUE(res->body.empty());
  7802. }
  7803. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7804. auto port = start(enable);
  7805. Client cli(HOST, port);
  7806. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7807. {"Accept-Encoding", "gzip"}});
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7810. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7811. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7812. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7813. EXPECT_EQ("cd", res->body);
  7814. }
  7815. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7816. auto port = start(enable);
  7817. Client cli(HOST, port);
  7818. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::OK_200, res->status);
  7821. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7822. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7823. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7824. }
  7825. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7826. auto port = start(enable);
  7827. Client cli(HOST, port);
  7828. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::OK_200, res->status);
  7831. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7832. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7833. EXPECT_TRUE(res->body.empty());
  7834. }
  7835. TEST_F(StaticFileCompressionTest, MinLength) {
  7836. auto port = start(enable);
  7837. Client cli(HOST, port);
  7838. // 104 bytes, well under the default floor. Compressing it would add the
  7839. // gzip header and trailer to a body that already fits in one packet.
  7840. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7844. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7845. }
  7846. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7847. auto port = start([](Server &svr) {
  7848. svr.set_static_file_compression(true);
  7849. svr.set_static_file_compression_min_length(1);
  7850. });
  7851. Client cli(HOST, port);
  7852. cli.set_decompress(false);
  7853. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7856. // A 9-byte file comes back larger than it went in, because gzip's header and
  7857. // trailer outweigh anything deflate can save. That is the end of the range
  7858. // the floor exists to keep out.
  7859. EXPECT_GT(res->body.size(), 9U);
  7860. }
  7861. TEST_F(StaticFileCompressionTest, MaxLength) {
  7862. auto port = start([](Server &svr) {
  7863. svr.set_static_file_compression(true);
  7864. svr.set_static_file_compression_min_length(0);
  7865. svr.set_static_file_compression_max_length(1024);
  7866. });
  7867. Client cli(HOST, port);
  7868. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7869. // defines `small` as a macro on Windows.
  7870. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7872. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7873. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7874. // Under it: compressed.
  7875. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7876. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7877. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7878. }
  7879. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7880. auto port = start(enable_without_floor);
  7881. Client cli(HOST, port);
  7882. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7883. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7884. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7885. auto identity_etag = identity->get_header_value("ETag");
  7886. ASSERT_FALSE(identity_etag.empty());
  7887. auto gzipped =
  7888. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7889. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7890. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7891. auto gzip_etag = gzipped->get_header_value("ETag");
  7892. ASSERT_FALSE(gzip_etag.empty());
  7893. // Two representations, two validators.
  7894. EXPECT_NE(identity_etag, gzip_etag);
  7895. // Each one revalidates against the request that would produce it...
  7896. auto fresh =
  7897. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7898. {"If-None-Match", gzip_etag}});
  7899. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7900. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7901. auto fresh_identity =
  7902. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7903. {"If-None-Match", identity_etag}});
  7904. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7905. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7906. // ...and not against the other representation.
  7907. auto crossed =
  7908. cli.Get("/dir/index.html",
  7909. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7910. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7911. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7912. }
  7913. // The opt-in covers responses the server reads off disk itself. A caller's own
  7914. // known-length provider keeps its Content-Length and, more importantly, keeps
  7915. // delivering incrementally: routing it through a compressor would hold every
  7916. // write back until zlib's window filled.
  7917. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7918. auto port = start(enable);
  7919. Client cli(HOST, port);
  7920. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7922. EXPECT_EQ(StatusCode::OK_200, res->status);
  7923. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7924. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7925. EXPECT_EQ("aaabbb", res->body);
  7926. }
  7927. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7928. auto port = start(enable);
  7929. Client cli(HOST, port);
  7930. cli.set_read_timeout(1, 0);
  7931. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7932. Headers{{"Accept-Encoding", "gzip"}});
  7933. ASSERT_TRUE(handle.is_valid());
  7934. // The provider writes 100 bytes and then stalls for longer than the read
  7935. // timeout. Those first bytes have to arrive anyway: run the response through
  7936. // a compressor and zlib holds them until its window fills, so the read would
  7937. // come back empty instead.
  7938. char buf[256];
  7939. auto n = handle.read(buf, sizeof(buf));
  7940. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7941. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7942. }
  7943. #endif
  7944. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7945. TEST_F(ServerTest, Brotli) {
  7946. Headers headers;
  7947. headers.emplace("Accept-Encoding", "br");
  7948. auto res = cli_.Get("/compress", headers);
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7951. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7952. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7953. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7954. "7890123456789012345678901234567890",
  7955. res->body);
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. }
  7958. #endif
  7959. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7960. TEST_F(ServerTest, Zstd) {
  7961. Headers headers;
  7962. headers.emplace("Accept-Encoding", "zstd");
  7963. auto res = cli_.Get("/compress", headers);
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7966. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7967. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7968. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7969. "7890123456789012345678901234567890",
  7970. res->body);
  7971. EXPECT_EQ(StatusCode::OK_200, res->status);
  7972. }
  7973. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7974. Headers headers;
  7975. headers.emplace("Accept-Encoding", "");
  7976. auto res = cli_.Get("/compress", headers);
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7979. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7980. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7981. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7982. "7890123456789012345678901234567890",
  7983. res->body);
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. }
  7986. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7987. Headers headers;
  7988. headers.emplace("Accept-Encoding", "zstd");
  7989. std::string body;
  7990. auto res = cli_.Get("/compress", headers,
  7991. [&](const char *data, uint64_t data_length) {
  7992. EXPECT_EQ(100U, data_length);
  7993. body.append(data, data_length);
  7994. return true;
  7995. });
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7999. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8000. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8001. "7890123456789012345678901234567890",
  8002. body);
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. }
  8005. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8006. Headers headers;
  8007. headers.emplace("Accept-Encoding", "zstd");
  8008. cli_.set_decompress(false);
  8009. auto res = cli_.Get("/compress", headers);
  8010. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8011. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8012. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8013. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8015. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8016. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8017. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. ASSERT_EQ(26U, res->body.size());
  8020. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8021. 0);
  8022. }
  8023. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8024. Headers headers;
  8025. headers.emplace("Accept-Encoding", "");
  8026. std::string body;
  8027. auto res = cli_.Get("/compress", headers,
  8028. [&](const char *data, uint64_t data_length) {
  8029. EXPECT_EQ(100U, data_length);
  8030. body.append(data, data_length);
  8031. return true;
  8032. });
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8037. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8038. "7890123456789012345678901234567890",
  8039. body);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST_F(ServerTest, NoZstd) {
  8043. Headers headers;
  8044. headers.emplace("Accept-Encoding", "zstd");
  8045. auto res = cli_.Get("/nocompress", headers);
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8048. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8049. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8050. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8051. "7890123456789012345678901234567890",
  8052. res->body);
  8053. EXPECT_EQ(StatusCode::OK_200, res->status);
  8054. }
  8055. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8056. Headers headers;
  8057. headers.emplace("Accept-Encoding", "zstd");
  8058. std::string body;
  8059. auto res = cli_.Get("/nocompress", headers,
  8060. [&](const char *data, uint64_t data_length) {
  8061. EXPECT_EQ(100U, data_length);
  8062. body.append(data, data_length);
  8063. return true;
  8064. });
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8067. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8068. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8069. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8070. "7890123456789012345678901234567890",
  8071. body);
  8072. EXPECT_EQ(StatusCode::OK_200, res->status);
  8073. }
  8074. // TODO: How to enable zstd ??
  8075. TEST_F(ServerTest, MultipartFormDataZstd) {
  8076. UploadFormDataItems items = {
  8077. {"key1", "test", "", ""},
  8078. {"key2", "--abcdefg123", "", ""},
  8079. };
  8080. Headers headers;
  8081. headers.emplace("Accept-Encoding", "zstd");
  8082. cli_.set_compress(true);
  8083. auto res = cli_.Post("/compress-multipart", headers, items);
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(StatusCode::OK_200, res->status);
  8086. }
  8087. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8088. Headers headers;
  8089. headers.emplace("Accept-Encoding", "zstd");
  8090. cli_.set_compress(true);
  8091. auto res = cli_.Put(
  8092. "/put", headers, 3,
  8093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8094. sink.os << "PUT";
  8095. return true;
  8096. },
  8097. "text/plain");
  8098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8099. EXPECT_EQ(StatusCode::OK_200, res->status);
  8100. EXPECT_EQ("PUT", res->body);
  8101. }
  8102. // Pre-compression logging tests
  8103. TEST_F(ServerTest, PreCompressionLogging) {
  8104. // Test data for compression (matches the actual /compress endpoint content)
  8105. const std::string test_content =
  8106. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8107. "3456789012345678901234567890";
  8108. // Variables to capture logging data
  8109. std::string pre_compression_body;
  8110. std::string pre_compression_content_type;
  8111. std::string pre_compression_content_encoding;
  8112. std::string post_compression_body;
  8113. std::string post_compression_content_type;
  8114. std::string post_compression_content_encoding;
  8115. // Set up pre-compression logger
  8116. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8117. const Response &res) {
  8118. pre_compression_body = res.body;
  8119. pre_compression_content_type = res.get_header_value("Content-Type");
  8120. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8121. });
  8122. // Set up post-compression logger
  8123. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8124. post_compression_body = res.body;
  8125. post_compression_content_type = res.get_header_value("Content-Type");
  8126. post_compression_content_encoding =
  8127. res.get_header_value("Content-Encoding");
  8128. });
  8129. // Test with gzip compression
  8130. Headers headers;
  8131. headers.emplace("Accept-Encoding", "gzip");
  8132. auto res = cli_.Get("/compress", headers);
  8133. // Verify response was compressed
  8134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8137. // Verify pre-compression logger captured uncompressed content
  8138. EXPECT_EQ(test_content, pre_compression_body);
  8139. EXPECT_EQ("text/plain", pre_compression_content_type);
  8140. EXPECT_TRUE(pre_compression_content_encoding
  8141. .empty()); // No encoding header before compression
  8142. // Verify post-compression logger captured compressed content
  8143. EXPECT_NE(test_content,
  8144. post_compression_body); // Should be different after compression
  8145. EXPECT_EQ("text/plain", post_compression_content_type);
  8146. EXPECT_EQ("gzip", post_compression_content_encoding);
  8147. // Verify compressed content is smaller
  8148. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8149. }
  8150. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8151. const std::string test_content =
  8152. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8153. "3456789012345678901234567890";
  8154. std::string pre_compression_body;
  8155. std::string post_compression_body;
  8156. svr_.set_pre_compression_logger(
  8157. [&](const Request & /*req*/, const Response &res) {
  8158. pre_compression_body = res.body;
  8159. });
  8160. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8161. post_compression_body = res.body;
  8162. });
  8163. Headers headers;
  8164. headers.emplace("Accept-Encoding", "br");
  8165. auto res = cli_.Get("/compress", headers);
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8169. // Verify pre-compression content is uncompressed
  8170. EXPECT_EQ(test_content, pre_compression_body);
  8171. // Verify post-compression content is compressed
  8172. EXPECT_NE(test_content, post_compression_body);
  8173. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8174. }
  8175. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8176. const std::string test_content =
  8177. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8178. "3456789012345678901234567890";
  8179. std::string pre_compression_body;
  8180. std::string post_compression_body;
  8181. svr_.set_pre_compression_logger(
  8182. [&](const Request & /*req*/, const Response &res) {
  8183. pre_compression_body = res.body;
  8184. });
  8185. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8186. post_compression_body = res.body;
  8187. });
  8188. // Request without compression (use /nocompress endpoint)
  8189. Headers headers;
  8190. auto res = cli_.Get("/nocompress", headers);
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8194. // Pre-compression logger should not be called when no compression is applied
  8195. EXPECT_TRUE(
  8196. pre_compression_body.empty()); // Pre-compression logger not called
  8197. EXPECT_EQ(
  8198. test_content,
  8199. post_compression_body); // Post-compression logger captures final content
  8200. }
  8201. TEST_F(ServerTest, LoggerSeesContentLength) {
  8202. size_t logged_content_length = 0;
  8203. std::string logged_content_length_header;
  8204. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8205. logged_content_length = res.content_length_;
  8206. logged_content_length_header = res.get_header_value("Content-Length");
  8207. });
  8208. auto res = cli_.Get("/nocompress");
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. EXPECT_EQ(res->body.size(), logged_content_length);
  8212. EXPECT_EQ(std::to_string(logged_content_length),
  8213. logged_content_length_header);
  8214. }
  8215. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8216. const std::string test_content =
  8217. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8218. "3456789012345678901234567890";
  8219. std::string pre_compression_body;
  8220. bool pre_logger_called = false;
  8221. // Set only pre-compression logger
  8222. svr_.set_pre_compression_logger(
  8223. [&](const Request & /*req*/, const Response &res) {
  8224. pre_compression_body = res.body;
  8225. pre_logger_called = true;
  8226. });
  8227. Headers headers;
  8228. headers.emplace("Accept-Encoding", "gzip");
  8229. auto res = cli_.Get("/compress", headers);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::OK_200, res->status);
  8232. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8233. // Verify pre-compression logger was called
  8234. EXPECT_TRUE(pre_logger_called);
  8235. EXPECT_EQ(test_content, pre_compression_body);
  8236. }
  8237. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8238. {
  8239. // Test with Expect: 100-continue header - success case
  8240. // Server returns 100 Continue, client sends body, server returns 200 OK
  8241. Request req;
  8242. req.method = "POST";
  8243. req.path = "/post-large";
  8244. req.set_header("Expect", "100-continue");
  8245. req.body = LARGE_DATA;
  8246. Response res;
  8247. auto error = Error::Success;
  8248. cli_.set_keep_alive(true);
  8249. auto ret = cli_.send(req, res, error);
  8250. EXPECT_TRUE(ret);
  8251. EXPECT_EQ(StatusCode::OK_200, res.status);
  8252. EXPECT_EQ(LARGE_DATA, res.body);
  8253. }
  8254. {
  8255. // Test with Expect: 100-continue header - error case
  8256. // Client should not send the body when server returns an error
  8257. Request req;
  8258. req.method = "POST";
  8259. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8260. req.set_header("Expect", "100-continue");
  8261. req.body = LARGE_DATA;
  8262. Response res;
  8263. auto error = Error::Success;
  8264. auto start = std::chrono::high_resolution_clock::now();
  8265. cli_.set_keep_alive(true);
  8266. auto ret = cli_.send(req, res, error);
  8267. auto end = std::chrono::high_resolution_clock::now();
  8268. auto elapsed =
  8269. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8270. .count();
  8271. // With Expect: 100-continue, request completes successfully but with error
  8272. EXPECT_TRUE(ret);
  8273. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8274. EXPECT_EQ("close", res.get_header_value("Connection"));
  8275. EXPECT_FALSE(cli_.is_socket_open());
  8276. EXPECT_LE(elapsed, 2000);
  8277. }
  8278. {
  8279. // Send an extra GET request to ensure error recovery without hanging
  8280. Request req;
  8281. req.method = "GET";
  8282. req.path = "/hi";
  8283. auto start = std::chrono::high_resolution_clock::now();
  8284. auto res = cli_.send(req);
  8285. auto end = std::chrono::high_resolution_clock::now();
  8286. auto elapsed =
  8287. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8288. .count();
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::OK_200, res->status);
  8291. EXPECT_EQ("Hello World!", res->body);
  8292. EXPECT_LE(elapsed, 500);
  8293. }
  8294. }
  8295. TEST(ZstdDecompressor, ChunkedDecompression) {
  8296. std::string data;
  8297. for (size_t i = 0; i < 32 * 1024; ++i) {
  8298. data.push_back(static_cast<char>('a' + i % 26));
  8299. }
  8300. std::string compressed_data;
  8301. {
  8302. httplib::detail::zstd_compressor compressor;
  8303. bool result = compressor.compress(
  8304. data.data(), data.size(),
  8305. /*last=*/true,
  8306. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8307. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8308. compressed_data_size);
  8309. return true;
  8310. });
  8311. ASSERT_TRUE(result);
  8312. }
  8313. std::string decompressed_data;
  8314. {
  8315. httplib::detail::zstd_decompressor decompressor;
  8316. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8317. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8318. size_t chunk_size = 130;
  8319. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8320. chunk_begin += chunk_size) {
  8321. size_t current_chunk_size =
  8322. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8323. bool result = decompressor.decompress(
  8324. compressed_data.data() + chunk_begin, current_chunk_size,
  8325. [&](const char *decompressed_data_chunk,
  8326. size_t decompressed_data_chunk_size) {
  8327. decompressed_data.insert(decompressed_data.size(),
  8328. decompressed_data_chunk,
  8329. decompressed_data_chunk_size);
  8330. return true;
  8331. });
  8332. ASSERT_TRUE(result);
  8333. }
  8334. }
  8335. ASSERT_EQ(data, decompressed_data);
  8336. }
  8337. TEST(ZstdDecompressor, Decompress) {
  8338. std::string original_text = "Compressed with ZSTD";
  8339. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8340. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8341. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8342. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8343. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8344. std::string decompressed_data;
  8345. {
  8346. httplib::detail::zstd_decompressor decompressor;
  8347. bool result = decompressor.decompress(
  8348. compressed_data.data(), compressed_data.size(),
  8349. [&](const char *decompressed_data_chunk,
  8350. size_t decompressed_data_chunk_size) {
  8351. decompressed_data.insert(decompressed_data.size(),
  8352. decompressed_data_chunk,
  8353. decompressed_data_chunk_size);
  8354. return true;
  8355. });
  8356. ASSERT_TRUE(result);
  8357. }
  8358. ASSERT_EQ(original_text, decompressed_data);
  8359. }
  8360. #endif
  8361. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8362. // separate chunks so that the server sees each part in its own read(). Used to
  8363. // place a read boundary at a specific offset of a request body.
  8364. static bool send_request_in_parts(time_t read_timeout_sec,
  8365. const std::vector<std::string> &parts,
  8366. std::string *resp = nullptr,
  8367. int port = PORT) {
  8368. auto error = Error::Success;
  8369. auto client_sock = detail::create_client_socket(
  8370. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8371. /*connection_timeout_sec=*/5, 0,
  8372. /*read_timeout_sec=*/5, 0,
  8373. /*write_timeout_sec=*/5, 0, std::string(), error);
  8374. if (client_sock == INVALID_SOCKET) { return false; }
  8375. auto ret = detail::process_client_socket(
  8376. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8377. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8378. for (size_t i = 0; i < parts.size(); i++) {
  8379. const auto &part = parts[i];
  8380. if (part.size() !=
  8381. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8382. return false;
  8383. }
  8384. if (i + 1 < parts.size()) {
  8385. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8386. }
  8387. }
  8388. char buf[512];
  8389. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8390. while (line_reader.getline()) {
  8391. if (resp) { *resp += line_reader.ptr(); }
  8392. }
  8393. return true;
  8394. });
  8395. detail::close_socket(client_sock);
  8396. return ret;
  8397. }
  8398. // Sends a raw request to a server listening at HOST:PORT.
  8399. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8400. std::string *resp = nullptr, int port = PORT) {
  8401. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8402. }
  8403. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8404. Server svr;
  8405. std::string header_value;
  8406. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8407. header_value = req.get_header_value("foo");
  8408. res.set_content("ok", "text/plain");
  8409. });
  8410. thread t = thread([&] { svr.listen(HOST, PORT); });
  8411. auto se = detail::scope_exit([&] {
  8412. svr.stop();
  8413. t.join();
  8414. ASSERT_FALSE(svr.is_running());
  8415. });
  8416. svr.wait_until_ready();
  8417. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8418. // like characters are not treated the same - use vertical tab and escape.
  8419. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8420. "foo: \t \v bar \x1B\t \r\n"
  8421. "Connection: close\r\n"
  8422. "\r\n";
  8423. std::string res;
  8424. ASSERT_TRUE(send_request(5, req, &res));
  8425. EXPECT_EQ(header_value, "");
  8426. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8427. }
  8428. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8429. Server svr;
  8430. std::string received;
  8431. svr.Get("/order", [&](const Request &req, Response &res) {
  8432. received = entries_to_string(req.headers);
  8433. res.set_content("ok", "text/plain");
  8434. });
  8435. auto port = svr.bind_to_any_port(HOST);
  8436. thread t = thread([&] { svr.listen_after_bind(); });
  8437. auto se = detail::scope_exit([&] {
  8438. svr.stop();
  8439. t.join();
  8440. ASSERT_FALSE(svr.is_running());
  8441. });
  8442. svr.wait_until_ready();
  8443. const std::string req = "GET /order HTTP/1.1\r\n"
  8444. "X-First: 1\r\n"
  8445. "X-Dup: a\r\n"
  8446. "X-Second: 2\r\n"
  8447. "X-Dup: b\r\n"
  8448. "Connection: close\r\n"
  8449. "\r\n";
  8450. std::string res;
  8451. ASSERT_TRUE(send_request(5, req, &res, port));
  8452. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8453. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8454. }
  8455. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8456. Server svr;
  8457. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8458. res.set_header("Set-Cookie", "first=1");
  8459. res.set_header("X-Between", "y");
  8460. res.set_header("Set-Cookie", "second=2");
  8461. res.set_content("ok", "text/plain");
  8462. });
  8463. auto port = svr.bind_to_any_port(HOST);
  8464. thread t = thread([&] { svr.listen_after_bind(); });
  8465. auto se = detail::scope_exit([&] {
  8466. svr.stop();
  8467. t.join();
  8468. ASSERT_FALSE(svr.is_running());
  8469. });
  8470. svr.wait_until_ready();
  8471. Client cli(HOST, port);
  8472. auto res = cli.Get("/cookies");
  8473. ASSERT_TRUE(res);
  8474. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8475. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8476. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8477. }
  8478. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8479. Server svr;
  8480. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8481. auto i = new int(0);
  8482. res.set_header("Trailer", "X-Safe, X-Reflected");
  8483. res.set_chunked_content_provider(
  8484. "text/plain",
  8485. [i](size_t /*offset*/, DataSink &sink) {
  8486. if (*i == 0) {
  8487. sink.os << "body";
  8488. } else {
  8489. Headers trailer;
  8490. // A valid trailer that must survive.
  8491. trailer.emplace("X-Safe", "safe");
  8492. // Attacker-controlled value carrying CR/LF (response splitting).
  8493. trailer.emplace("X-Reflected",
  8494. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8495. // Attacker-controlled name carrying CR/LF.
  8496. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8497. sink.done_with_trailer(trailer);
  8498. }
  8499. (*i)++;
  8500. return true;
  8501. },
  8502. [i](bool /*success*/) { delete i; });
  8503. });
  8504. thread t = thread([&] { svr.listen(HOST, PORT); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. t.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. });
  8510. svr.wait_until_ready();
  8511. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8512. "Host: " + HOST +
  8513. "\r\n"
  8514. "Connection: close\r\n"
  8515. "\r\n";
  8516. std::string res;
  8517. ASSERT_TRUE(send_request(5, req, &res));
  8518. // The injected fields must not appear anywhere in the raw response.
  8519. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8520. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8521. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8522. // Invalid trailers are dropped entirely, matching set_header().
  8523. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8524. // The valid trailer still passes through.
  8525. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8526. }
  8527. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8528. Server svr;
  8529. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8530. // res.headers is a public field an application can populate directly,
  8531. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8532. // A valid header that must survive.
  8533. res.headers.emplace("X-Safe", "safe");
  8534. // Attacker-controlled value carrying CR/LF (response splitting).
  8535. res.headers.emplace("X-Reflected",
  8536. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8537. // Attacker-controlled name carrying CR/LF.
  8538. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8539. res.set_content("body", "text/plain");
  8540. });
  8541. thread t = thread([&] { svr.listen(HOST, PORT); });
  8542. auto se = detail::scope_exit([&] {
  8543. svr.stop();
  8544. t.join();
  8545. ASSERT_FALSE(svr.is_running());
  8546. });
  8547. svr.wait_until_ready();
  8548. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8549. "Host: " + HOST +
  8550. "\r\n"
  8551. "Connection: close\r\n"
  8552. "\r\n";
  8553. std::string res;
  8554. ASSERT_TRUE(send_request(5, req, &res));
  8555. // The injected fields must not appear anywhere in the raw response.
  8556. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8557. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8558. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8559. // Invalid headers are dropped entirely, matching set_header().
  8560. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8561. // The valid header still passes through.
  8562. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8563. }
  8564. // Forward declaration: in split builds split.py strips `inline` and moves the
  8565. // definition into httplib.cc, so detail::write_request_line is not visible from
  8566. // the public httplib.h. Re-declaring it here lets the tests link against the
  8567. // symbol in both header-only and split builds.
  8568. namespace httplib {
  8569. namespace detail {
  8570. ssize_t write_request_line(Stream &strm, const std::string &method,
  8571. const std::string &path);
  8572. } // namespace detail
  8573. } // namespace httplib
  8574. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8575. // A well-formed target is written verbatim.
  8576. {
  8577. detail::BufferStream strm;
  8578. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8579. EXPECT_GT(n, 0);
  8580. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8581. }
  8582. // A target carrying CR/LF, SP or other control octets must be rejected
  8583. // before anything reaches the wire, otherwise it splits the request line and
  8584. // injects a header or a whole request. This is what a decoded redirect
  8585. // Location ("%0D%0A") turns into when path encoding is disabled.
  8586. const std::string evil_targets[] = {
  8587. "/a\r\nInjected: pwned",
  8588. "/a\rInjected",
  8589. "/a\nInjected",
  8590. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8591. "/a b",
  8592. "/a\tb",
  8593. "/a\x7f",
  8594. };
  8595. for (const auto &evil : evil_targets) {
  8596. detail::BufferStream strm;
  8597. auto n = detail::write_request_line(strm, "GET", evil);
  8598. EXPECT_LT(n, 0);
  8599. EXPECT_TRUE(strm.get_buffer().empty());
  8600. }
  8601. }
  8602. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8603. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8604. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8605. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8606. // write_request. The client must fail cleanly with Error::Write instead of
  8607. // putting a request-line-less, header-injecting request on the wire.
  8608. Server svr;
  8609. svr.Get("/a", [](const Request &, Response &res) {
  8610. res.set_content("ok", "text/plain");
  8611. });
  8612. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8613. auto se = detail::scope_exit([&] {
  8614. svr.stop();
  8615. thread.join();
  8616. ASSERT_FALSE(svr.is_running());
  8617. });
  8618. svr.wait_until_ready();
  8619. {
  8620. Client cli(HOST, PORT);
  8621. cli.set_path_encode(false);
  8622. // The request is rejected before anything is written, so the connection
  8623. // stays silent and the subsequent response read would otherwise block for
  8624. // the full default read timeout. Shorten it -- the assertion is on the
  8625. // error, not the timeout.
  8626. cli.set_read_timeout(1, 0);
  8627. auto res = cli.Get("/a\r\nInjected: pwned");
  8628. EXPECT_FALSE(res);
  8629. EXPECT_EQ(Error::Write, res.error());
  8630. }
  8631. }
  8632. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8633. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8634. // including extension methods.
  8635. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8636. for (const auto &method : good_methods) {
  8637. detail::BufferStream strm;
  8638. auto n = detail::write_request_line(strm, method, "/");
  8639. EXPECT_GT(n, 0);
  8640. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8641. }
  8642. // A method carrying CR/LF would split the request line and smuggle a whole
  8643. // request ahead of the real one. A space or an empty method corrupts the
  8644. // request line. All must be rejected before anything reaches the wire.
  8645. const std::string evil_methods[] = {
  8646. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8647. "GET\r\nInjected: pwned",
  8648. "GET\r",
  8649. "GET\n",
  8650. "GE T",
  8651. "",
  8652. };
  8653. for (const auto &evil : evil_methods) {
  8654. detail::BufferStream strm;
  8655. auto n = detail::write_request_line(strm, evil, "/");
  8656. EXPECT_LT(n, 0);
  8657. EXPECT_TRUE(strm.get_buffer().empty());
  8658. }
  8659. }
  8660. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8661. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8662. // through Client::send must fail with Error::Write and no request, neither
  8663. // the smuggled one nor the real one, may reach the server.
  8664. Server svr;
  8665. std::atomic<int> request_count(0);
  8666. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8667. request_count++;
  8668. res.status = StatusCode::OK_200;
  8669. return Server::HandlerResponse::Handled;
  8670. });
  8671. auto port = svr.bind_to_any_port(HOST);
  8672. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8673. auto se = detail::scope_exit([&] {
  8674. svr.stop();
  8675. thread.join();
  8676. ASSERT_FALSE(svr.is_running());
  8677. });
  8678. svr.wait_until_ready();
  8679. {
  8680. Client cli(HOST, port);
  8681. const std::string evil_methods[] = {
  8682. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8683. "GE T",
  8684. "",
  8685. };
  8686. for (const auto &evil : evil_methods) {
  8687. Request req;
  8688. req.method = evil;
  8689. req.path = "/";
  8690. auto res = cli.send(req);
  8691. EXPECT_FALSE(res);
  8692. EXPECT_EQ(Error::Write, res.error());
  8693. }
  8694. auto handle =
  8695. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8696. EXPECT_FALSE(handle.is_valid());
  8697. EXPECT_EQ(Error::Write, handle.error);
  8698. // A valid request on the same client still goes through.
  8699. auto res = cli.Get("/");
  8700. ASSERT_TRUE(res);
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. EXPECT_EQ(1, request_count.load());
  8704. }
  8705. // Sends a raw request and verifies that there isn't a crash or exception.
  8706. static void test_raw_request(const std::string &req,
  8707. std::string *out = nullptr) {
  8708. Server svr;
  8709. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8710. res.set_content("ok", "text/plain");
  8711. });
  8712. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8713. res.set_content("ok", "text/plain");
  8714. });
  8715. svr.Get("/header_field_value_check",
  8716. [&](const Request & /*req*/, Response &res) {
  8717. res.set_content("ok", "text/plain");
  8718. });
  8719. svr.CustomRoute("PROPFIND", "/dav",
  8720. [&](const Request & /*req*/, Response &res) {
  8721. res.status = StatusCode::MultiStatus_207;
  8722. });
  8723. // Server read timeout must be longer than the client read timeout for the
  8724. // bug to reproduce, probably to force the server to process a request
  8725. // without a trailing blank line.
  8726. const time_t client_read_timeout_sec = 1;
  8727. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8728. bool listen_thread_ok = false;
  8729. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8730. auto se = detail::scope_exit([&] {
  8731. svr.stop();
  8732. t.join();
  8733. ASSERT_FALSE(svr.is_running());
  8734. EXPECT_TRUE(listen_thread_ok);
  8735. });
  8736. svr.wait_until_ready();
  8737. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8738. }
  8739. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8740. // A certain header line causes an exception if the header property is parsed
  8741. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8742. test_raw_request(
  8743. "GET /hi HTTP/1.1\r\n"
  8744. " : "
  8745. " "
  8746. " ");
  8747. }
  8748. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8749. // A certain header line causes an exception if the header property *name* is
  8750. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8751. // greedy matcher and requires backtracking when there are a lot of ":"
  8752. // characters.
  8753. // This occurs with libc++ but not libstdc++.
  8754. test_raw_request(
  8755. "GET /hi HTTP/1.1\r\n"
  8756. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8757. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8758. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8759. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8760. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8761. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8762. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8763. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8764. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8765. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8766. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8767. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8768. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8769. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8770. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8771. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8772. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8773. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8774. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8775. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8776. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8777. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8778. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8779. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8780. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8781. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8782. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8783. "&&&%%%");
  8784. }
  8785. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8786. // Make sure this doesn't crash the server.
  8787. // In a previous version of the header line regex, the "\r" rendered the line
  8788. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8789. // a new position where the leading white space ended and the field value
  8790. // began.
  8791. // The crash occurs with libc++ but not libstdc++.
  8792. test_raw_request("GET /hi HTTP/1.1\r\n"
  8793. "a:" +
  8794. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8795. "\r\n"
  8796. "\r\n");
  8797. }
  8798. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8799. std::string out;
  8800. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8801. "Content-Type: text/plain\r\n"
  8802. "Transfer-Encoding: chunked\r\n"
  8803. "\r\n"
  8804. "nothex\r\n",
  8805. &out);
  8806. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8807. }
  8808. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8809. std::string out;
  8810. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8811. "Content-Type: text/plain\r\n"
  8812. "Transfer-Encoding: chunked\r\n"
  8813. "\r\n"
  8814. "3\r\n"
  8815. "xyz\r\n"
  8816. "NaN\r\n",
  8817. &out);
  8818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8819. }
  8820. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8821. std::string out;
  8822. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8823. "Content-Type: text/plain\r\n"
  8824. "Transfer-Encoding: chunked\r\n"
  8825. "\r\n"
  8826. // Length is too large for 64 bits.
  8827. "1ffffffffffffffff\r\n"
  8828. "xyz\r\n",
  8829. &out);
  8830. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8831. }
  8832. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8833. test_raw_request("GET /hi HTTP/1.1\r\n"
  8834. "Content-Type: text/plain\r\n\r");
  8835. }
  8836. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8837. std::string out;
  8838. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8839. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8840. }
  8841. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8842. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8843. std::string out;
  8844. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8845. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8846. }
  8847. }
  8848. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8849. std::string out;
  8850. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8851. "Connection: close\r\n\r\n",
  8852. &out);
  8853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8854. }
  8855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8856. Server svr;
  8857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8858. EXPECT_TRUE(!req.remote_addr.empty());
  8859. });
  8860. thread t = thread([&] { svr.listen(HOST, PORT); });
  8861. auto se = detail::scope_exit([&] {
  8862. svr.stop();
  8863. t.join();
  8864. ASSERT_FALSE(svr.is_running());
  8865. });
  8866. svr.wait_until_ready();
  8867. // Send an invalid request line to trigger Bad Request
  8868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8869. std::string out;
  8870. ASSERT_TRUE(send_request(5, bad_req, &out));
  8871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8872. }
  8873. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8874. // answered right away rather than blocking on a read that waits for EOF.
  8875. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8876. std::string out;
  8877. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8878. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8879. }
  8880. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8881. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8882. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8883. for (const auto *method : methods) {
  8884. Server svr;
  8885. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8886. EXPECT_FALSE(svr.is_valid()) << method;
  8887. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8888. }
  8889. }
  8890. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8891. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8892. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8893. for (const auto *method : methods) {
  8894. Server svr;
  8895. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8896. EXPECT_FALSE(svr.is_valid()) << method;
  8897. }
  8898. }
  8899. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8900. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8901. "COPY", "MOVE", "LOCK",
  8902. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8903. Server svr;
  8904. for (const auto *method : methods) {
  8905. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8906. }
  8907. EXPECT_TRUE(svr.is_valid());
  8908. }
  8909. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8910. Server svr;
  8911. svr.CustomRoute("POST", "/x",
  8912. [](const Request &, Response &, const ContentReader &) {});
  8913. EXPECT_FALSE(svr.is_valid());
  8914. }
  8915. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8916. Server svr;
  8917. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8918. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8919. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8920. EXPECT_FALSE(svr.is_valid());
  8921. }
  8922. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8923. Server svr;
  8924. auto captured = Error::Success;
  8925. svr.set_error_logger(
  8926. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8927. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8928. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8929. }
  8930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8931. std::string out;
  8932. std::string request(
  8933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8934. test_raw_request(request, &out);
  8935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8936. }
  8937. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8938. std::string out;
  8939. std::string request(
  8940. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8941. test_raw_request(request, &out);
  8942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8943. }
  8944. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8945. std::string out;
  8946. std::string request(
  8947. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8948. test_raw_request(request, &out);
  8949. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8950. }
  8951. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8952. std::string out;
  8953. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8954. "Test: \r\n\r\n",
  8955. &out);
  8956. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8957. }
  8958. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8959. Server svr;
  8960. std::string x_custom;
  8961. std::string cookie;
  8962. std::string xff;
  8963. std::string x_unicode;
  8964. std::string x_iis;
  8965. svr.Get("/check", [&](const Request &req, Response &res) {
  8966. x_custom = req.get_header_value("X-Custom");
  8967. cookie = req.get_header_value("Cookie");
  8968. xff = req.get_header_value("X-Forwarded-For");
  8969. x_unicode = req.get_header_value("X-Unicode");
  8970. x_iis = req.get_header_value("X-IIS");
  8971. res.set_content("ok", "text/plain");
  8972. });
  8973. thread t = thread([&] { svr.listen(HOST, PORT); });
  8974. auto se = detail::scope_exit([&] {
  8975. svr.stop();
  8976. t.join();
  8977. ASSERT_FALSE(svr.is_running());
  8978. });
  8979. svr.wait_until_ready();
  8980. const std::string req = "GET /check HTTP/1.1\r\n"
  8981. "Host: localhost\r\n"
  8982. "X-Custom: a%0D%0AInjected: b\r\n"
  8983. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8984. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8985. "X-Unicode: %E3%81%82\r\n"
  8986. "X-IIS: %u00E9\r\n"
  8987. "Connection: close\r\n"
  8988. "\r\n";
  8989. std::string res;
  8990. ASSERT_TRUE(send_request(5, req, &res));
  8991. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8992. // Every value must be returned verbatim (wire form), with no decoding.
  8993. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8994. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8995. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8996. EXPECT_EQ("%E3%81%82", x_unicode);
  8997. EXPECT_EQ("%u00E9", x_iis);
  8998. }
  8999. // Applications that previously relied on automatic percent-decoding can
  9000. // reproduce the old behavior by explicitly calling decode_path_component()
  9001. // or, for RFC 3986 conformance, decode_uri_component().
  9002. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9003. Server svr;
  9004. std::string decoded;
  9005. svr.Get("/check", [&](const Request &req, Response &res) {
  9006. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9007. res.set_content("ok", "text/plain");
  9008. });
  9009. thread t = thread([&] { svr.listen(HOST, PORT); });
  9010. auto se = detail::scope_exit([&] {
  9011. svr.stop();
  9012. t.join();
  9013. ASSERT_FALSE(svr.is_running());
  9014. });
  9015. svr.wait_until_ready();
  9016. const std::string req = "GET /check HTTP/1.1\r\n"
  9017. "Host: localhost\r\n"
  9018. "X-Custom: hello%20world\r\n"
  9019. "Connection: close\r\n"
  9020. "\r\n";
  9021. std::string res;
  9022. ASSERT_TRUE(send_request(5, req, &res));
  9023. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9024. EXPECT_EQ("hello world", decoded);
  9025. }
  9026. // Regression test for #2033. Browsers send Referer values that include
  9027. // percent-encoded characters such as %0A inside the URL. Decoding the
  9028. // header value would either trip the post-decode CR/LF/NUL guard (the
  9029. // original bug, returning 400) or, after that guard was relaxed, silently
  9030. // store a literal LF — both unacceptable. The wire form must round-trip.
  9031. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9032. Server svr;
  9033. std::string referer;
  9034. svr.Get("/check", [&](const Request &req, Response &res) {
  9035. referer = req.get_header_value("Referer");
  9036. res.set_content("ok", "text/plain");
  9037. });
  9038. thread t = thread([&] { svr.listen(HOST, PORT); });
  9039. auto se = detail::scope_exit([&] {
  9040. svr.stop();
  9041. t.join();
  9042. ASSERT_FALSE(svr.is_running());
  9043. });
  9044. svr.wait_until_ready();
  9045. const std::string req = "GET /check HTTP/1.1\r\n"
  9046. "Host: localhost\r\n"
  9047. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9048. "Connection: close\r\n"
  9049. "\r\n";
  9050. std::string res;
  9051. ASSERT_TRUE(send_request(5, req, &res));
  9052. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9053. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9054. }
  9055. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9056. Server svr;
  9057. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9058. res.set_header("Cache-Control", "no-cache");
  9059. res.set_chunked_content_provider(
  9060. "text/event-stream", [](size_t offset, DataSink &sink) {
  9061. std::string s = "data:";
  9062. s += std::to_string(offset);
  9063. s += "\n\n";
  9064. auto ret = sink.write(s.data(), s.size());
  9065. EXPECT_TRUE(ret);
  9066. std::this_thread::sleep_for(std::chrono::seconds(1));
  9067. return true;
  9068. });
  9069. });
  9070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9071. svr.wait_until_ready();
  9072. Client client(HOST, PORT);
  9073. const Headers headers = {{"Accept", "text/event-stream"}};
  9074. auto get_thread = std::thread([&client, &headers]() {
  9075. auto res = client.Get(
  9076. "/events", headers,
  9077. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9078. });
  9079. auto se = detail::scope_exit([&] {
  9080. svr.stop();
  9081. get_thread.join();
  9082. listen_thread.join();
  9083. ASSERT_FALSE(svr.is_running());
  9084. });
  9085. // Give GET time to get a few messages.
  9086. std::this_thread::sleep_for(std::chrono::seconds(2));
  9087. }
  9088. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9089. httplib::Server svr;
  9090. svr.Post("/hi",
  9091. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9092. res.status = StatusCode::OK_200;
  9093. });
  9094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9095. svr.wait_until_ready();
  9096. Client cli(HOST, PORT);
  9097. auto res = cli.Post("/hi", "data", "text/plain");
  9098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. svr.stop();
  9101. thread.join();
  9102. ASSERT_FALSE(svr.is_running());
  9103. res = cli.Post("/hi", "data", "text/plain");
  9104. ASSERT_FALSE(res);
  9105. }
  9106. TEST(ServerStopTest, ListenFailure) {
  9107. Server svr;
  9108. auto t = thread([&]() {
  9109. auto ret = svr.listen("????", PORT);
  9110. EXPECT_FALSE(ret);
  9111. });
  9112. svr.wait_until_ready();
  9113. svr.stop();
  9114. t.join();
  9115. }
  9116. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9117. TEST(ServerStopTest, Decommision) {
  9118. Server svr;
  9119. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9120. for (int i = 0; i < 4; i++) {
  9121. auto is_even = !(i % 2);
  9122. std::thread t{[&] {
  9123. try {
  9124. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9125. if (is_even) {
  9126. throw std::runtime_error("Some thing that happens to go wrong.");
  9127. }
  9128. svr.listen(HOST, PORT);
  9129. } catch (...) { svr.decommission(); }
  9130. }};
  9131. svr.wait_until_ready();
  9132. // Server is up
  9133. {
  9134. Client cli(HOST, PORT);
  9135. auto res = cli.Get("/hi");
  9136. if (is_even) {
  9137. EXPECT_FALSE(res);
  9138. } else {
  9139. EXPECT_TRUE(res);
  9140. EXPECT_EQ("hi...", res->body);
  9141. }
  9142. }
  9143. svr.stop();
  9144. t.join();
  9145. // Server is down...
  9146. {
  9147. Client cli(HOST, PORT);
  9148. auto res = cli.Get("/hi");
  9149. EXPECT_FALSE(res);
  9150. }
  9151. }
  9152. }
  9153. #endif
  9154. // Helper function for string body upload progress tests
  9155. template <typename SetupHandler, typename ClientCall>
  9156. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9157. ClientCall &&client_call,
  9158. const string &body) {
  9159. Server svr;
  9160. setup_handler(svr);
  9161. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9162. auto se = detail::scope_exit([&] {
  9163. svr.stop();
  9164. t.join();
  9165. });
  9166. svr.wait_until_ready();
  9167. Client cli(HOST, PORT);
  9168. vector<uint64_t> progress_values;
  9169. bool progress_called = false;
  9170. auto res =
  9171. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9172. progress_values.push_back(current);
  9173. progress_called = true;
  9174. return true;
  9175. });
  9176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9177. EXPECT_EQ(200, res->status);
  9178. EXPECT_TRUE(progress_called);
  9179. }
  9180. TEST(UploadProgressTest, PostStringBodyBasic) {
  9181. TestStringBodyUploadProgress(
  9182. [](Server &svr) {
  9183. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9184. res.set_content("received", "text/plain");
  9185. });
  9186. },
  9187. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9188. return cli.Post("/test", body, "text/plain", progress_callback);
  9189. },
  9190. "test data for upload progress");
  9191. }
  9192. TEST(UploadProgressTest, PutStringBodyBasic) {
  9193. TestStringBodyUploadProgress(
  9194. [](Server &svr) {
  9195. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9196. res.set_content("put received", "text/plain");
  9197. });
  9198. },
  9199. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9200. return cli.Put("/test", body, "text/plain", progress_callback);
  9201. },
  9202. "put test data for upload progress");
  9203. }
  9204. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9205. TestStringBodyUploadProgress(
  9206. [](Server &svr) {
  9207. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9208. res.set_content("patch received", "text/plain");
  9209. });
  9210. },
  9211. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9212. return cli.Patch("/test", body, "text/plain", progress_callback);
  9213. },
  9214. "patch test data for upload progress");
  9215. }
  9216. // Helper function for content provider upload progress tests
  9217. template <typename SetupHandler, typename ClientCall>
  9218. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9219. ClientCall &&client_call) {
  9220. Server svr;
  9221. setup_handler(svr);
  9222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9223. auto se = detail::scope_exit([&] {
  9224. svr.stop();
  9225. t.join();
  9226. });
  9227. svr.wait_until_ready();
  9228. Client cli(HOST, PORT);
  9229. vector<uint64_t> progress_values;
  9230. auto res =
  9231. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9232. progress_values.push_back(current);
  9233. return true;
  9234. });
  9235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9236. EXPECT_EQ(200, res->status);
  9237. EXPECT_FALSE(progress_values.empty());
  9238. }
  9239. TEST(UploadProgressTest, PostContentProviderProgress) {
  9240. TestContentProviderUploadProgress(
  9241. [](Server &svr) {
  9242. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9243. res.set_content("provider received", "text/plain");
  9244. });
  9245. },
  9246. [](Client &cli, UploadProgress progress_callback) {
  9247. return cli.Post(
  9248. "/test", 10,
  9249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9250. sink.os << "test data";
  9251. return true;
  9252. },
  9253. "text/plain", progress_callback);
  9254. });
  9255. }
  9256. // Helper function for multipart upload progress tests
  9257. template <typename SetupHandler, typename ClientCall>
  9258. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9259. ClientCall &&client_call,
  9260. const string &endpoint) {
  9261. Server svr;
  9262. setup_handler(svr);
  9263. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. t.join();
  9267. });
  9268. svr.wait_until_ready();
  9269. Client cli(HOST, PORT);
  9270. vector<uint64_t> progress_values;
  9271. UploadFormDataItems items = {
  9272. {"field1", "value1", "", ""},
  9273. {"field2", "longer value for progress tracking test", "", ""},
  9274. {"file1", "file content data for upload progress", "test.txt",
  9275. "text/plain"}};
  9276. auto res = client_call(cli, endpoint, items,
  9277. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9278. progress_values.push_back(current);
  9279. return true;
  9280. });
  9281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9282. EXPECT_EQ(200, res->status);
  9283. EXPECT_FALSE(progress_values.empty());
  9284. }
  9285. TEST(UploadProgressTest, PostMultipartProgress) {
  9286. TestMultipartUploadProgress(
  9287. [](Server &svr) {
  9288. svr.Post("/multipart", [](const Request &req, Response &res) {
  9289. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9290. res.set_content("multipart received", "text/plain");
  9291. });
  9292. },
  9293. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9294. UploadProgress progress_callback) {
  9295. return cli.Post(endpoint, items, progress_callback);
  9296. },
  9297. "/multipart");
  9298. }
  9299. // Helper function for basic download progress tests
  9300. template <typename SetupHandler, typename ClientCall>
  9301. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9302. ClientCall &&client_call, const string &endpoint,
  9303. size_t expected_content_size) {
  9304. Server svr;
  9305. setup_handler(svr);
  9306. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9307. auto se = detail::scope_exit([&] {
  9308. svr.stop();
  9309. t.join();
  9310. });
  9311. svr.wait_until_ready();
  9312. Client cli(HOST, PORT);
  9313. vector<uint64_t> progress_values;
  9314. auto res = client_call(cli, endpoint,
  9315. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9316. progress_values.push_back(current);
  9317. return true;
  9318. });
  9319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9320. EXPECT_EQ(200, res->status);
  9321. EXPECT_FALSE(progress_values.empty());
  9322. EXPECT_EQ(expected_content_size, res->body.size());
  9323. }
  9324. TEST(DownloadProgressTest, GetBasic) {
  9325. TestBasicDownloadProgress(
  9326. [](Server &svr) {
  9327. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9328. string content(1000, 'D');
  9329. res.set_content(content, "text/plain");
  9330. });
  9331. },
  9332. [](Client &cli, const string &endpoint,
  9333. DownloadProgress progress_callback) {
  9334. return cli.Get(endpoint, progress_callback);
  9335. },
  9336. "/download", 1000u);
  9337. }
  9338. // Helper function for content receiver download progress tests
  9339. template <typename SetupHandler, typename ClientCall>
  9340. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9341. ClientCall &&client_call,
  9342. const string &endpoint,
  9343. size_t expected_content_size) {
  9344. Server svr;
  9345. setup_handler(svr);
  9346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. t.join();
  9350. });
  9351. svr.wait_until_ready();
  9352. Client cli(HOST, PORT);
  9353. vector<uint64_t> progress_values;
  9354. string received_body;
  9355. auto res = client_call(
  9356. cli, endpoint,
  9357. [&](const char *data, size_t data_length) -> bool {
  9358. received_body.append(data, data_length);
  9359. return true;
  9360. },
  9361. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9362. progress_values.push_back(current);
  9363. return true;
  9364. });
  9365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9366. EXPECT_EQ(200, res->status);
  9367. EXPECT_FALSE(progress_values.empty());
  9368. EXPECT_EQ(expected_content_size, received_body.size());
  9369. EXPECT_TRUE(res->body.empty());
  9370. }
  9371. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9372. TestContentReceiverDownloadProgress(
  9373. [](Server &svr) {
  9374. svr.Get("/download-receiver",
  9375. [](const Request & /*req*/, Response &res) {
  9376. string content(2000, 'R');
  9377. res.set_content(content, "text/plain");
  9378. });
  9379. },
  9380. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9381. DownloadProgress progress_callback) {
  9382. return cli.Get(endpoint, content_receiver, progress_callback);
  9383. },
  9384. "/download-receiver", 2000u);
  9385. }
  9386. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9387. // A provider reaching a pass with nothing to hand over - an empty buffer
  9388. // popped off a queue, say - must not be taken to mean the body is finished.
  9389. // It used to end the loop with the terminating chunk unwritten while the
  9390. // server still considered the response complete, so the peer waited for an
  9391. // end that never arrived.
  9392. Server svr;
  9393. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9394. auto step = std::make_shared<int>(0);
  9395. res.set_chunked_content_provider("text/plain",
  9396. [step](size_t /*offset*/, DataSink &sink) {
  9397. switch ((*step)++) {
  9398. case 0: sink.write("", 0); break;
  9399. case 1: sink.write("hello", 5); break;
  9400. default: sink.done(); break;
  9401. }
  9402. return true;
  9403. });
  9404. });
  9405. auto port = svr.bind_to_any_port(HOST);
  9406. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9407. auto listen_se = detail::scope_exit([&] {
  9408. svr.stop();
  9409. listen_thread.join();
  9410. ASSERT_FALSE(svr.is_running());
  9411. });
  9412. svr.wait_until_ready();
  9413. Client cli(HOST, port);
  9414. // Without the fix the body is never terminated, so bound the wait rather
  9415. // than letting the test hang on the default read timeout.
  9416. cli.set_read_timeout(5, 0);
  9417. auto res = cli.Get("/stream");
  9418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9419. EXPECT_EQ(StatusCode::OK_200, res->status);
  9420. EXPECT_EQ("hello", res->body);
  9421. }
  9422. TEST(StreamingTest, NoContentLengthStreaming) {
  9423. Server svr;
  9424. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9425. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9426. if (offset < 6) {
  9427. sink.os << (offset < 3 ? "a" : "b");
  9428. } else {
  9429. sink.done();
  9430. }
  9431. return true;
  9432. });
  9433. });
  9434. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9435. auto listen_se = detail::scope_exit([&] {
  9436. svr.stop();
  9437. listen_thread.join();
  9438. ASSERT_FALSE(svr.is_running());
  9439. });
  9440. svr.wait_until_ready();
  9441. Client client(HOST, PORT);
  9442. auto get_thread = std::thread([&client]() {
  9443. std::string s;
  9444. auto res =
  9445. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9446. s += std::string(data, len);
  9447. return true;
  9448. });
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. EXPECT_EQ("aaabbb", s);
  9452. });
  9453. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9454. // Give GET time to get a few messages.
  9455. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9456. }
  9457. TEST(MountTest, Unmount) {
  9458. Server svr;
  9459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9460. auto se = detail::scope_exit([&] {
  9461. svr.stop();
  9462. listen_thread.join();
  9463. ASSERT_FALSE(svr.is_running());
  9464. });
  9465. svr.wait_until_ready();
  9466. Client cli("localhost", PORT);
  9467. svr.set_mount_point("/mount2", "./www2");
  9468. auto res = cli.Get("/");
  9469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9471. res = cli.Get("/mount2/dir/test.html");
  9472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9473. EXPECT_EQ(StatusCode::OK_200, res->status);
  9474. svr.set_mount_point("/", "./www");
  9475. res = cli.Get("/dir/");
  9476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9477. EXPECT_EQ(StatusCode::OK_200, res->status);
  9478. svr.remove_mount_point("/");
  9479. res = cli.Get("/dir/");
  9480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9481. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9482. svr.remove_mount_point("/mount2");
  9483. res = cli.Get("/mount2/dir/test.html");
  9484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9486. }
  9487. TEST(MountTest, PathSegmentBoundary) {
  9488. Server svr;
  9489. svr.set_mount_point("/mount2", "./www2");
  9490. svr.set_mount_point("/", "./www");
  9491. auto port = svr.bind_to_any_port(HOST);
  9492. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9493. auto se = detail::scope_exit([&] {
  9494. svr.stop();
  9495. listen_thread.join();
  9496. ASSERT_FALSE(svr.is_running());
  9497. });
  9498. svr.wait_until_ready();
  9499. Client cli(HOST, port);
  9500. auto res = cli.Get("/mount2/dir/test.html");
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. // "/mount2" must not match part-way through a path segment.
  9504. res = cli.Get("/mount2dir/test.html");
  9505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9507. // A mount point ending in '/' keeps matching every path below it.
  9508. res = cli.Get("/dir/test.html");
  9509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9510. EXPECT_EQ(StatusCode::OK_200, res->status);
  9511. }
  9512. TEST(MountTest, Redicect) {
  9513. Server svr;
  9514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. listen_thread.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.set_mount_point("/", "./www");
  9521. svr.wait_until_ready();
  9522. Client cli("localhost", PORT);
  9523. auto res = cli.Get("/dir/");
  9524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9525. EXPECT_EQ(StatusCode::OK_200, res->status);
  9526. res = cli.Get("/dir");
  9527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9528. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9529. res = cli.Get("/file");
  9530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9531. EXPECT_EQ(StatusCode::OK_200, res->status);
  9532. res = cli.Get("/file/");
  9533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9535. cli.set_follow_location(true);
  9536. res = cli.Get("/dir");
  9537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9538. EXPECT_EQ(StatusCode::OK_200, res->status);
  9539. }
  9540. TEST(MountTest, MultibytesPathName) {
  9541. Server svr;
  9542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9543. auto se = detail::scope_exit([&] {
  9544. svr.stop();
  9545. listen_thread.join();
  9546. ASSERT_FALSE(svr.is_running());
  9547. });
  9548. svr.set_mount_point("/", "./www");
  9549. svr.wait_until_ready();
  9550. Client cli("localhost", PORT);
  9551. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9553. EXPECT_EQ(StatusCode::OK_200, res->status);
  9554. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9555. }
  9556. #ifdef _WIN32
  9557. // Issue #2435: mmap::open() must succeed even when another handle holds
  9558. // the file open for writing (e.g. an active log file).
  9559. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9560. const char *path = "mmap_concurrent_writer_test.txt";
  9561. const char *content = "hello";
  9562. {
  9563. std::ofstream f(path, std::ios::binary);
  9564. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9565. }
  9566. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9567. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9568. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9569. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9570. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9571. detail::mmap m(path);
  9572. ASSERT_TRUE(m.is_open());
  9573. EXPECT_EQ(strlen(content), m.size());
  9574. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9575. }
  9576. #endif
  9577. #ifndef _WIN32
  9578. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9579. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9580. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9581. TEST(MmapTest, FailedMappingIsNotOpen) {
  9582. const char *path = "./mmap_failed_mapping_test_dir";
  9583. ASSERT_EQ(0, ::mkdir(path, 0755));
  9584. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9585. detail::mmap m(path);
  9586. EXPECT_FALSE(m.is_open());
  9587. EXPECT_EQ(0U, m.size());
  9588. EXPECT_NE(static_cast<const void *>(m.data()),
  9589. static_cast<const void *>(MAP_FAILED));
  9590. }
  9591. #endif
  9592. TEST(KeepAliveTest, ReadTimeout) {
  9593. Server svr;
  9594. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9595. std::this_thread::sleep_for(std::chrono::seconds(2));
  9596. res.set_content("a", "text/plain");
  9597. });
  9598. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9599. res.set_content("b", "text/plain");
  9600. });
  9601. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9602. auto se = detail::scope_exit([&] {
  9603. svr.stop();
  9604. listen_thread.join();
  9605. ASSERT_FALSE(svr.is_running());
  9606. });
  9607. svr.wait_until_ready();
  9608. Client cli("localhost", PORT);
  9609. cli.set_keep_alive(true);
  9610. cli.set_read_timeout(std::chrono::seconds(1));
  9611. auto resa = cli.Get("/a");
  9612. ASSERT_FALSE(resa);
  9613. EXPECT_EQ(Error::Read, resa.error());
  9614. auto resb = cli.Get("/b");
  9615. ASSERT_TRUE(resb);
  9616. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9617. EXPECT_EQ("b", resb->body);
  9618. }
  9619. TEST(KeepAliveTest, MaxCount) {
  9620. size_t keep_alive_max_count = 3;
  9621. Server svr;
  9622. svr.set_keep_alive_max_count(keep_alive_max_count);
  9623. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9624. res.set_content("Hello World!", "text/plain");
  9625. });
  9626. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. listen_thread.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. Client cli(HOST, PORT);
  9634. cli.set_keep_alive(true);
  9635. for (size_t i = 0; i < 5; i++) {
  9636. auto result = cli.Get("/hi");
  9637. ASSERT_TRUE(result);
  9638. EXPECT_EQ(StatusCode::OK_200, result->status);
  9639. if (i == keep_alive_max_count - 1) {
  9640. EXPECT_EQ("close", result->get_header_value("Connection"));
  9641. } else {
  9642. EXPECT_FALSE(result->has_header("Connection"));
  9643. }
  9644. }
  9645. }
  9646. TEST(KeepAliveTest, Issue1041) {
  9647. Server svr;
  9648. svr.set_keep_alive_timeout(3);
  9649. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9650. res.set_content("Hello World!", "text/plain");
  9651. });
  9652. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. svr.stop();
  9655. listen_thread.join();
  9656. ASSERT_FALSE(svr.is_running());
  9657. });
  9658. svr.wait_until_ready();
  9659. Client cli(HOST, PORT);
  9660. cli.set_keep_alive(true);
  9661. auto result = cli.Get("/hi");
  9662. ASSERT_TRUE(result);
  9663. EXPECT_EQ(StatusCode::OK_200, result->status);
  9664. std::this_thread::sleep_for(std::chrono::seconds(5));
  9665. result = cli.Get("/hi");
  9666. ASSERT_TRUE(result);
  9667. EXPECT_EQ(StatusCode::OK_200, result->status);
  9668. }
  9669. TEST(KeepAliveTest, Issue1959) {
  9670. Server svr;
  9671. svr.set_keep_alive_timeout(5);
  9672. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9673. res.set_content("a", "text/plain");
  9674. });
  9675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9676. auto se = detail::scope_exit([&] {
  9677. if (!svr.is_running()) return;
  9678. svr.stop();
  9679. listen_thread.join();
  9680. ASSERT_FALSE(svr.is_running());
  9681. });
  9682. svr.wait_until_ready();
  9683. Client cli("localhost", PORT);
  9684. cli.set_keep_alive(true);
  9685. using namespace std::chrono;
  9686. auto start = steady_clock::now();
  9687. cli.Get("/a");
  9688. svr.stop();
  9689. listen_thread.join();
  9690. auto end = steady_clock::now();
  9691. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9692. EXPECT_LT(elapsed, 5000);
  9693. }
  9694. #ifdef CPPHTTPLIB_SSL_ENABLED
  9695. TEST(KeepAliveTest, SSLClientReconnection) {
  9696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9697. ASSERT_TRUE(svr.is_valid());
  9698. svr.set_keep_alive_timeout(1);
  9699. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9700. res.set_content("Hello World!", "text/plain");
  9701. });
  9702. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. listen_thread.join();
  9706. ASSERT_FALSE(svr.is_running());
  9707. });
  9708. svr.wait_until_ready();
  9709. SSLClient cli(HOST, PORT);
  9710. cli.enable_server_certificate_verification(false);
  9711. cli.set_keep_alive(true);
  9712. auto result = cli.Get("/hi");
  9713. ASSERT_TRUE(result);
  9714. EXPECT_EQ(StatusCode::OK_200, result->status);
  9715. result = cli.Get("/hi");
  9716. ASSERT_TRUE(result);
  9717. EXPECT_EQ(StatusCode::OK_200, result->status);
  9718. std::this_thread::sleep_for(std::chrono::seconds(2));
  9719. // Recoonect
  9720. result = cli.Get("/hi");
  9721. ASSERT_TRUE(result);
  9722. EXPECT_EQ(StatusCode::OK_200, result->status);
  9723. result = cli.Get("/hi");
  9724. ASSERT_TRUE(result);
  9725. EXPECT_EQ(StatusCode::OK_200, result->status);
  9726. }
  9727. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9729. ASSERT_TRUE(svr.is_valid());
  9730. svr.set_keep_alive_timeout(1);
  9731. std::string content = "reconnect";
  9732. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9733. res.set_content("Hello World!", "text/plain");
  9734. });
  9735. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9736. auto se = detail::scope_exit([&] {
  9737. svr.stop();
  9738. listen_thread.join();
  9739. ASSERT_FALSE(svr.is_running());
  9740. });
  9741. svr.wait_until_ready();
  9742. SSLClient cli(HOST, PORT);
  9743. cli.enable_server_certificate_verification(false);
  9744. cli.set_keep_alive(true);
  9745. auto result = cli.Post(
  9746. "/hi", content.size(),
  9747. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9748. sink.write(content.c_str(), content.size());
  9749. return true;
  9750. },
  9751. "text/plain");
  9752. ASSERT_TRUE(result);
  9753. EXPECT_EQ(200, result->status);
  9754. std::this_thread::sleep_for(std::chrono::seconds(2));
  9755. // Recoonect
  9756. result = cli.Post(
  9757. "/hi", content.size(),
  9758. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9759. sink.write(content.c_str(), content.size());
  9760. return true;
  9761. },
  9762. "text/plain");
  9763. ASSERT_TRUE(result);
  9764. EXPECT_EQ(200, result->status);
  9765. result = cli.Post(
  9766. "/hi", content.size(),
  9767. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9768. sink.write(content.c_str(), content.size());
  9769. return true;
  9770. },
  9771. "text/plain");
  9772. ASSERT_TRUE(result);
  9773. EXPECT_EQ(200, result->status);
  9774. }
  9775. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9776. using namespace httplib::tls;
  9777. {
  9778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9779. ASSERT_TRUE(svr.is_valid());
  9780. svr.Get("/sni", [&](const Request &req, Response &res) {
  9781. std::string expected = req.sni();
  9782. EXPECT_EQ(expected, req.get_param_value("expected"));
  9783. res.set_content("ok", "text/plain");
  9784. });
  9785. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. listen_thread.join();
  9789. ASSERT_FALSE(svr.is_running());
  9790. });
  9791. svr.wait_until_ready();
  9792. {
  9793. SSLClient cli("localhost", PORT);
  9794. cli.enable_server_certificate_verification(false);
  9795. auto res = cli.Get("/sni?expected=localhost");
  9796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9797. }
  9798. {
  9799. SSLClient cli("::1", PORT);
  9800. cli.enable_server_certificate_verification(false);
  9801. auto res = cli.Get("/sni?expected=");
  9802. // NOTE: This may fail if the server is listening on IPv4 only
  9803. // (e.g., when localhost resolves to 127.0.0.1 only)
  9804. if (res) {
  9805. EXPECT_EQ(StatusCode::OK_200, res->status);
  9806. } else {
  9807. EXPECT_EQ(Error::Connection, res.error());
  9808. }
  9809. }
  9810. }
  9811. }
  9812. #endif
  9813. TEST(ClientProblemDetectionTest, ContentProvider) {
  9814. Server svr;
  9815. size_t content_length = 1024 * 1024;
  9816. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9817. res.set_content_provider(
  9818. content_length, "text/plain",
  9819. [&](size_t offset, size_t length, DataSink &sink) {
  9820. auto out_len = std::min(length, static_cast<size_t>(1024));
  9821. std::string out(out_len, '@');
  9822. sink.write(out.data(), out_len);
  9823. return offset < 4096;
  9824. },
  9825. [](bool success) { ASSERT_FALSE(success); });
  9826. });
  9827. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9828. res.set_content_provider(
  9829. 0, "text/plain",
  9830. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9831. EXPECT_TRUE(false);
  9832. return true;
  9833. },
  9834. [](bool success) { ASSERT_FALSE(success); });
  9835. });
  9836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9837. auto se = detail::scope_exit([&] {
  9838. svr.stop();
  9839. listen_thread.join();
  9840. ASSERT_FALSE(svr.is_running());
  9841. });
  9842. svr.wait_until_ready();
  9843. Client cli("localhost", PORT);
  9844. {
  9845. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9846. size_t /*data_length*/) { return false; });
  9847. ASSERT_FALSE(res);
  9848. }
  9849. {
  9850. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9851. size_t /*data_length*/) { return false; });
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. }
  9854. }
  9855. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9856. // A provider that reports success without writing anything and without
  9857. // calling done() used to be handed the same offset and length again on every
  9858. // pass, so it spun for as long as the peer stayed connected.
  9859. Server svr;
  9860. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9861. res.set_content("ok", "text/plain");
  9862. });
  9863. auto port = svr.bind_to_any_port(HOST);
  9864. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  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. std::atomic<int> call_count{0};
  9872. Client cli(HOST, port);
  9873. auto res = cli.Post(
  9874. "/", 1024,
  9875. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9876. // Give up after enough passes to show the spin, so that losing the
  9877. // check below fails this test instead of hanging it.
  9878. return ++call_count < 100;
  9879. },
  9880. "text/plain");
  9881. ASSERT_FALSE(res);
  9882. EXPECT_EQ(Error::Write, res.error());
  9883. EXPECT_EQ(1, call_count.load());
  9884. }
  9885. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9886. // A writer only has to assign `write`. The other three used to be left as
  9887. // empty std::functions, so a provider calling one threw
  9888. // std::bad_function_call out of the thread running it and took the whole
  9889. // process down.
  9890. DataSink sink;
  9891. std::string written;
  9892. sink.write = [&](const char *data, size_t data_len) {
  9893. written.append(data, data_len);
  9894. return true;
  9895. };
  9896. EXPECT_TRUE(sink.is_writable());
  9897. sink.done();
  9898. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9899. EXPECT_TRUE(written.empty());
  9900. }
  9901. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9902. // A sink that cannot carry trailers still has to finish.
  9903. DataSink sink;
  9904. auto done_count = 0;
  9905. sink.done = [&]() { done_count++; };
  9906. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9907. EXPECT_EQ(1, done_count);
  9908. }
  9909. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9910. Server svr;
  9911. const std::string body(4096, 'x');
  9912. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9913. res.set_content_provider(body.size(), "text/plain",
  9914. [&](size_t offset, size_t length, DataSink &sink) {
  9915. sink.write(body.data() + offset, length);
  9916. sink.done();
  9917. return true;
  9918. });
  9919. });
  9920. auto port = svr.bind_to_any_port(HOST);
  9921. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9922. auto se = detail::scope_exit([&] {
  9923. svr.stop();
  9924. listen_thread.join();
  9925. ASSERT_FALSE(svr.is_running());
  9926. });
  9927. svr.wait_until_ready();
  9928. Client cli(HOST, port);
  9929. auto res = cli.Get("/");
  9930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9931. EXPECT_EQ(StatusCode::OK_200, res->status);
  9932. EXPECT_EQ(body, res->body);
  9933. }
  9934. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9935. Server svr;
  9936. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9937. res.set_content_provider(
  9938. 1024, "text/plain",
  9939. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9940. sink.write("hello", 5);
  9941. sink.done(); // short of the 1024 bytes the response promised
  9942. return true;
  9943. });
  9944. });
  9945. auto port = svr.bind_to_any_port(HOST);
  9946. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9947. auto se = detail::scope_exit([&] {
  9948. svr.stop();
  9949. listen_thread.join();
  9950. ASSERT_FALSE(svr.is_running());
  9951. });
  9952. svr.wait_until_ready();
  9953. Client cli(HOST, port);
  9954. cli.set_read_timeout(5, 0);
  9955. // The response is short of its Content-Length, so the client cannot read a
  9956. // complete body. What matters is that this returns at all: a no-op done()
  9957. // would leave the writer looping over a provider that never makes progress.
  9958. auto res = cli.Get("/");
  9959. EXPECT_FALSE(res);
  9960. }
  9961. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9962. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9963. // The compressed path builds the whole body before connecting, so this
  9964. // fails client-side and never reaches a server.
  9965. Client cli(HOST, PORT);
  9966. cli.set_compress(true);
  9967. auto res = cli.Post(
  9968. "/", 1024,
  9969. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9970. sink.write("hello", 5);
  9971. sink.done(); // short of the 1024 bytes the request announced
  9972. return true;
  9973. },
  9974. "text/plain");
  9975. ASSERT_FALSE(res);
  9976. EXPECT_EQ(Error::Write, res.error());
  9977. }
  9978. #endif
  9979. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9980. Server svr;
  9981. svr.set_error_handler([](Request const &, Response &res) -> void {
  9982. res.set_chunked_content_provider(
  9983. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9984. sink.os << "hello";
  9985. sink.os << "world";
  9986. sink.done();
  9987. return true;
  9988. });
  9989. });
  9990. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. listen_thread.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. Client cli("localhost", PORT);
  9998. auto res = cli.Get("/");
  9999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10000. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10001. EXPECT_EQ("helloworld", res->body);
  10002. }
  10003. TEST(LongPollingTest, ClientCloseDetection) {
  10004. Server svr;
  10005. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10006. res.set_chunked_content_provider(
  10007. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10008. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10009. sink.os << "hello";
  10010. auto count = 10;
  10011. while (count > 0 && sink.is_writable()) {
  10012. this_thread::sleep_for(chrono::milliseconds(10));
  10013. count--;
  10014. }
  10015. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10016. return true;
  10017. });
  10018. });
  10019. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10020. auto se = detail::scope_exit([&] {
  10021. svr.stop();
  10022. listen_thread.join();
  10023. ASSERT_FALSE(svr.is_running());
  10024. });
  10025. svr.wait_until_ready();
  10026. Client cli("localhost", PORT);
  10027. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10028. EXPECT_EQ("hello", string(data, data_length));
  10029. return false; // close the socket immediately.
  10030. });
  10031. ASSERT_FALSE(res);
  10032. }
  10033. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10034. Server svr;
  10035. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10036. res.set_chunked_content_provider(
  10037. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10038. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10039. sink.os << "hello";
  10040. EXPECT_TRUE(sink.os.good());
  10041. // Wait for the client to close the connection
  10042. auto count = 10;
  10043. while (count > 0 && sink.is_writable()) {
  10044. this_thread::sleep_for(chrono::milliseconds(10));
  10045. count--;
  10046. }
  10047. // After client disconnect, write repeatedly until the socket
  10048. // write actually fails (small writes may be absorbed by the
  10049. // kernel buffer)
  10050. std::string chunk(1024, 'x');
  10051. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10052. sink.os << chunk;
  10053. }
  10054. EXPECT_TRUE(sink.os.fail());
  10055. return true;
  10056. });
  10057. });
  10058. auto port = svr.bind_to_any_port("localhost");
  10059. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10060. auto se = detail::scope_exit([&] {
  10061. svr.stop();
  10062. listen_thread.join();
  10063. ASSERT_FALSE(svr.is_running());
  10064. });
  10065. svr.wait_until_ready();
  10066. Client cli("localhost", port);
  10067. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10068. EXPECT_EQ("hello", string(data, data_length));
  10069. return false; // close the socket immediately.
  10070. });
  10071. ASSERT_FALSE(res);
  10072. }
  10073. TEST(GetWithParametersTest, GetWithParameters) {
  10074. Server svr;
  10075. svr.Get("/", [&](const Request &req, Response &) {
  10076. EXPECT_EQ("world", req.get_param_value("hello"));
  10077. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10078. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10079. });
  10080. svr.Get("/params", [&](const Request &req, Response &) {
  10081. EXPECT_EQ("world", req.get_param_value("hello"));
  10082. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10083. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10084. });
  10085. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10086. EXPECT_EQ("resource-id", req.matches[1]);
  10087. EXPECT_EQ("foo", req.get_param_value("param1"));
  10088. EXPECT_EQ("bar", req.get_param_value("param2"));
  10089. });
  10090. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10091. EXPECT_EQ("user-id", req.path_params.at("id"));
  10092. EXPECT_EQ("foo", req.get_param_value("param1"));
  10093. EXPECT_EQ("bar", req.get_param_value("param2"));
  10094. });
  10095. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. listen_thread.join();
  10099. ASSERT_FALSE(svr.is_running());
  10100. });
  10101. svr.wait_until_ready();
  10102. {
  10103. Client cli(HOST, PORT);
  10104. Params params;
  10105. params.emplace("hello", "world");
  10106. params.emplace("hello2", "world2");
  10107. params.emplace("hello3", "world3");
  10108. auto res = cli.Get("/", params, Headers{});
  10109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10110. EXPECT_EQ(StatusCode::OK_200, res->status);
  10111. }
  10112. {
  10113. Client cli(HOST, PORT);
  10114. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10116. EXPECT_EQ(StatusCode::OK_200, res->status);
  10117. }
  10118. {
  10119. Client cli(HOST, PORT);
  10120. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10122. EXPECT_EQ(StatusCode::OK_200, res->status);
  10123. }
  10124. {
  10125. Client cli(HOST, PORT);
  10126. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. EXPECT_EQ(StatusCode::OK_200, res->status);
  10129. }
  10130. }
  10131. TEST(GetWithParametersTest, GetWithParameters2) {
  10132. Server svr;
  10133. svr.Get("/", [&](const Request &req, Response &res) {
  10134. auto text = req.get_param_value("hello");
  10135. res.set_content(text, "text/plain");
  10136. });
  10137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. listen_thread.join();
  10141. ASSERT_FALSE(svr.is_running());
  10142. });
  10143. svr.wait_until_ready();
  10144. Client cli("localhost", PORT);
  10145. Params params;
  10146. params.emplace("hello", "world");
  10147. std::string body;
  10148. auto res = cli.Get("/", params, Headers{},
  10149. [&](const char *data, size_t data_length) {
  10150. body.append(data, data_length);
  10151. return true;
  10152. });
  10153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10154. EXPECT_EQ(StatusCode::OK_200, res->status);
  10155. EXPECT_EQ("world", body);
  10156. }
  10157. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10158. Server svr;
  10159. svr.Get("/search", [&](const Request &req, Response &res) {
  10160. auto q = req.get_param_value("q");
  10161. res.set_content(q, "text/plain");
  10162. });
  10163. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10164. auto se = detail::scope_exit([&] {
  10165. svr.stop();
  10166. listen_thread.join();
  10167. ASSERT_FALSE(svr.is_running());
  10168. });
  10169. svr.wait_until_ready();
  10170. Client cli("localhost", PORT);
  10171. // Verify that Get(path, params) works without requiring Headers argument
  10172. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10174. EXPECT_EQ(StatusCode::OK_200, res->status);
  10175. EXPECT_EQ("cpp-httplib", res->body);
  10176. }
  10177. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10178. auto host = "httpbingo.org";
  10179. auto path = std::string{"/range/32"};
  10180. #ifdef CPPHTTPLIB_SSL_ENABLED
  10181. SSLClient cli(host);
  10182. #else
  10183. Client cli(host);
  10184. #endif
  10185. cli.set_default_headers({make_range_header({{1, 10}})});
  10186. cli.set_connection_timeout(5);
  10187. {
  10188. auto res = cli.Get(path);
  10189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10190. EXPECT_EQ("bcdefghijk", res->body);
  10191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10192. }
  10193. {
  10194. auto res = cli.Get(path);
  10195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10196. EXPECT_EQ("bcdefghijk", res->body);
  10197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10198. }
  10199. }
  10200. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10201. Server svr;
  10202. svr.set_default_headers({{"Hello", "World"}});
  10203. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10204. res.set_content("ok", "text/plain");
  10205. });
  10206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10207. auto se = detail::scope_exit([&] {
  10208. svr.stop();
  10209. listen_thread.join();
  10210. ASSERT_FALSE(svr.is_running());
  10211. });
  10212. svr.wait_until_ready();
  10213. Client cli("localhost", PORT);
  10214. auto res = cli.Get("/");
  10215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10216. EXPECT_EQ(StatusCode::OK_200, res->status);
  10217. EXPECT_EQ("ok", res->body);
  10218. EXPECT_EQ("World", res->get_header_value("Hello"));
  10219. }
  10220. #ifdef CPPHTTPLIB_SSL_ENABLED
  10221. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10223. ASSERT_TRUE(svr.is_valid());
  10224. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10225. std::this_thread::sleep_for(std::chrono::seconds(2));
  10226. res.set_content("a", "text/plain");
  10227. });
  10228. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10229. res.set_content("b", "text/plain");
  10230. });
  10231. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10232. auto se = detail::scope_exit([&] {
  10233. svr.stop();
  10234. listen_thread.join();
  10235. ASSERT_FALSE(svr.is_running());
  10236. });
  10237. svr.wait_until_ready();
  10238. SSLClient cli("localhost", PORT);
  10239. cli.enable_server_certificate_verification(false);
  10240. cli.set_keep_alive(true);
  10241. cli.set_read_timeout(std::chrono::seconds(1));
  10242. auto resa = cli.Get("/a");
  10243. ASSERT_TRUE(!resa);
  10244. EXPECT_EQ(Error::Read, resa.error());
  10245. auto resb = cli.Get("/b");
  10246. ASSERT_TRUE(resb);
  10247. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10248. EXPECT_EQ("b", resb->body);
  10249. }
  10250. // Closing an idle keep-alive connection sends close_notify and returns. The
  10251. // server must not wait for the client's close_notify: an idle client never
  10252. // sends one, so the worker would be held until the read timeout expires, and
  10253. // stop() would wait for it.
  10254. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10256. ASSERT_TRUE(svr.is_valid());
  10257. svr.set_keep_alive_timeout(1);
  10258. svr.set_read_timeout(10, 0);
  10259. svr.Get("/", [](const Request &, Response &res) {
  10260. res.set_content("ok", "text/plain");
  10261. });
  10262. auto port = svr.bind_to_any_port(HOST);
  10263. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10264. auto se = detail::scope_exit([&] {
  10265. if (listen_thread.joinable()) {
  10266. svr.stop();
  10267. listen_thread.join();
  10268. }
  10269. });
  10270. svr.wait_until_ready();
  10271. SSLClient cli(HOST, port);
  10272. cli.enable_server_certificate_verification(false);
  10273. cli.set_keep_alive(true);
  10274. auto res = cli.Get("/");
  10275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10276. EXPECT_EQ(StatusCode::OK_200, res->status);
  10277. // Stay idle past the keep-alive timeout so the server closes the connection.
  10278. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10279. auto start = std::chrono::steady_clock::now();
  10280. svr.stop();
  10281. listen_thread.join();
  10282. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10283. std::chrono::steady_clock::now() - start)
  10284. .count();
  10285. EXPECT_LT(elapsed, 3000);
  10286. }
  10287. #endif
  10288. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10289. protected:
  10290. ServerTestWithAI_PASSIVE()
  10291. : cli_(HOST, PORT)
  10292. #ifdef CPPHTTPLIB_SSL_ENABLED
  10293. ,
  10294. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10295. #endif
  10296. {
  10297. #ifdef CPPHTTPLIB_SSL_ENABLED
  10298. cli_.enable_server_certificate_verification(false);
  10299. #endif
  10300. }
  10301. virtual void SetUp() {
  10302. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10303. res.set_content("Hello World!", "text/plain");
  10304. });
  10305. t_ = thread(
  10306. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10307. svr_.wait_until_ready();
  10308. }
  10309. virtual void TearDown() {
  10310. svr_.stop();
  10311. t_.join();
  10312. }
  10313. #ifdef CPPHTTPLIB_SSL_ENABLED
  10314. SSLClient cli_;
  10315. SSLServer svr_;
  10316. #else
  10317. Client cli_;
  10318. Server svr_;
  10319. #endif
  10320. thread t_;
  10321. };
  10322. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10323. auto res = cli_.Get("/hi");
  10324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10325. EXPECT_EQ(StatusCode::OK_200, res->status);
  10326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10327. EXPECT_EQ("Hello World!", res->body);
  10328. }
  10329. class ServerUpDownTest : public ::testing::Test {
  10330. protected:
  10331. ServerUpDownTest() : cli_(HOST, PORT) {}
  10332. virtual void SetUp() {
  10333. t_ = thread([&]() {
  10334. svr_.bind_to_any_port(HOST);
  10335. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10336. ASSERT_TRUE(svr_.listen_after_bind());
  10337. });
  10338. svr_.wait_until_ready();
  10339. }
  10340. virtual void TearDown() {
  10341. svr_.stop();
  10342. t_.join();
  10343. }
  10344. Client cli_;
  10345. Server svr_;
  10346. thread t_;
  10347. };
  10348. TEST_F(ServerUpDownTest, QuickStartStop) {
  10349. // Should not crash, especially when run with
  10350. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10351. }
  10352. class PayloadMaxLengthTest : public ::testing::Test {
  10353. protected:
  10354. PayloadMaxLengthTest()
  10355. : cli_(HOST, PORT)
  10356. #ifdef CPPHTTPLIB_SSL_ENABLED
  10357. ,
  10358. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10359. #endif
  10360. {
  10361. #ifdef CPPHTTPLIB_SSL_ENABLED
  10362. cli_.enable_server_certificate_verification(false);
  10363. #endif
  10364. }
  10365. virtual void SetUp() {
  10366. svr_.set_payload_max_length(8);
  10367. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10368. res.set_content("test", "text/plain");
  10369. });
  10370. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10371. svr_.wait_until_ready();
  10372. }
  10373. virtual void TearDown() {
  10374. svr_.stop();
  10375. t_.join();
  10376. }
  10377. #ifdef CPPHTTPLIB_SSL_ENABLED
  10378. SSLClient cli_;
  10379. SSLServer svr_;
  10380. #else
  10381. Client cli_;
  10382. Server svr_;
  10383. #endif
  10384. thread t_;
  10385. };
  10386. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10387. auto res = cli_.Post("/test", "123456789", "text/plain");
  10388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10389. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10390. res = cli_.Post("/test", "12345678", "text/plain");
  10391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10392. EXPECT_EQ(StatusCode::OK_200, res->status);
  10393. }
  10394. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10395. // Test chunked encoding with payload exceeding the 8-byte limit
  10396. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10397. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10399. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10400. }
  10401. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10402. // Test chunked encoding with payload within the 8-byte limit
  10403. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10404. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10406. EXPECT_EQ(StatusCode::OK_200, res->status);
  10407. }
  10408. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10409. // Test using send_request to send chunked data exceeding payload limit
  10410. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10411. "Host: " +
  10412. std::string(HOST) + ":" + std::to_string(PORT) +
  10413. "\r\n"
  10414. "Transfer-Encoding: chunked\r\n"
  10415. "Connection: close\r\n"
  10416. "\r\n"
  10417. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10418. "0123456789\r\n"
  10419. "0\r\n" // End chunk
  10420. "\r\n";
  10421. std::string response;
  10422. bool result = send_request(1, chunked_request, &response);
  10423. if (!result) {
  10424. // If send_request fails, it might be because the server closed the
  10425. // connection due to payload limit enforcement, which is acceptable
  10426. SUCCEED()
  10427. << "Server rejected oversized chunked request (connection closed)";
  10428. } else {
  10429. // If we got a response, check if it's an error response or connection was
  10430. // closed early Short response length indicates connection was closed due to
  10431. // payload limit
  10432. if (response.length() <= 10) {
  10433. SUCCEED() << "Server closed connection for oversized chunked request";
  10434. } else {
  10435. // Check for error status codes
  10436. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10437. response.find("Payload Too Large") != std::string::npos ||
  10438. response.find("400") != std::string::npos);
  10439. }
  10440. }
  10441. }
  10442. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10443. // Test request without Content-Length header exceeding payload limit
  10444. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10445. "Host: " +
  10446. std::string(HOST) + ":" +
  10447. std::to_string(PORT) +
  10448. "\r\n"
  10449. "Connection: close\r\n"
  10450. "\r\n";
  10451. // Add payload exceeding the 8-byte limit
  10452. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10453. request_without_content_length += large_payload;
  10454. std::string response;
  10455. bool result = send_request(1, request_without_content_length, &response);
  10456. if (!result) {
  10457. // If send_request fails, server likely closed connection due to payload
  10458. // limit
  10459. SUCCEED() << "Server rejected oversized request without Content-Length "
  10460. "(connection closed)";
  10461. } else {
  10462. // Check if server responded with error or closed connection early
  10463. if (response.length() <= 10) {
  10464. SUCCEED() << "Server closed connection for oversized request without "
  10465. "Content-Length";
  10466. } else {
  10467. // Check for error status codes
  10468. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10469. response.find("Payload Too Large") != std::string::npos ||
  10470. response.find("400") != std::string::npos);
  10471. }
  10472. }
  10473. }
  10474. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10475. // Test request without Content-Length header within payload limit
  10476. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10477. "Host: " +
  10478. std::string(HOST) + ":" +
  10479. std::to_string(PORT) +
  10480. "\r\n"
  10481. "Connection: close\r\n"
  10482. "\r\n";
  10483. // Add payload within the 8-byte limit
  10484. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10485. request_without_content_length += small_payload;
  10486. std::string response;
  10487. bool result = send_request(1, request_without_content_length, &response);
  10488. // For requests without Content-Length, the server may have different behavior
  10489. // The key is that it should not reject due to payload limit for small
  10490. // payloads
  10491. if (result) {
  10492. // Check for any HTTP response (success or error, but not connection closed)
  10493. if (response.length() > 10) {
  10494. SUCCEED()
  10495. << "Server processed request without Content-Length within limit";
  10496. } else {
  10497. // Short response might indicate connection closed, which is acceptable
  10498. SUCCEED() << "Server closed connection for request without "
  10499. "Content-Length (acceptable behavior)";
  10500. }
  10501. } else {
  10502. // Connection failure might be due to protocol requirements
  10503. SUCCEED() << "Connection issue with request without Content-Length "
  10504. "(environment-specific)";
  10505. }
  10506. }
  10507. class LargePayloadMaxLengthTest : public ::testing::Test {
  10508. protected:
  10509. LargePayloadMaxLengthTest()
  10510. : cli_(HOST, PORT)
  10511. #ifdef CPPHTTPLIB_SSL_ENABLED
  10512. ,
  10513. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10514. #endif
  10515. {
  10516. #ifdef CPPHTTPLIB_SSL_ENABLED
  10517. cli_.enable_server_certificate_verification(false);
  10518. #endif
  10519. }
  10520. virtual void SetUp() {
  10521. // Set 10MB payload limit
  10522. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10523. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10524. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10525. res.set_content("Large payload test", "text/plain");
  10526. });
  10527. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10528. svr_.wait_until_ready();
  10529. }
  10530. virtual void TearDown() {
  10531. svr_.stop();
  10532. t_.join();
  10533. }
  10534. #ifdef CPPHTTPLIB_SSL_ENABLED
  10535. SSLClient cli_;
  10536. SSLServer svr_;
  10537. #else
  10538. Client cli_;
  10539. Server svr_;
  10540. #endif
  10541. thread t_;
  10542. };
  10543. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10544. // Test chunked encoding with payload within 10MB limit
  10545. std::string medium_payload(5 * 1024 * 1024,
  10546. 'A'); // 5MB payload, within 10MB limit
  10547. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. }
  10551. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10552. // Test chunked encoding with payload exceeding 10MB limit
  10553. std::string large_payload(12 * 1024 * 1024,
  10554. 'B'); // 12MB payload, exceeds 10MB limit
  10555. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10556. // Server may either return 413 or close the connection
  10557. if (res) {
  10558. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10559. } else {
  10560. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10561. }
  10562. }
  10563. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10564. // Test request without Content-Length header within 10MB limit
  10565. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10566. "Host: " +
  10567. std::string(HOST) + ":" +
  10568. std::to_string(PORT) +
  10569. "\r\n"
  10570. "Connection: close\r\n"
  10571. "\r\n";
  10572. // Add 1MB payload (within 10MB limit)
  10573. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10574. request_without_content_length += medium_payload;
  10575. std::string response;
  10576. bool result = send_request(5, request_without_content_length, &response);
  10577. if (result) {
  10578. // Should get a proper HTTP response for payloads within limit
  10579. if (response.length() > 10) {
  10580. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10581. "10MB limit";
  10582. } else {
  10583. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10584. "Content-Length)";
  10585. }
  10586. } else {
  10587. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10588. }
  10589. }
  10590. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10591. // Test request without Content-Length header exceeding 10MB limit
  10592. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10593. "Host: " +
  10594. std::string(HOST) + ":" +
  10595. std::to_string(PORT) +
  10596. "\r\n"
  10597. "Connection: close\r\n"
  10598. "\r\n";
  10599. // Add 12MB payload (exceeds 10MB limit)
  10600. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10601. request_without_content_length += large_payload;
  10602. std::string response;
  10603. bool result = send_request(10, request_without_content_length, &response);
  10604. if (!result) {
  10605. // Server should close connection due to payload limit
  10606. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10607. "(connection closed)";
  10608. } else {
  10609. // Check for error response
  10610. if (response.length() <= 10) {
  10611. SUCCEED()
  10612. << "Server closed connection for 12MB request exceeding 10MB limit";
  10613. } else {
  10614. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10615. response.find("Payload Too Large") != std::string::npos ||
  10616. response.find("400") != std::string::npos);
  10617. }
  10618. }
  10619. }
  10620. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10621. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10622. // path.
  10623. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10624. Server svr;
  10625. const size_t LIMIT = 64 * 1024; // 64KB
  10626. svr.set_payload_max_length(LIMIT);
  10627. size_t total = 0;
  10628. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10629. const ContentReader &content_reader) {
  10630. content_reader([&](const char * /*data*/, size_t len) {
  10631. total += len;
  10632. return true;
  10633. });
  10634. res.status = 200;
  10635. res.set_content("stream_ok", "text/plain");
  10636. });
  10637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10638. auto se = detail::scope_exit([&] {
  10639. svr.stop();
  10640. thread.join();
  10641. ASSERT_FALSE(svr.is_running());
  10642. });
  10643. svr.wait_until_ready();
  10644. // Prepare 256KB raw data and gzip-compress it
  10645. std::string raw(256 * 1024, 'A');
  10646. std::string gz;
  10647. {
  10648. z_stream zs{};
  10649. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10650. Z_DEFAULT_STRATEGY);
  10651. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10652. zs.avail_in = static_cast<uInt>(raw.size());
  10653. char outbuf[4096];
  10654. int ret;
  10655. do {
  10656. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10657. zs.avail_out = sizeof(outbuf);
  10658. ret = deflate(&zs, Z_FINISH);
  10659. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10660. } while (ret != Z_STREAM_END);
  10661. deflateEnd(&zs);
  10662. }
  10663. Client cli(HOST, PORT);
  10664. cli.set_connection_timeout(std::chrono::seconds(5));
  10665. Headers headers = {{"Content-Encoding", "gzip"}};
  10666. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10667. "application/octet-stream");
  10668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10669. // Server must reject oversized decompressed payloads with 413.
  10670. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10671. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10672. EXPECT_LE(total, LIMIT);
  10673. }
  10674. #ifndef CPPHTTPLIB_SSL_ENABLED
  10675. // For a request with neither Content-Length nor Transfer-Encoding, the
  10676. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10677. // compressed wire bytes straight to the ContentReader without ever routing
  10678. // them through the decompressor, so payload_max_length_ only bounded the
  10679. // compressed size on the wire, not the decompressed size.
  10680. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10681. Server svr;
  10682. const size_t LIMIT = 64 * 1024; // 64KB
  10683. svr.set_payload_max_length(LIMIT);
  10684. size_t total = 0;
  10685. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10686. const ContentReader &content_reader) {
  10687. content_reader([&](const char * /*data*/, size_t len) {
  10688. total += len;
  10689. return true;
  10690. });
  10691. res.status = 200;
  10692. res.set_content("stream_ok", "text/plain");
  10693. });
  10694. auto port = svr.bind_to_any_port(HOST);
  10695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10696. auto se = detail::scope_exit([&] {
  10697. svr.stop();
  10698. thread.join();
  10699. ASSERT_FALSE(svr.is_running());
  10700. });
  10701. svr.wait_until_ready();
  10702. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10703. // StreamingGzipDecompression test above.
  10704. std::string raw(256 * 1024, 'A');
  10705. std::string gz;
  10706. {
  10707. httplib::detail::gzip_compressor compressor;
  10708. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10709. [&](const char *chunk, size_t len) {
  10710. gz.append(chunk, len);
  10711. return true;
  10712. });
  10713. ASSERT_TRUE(result);
  10714. }
  10715. // Send the gzip body over raw TCP with neither Content-Length nor
  10716. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10717. // kicks in.
  10718. std::string req = "POST /stream HTTP/1.1\r\n"
  10719. "Host: " +
  10720. std::string(HOST) + ":" + std::to_string(port) +
  10721. "\r\n"
  10722. "Content-Encoding: gzip\r\n"
  10723. "Connection: close\r\n"
  10724. "\r\n" +
  10725. gz;
  10726. std::string response;
  10727. ASSERT_TRUE(send_request(5, req, &response, port));
  10728. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10729. EXPECT_LE(total, LIMIT);
  10730. }
  10731. #endif
  10732. #endif
  10733. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10734. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10735. // the payload must be passed through untouched instead of being rejected.
  10736. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10737. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10738. Server svr;
  10739. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10740. res.set_content(body, "image/jpeg");
  10741. res.set_header("Content-Encoding", "UTF-8");
  10742. });
  10743. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content(body, "image/jpeg");
  10745. res.set_header("Content-Encoding", "identity");
  10746. });
  10747. svr.Post("/echo", [](const Request &req, Response &res) {
  10748. res.set_content(req.body, "image/jpeg");
  10749. });
  10750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10751. auto se = detail::scope_exit([&] {
  10752. svr.stop();
  10753. t.join();
  10754. ASSERT_FALSE(svr.is_running());
  10755. });
  10756. svr.wait_until_ready();
  10757. Client cli(HOST, PORT);
  10758. {
  10759. auto res = cli.Get("/image");
  10760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10761. EXPECT_EQ(StatusCode::OK_200, res->status);
  10762. EXPECT_EQ(body, res->body);
  10763. }
  10764. {
  10765. auto res = cli.Get("/identity");
  10766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10767. EXPECT_EQ(StatusCode::OK_200, res->status);
  10768. EXPECT_EQ(body, res->body);
  10769. }
  10770. {
  10771. // The same applies to a request body reaching the server.
  10772. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10773. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10775. EXPECT_EQ(StatusCode::OK_200, res->status);
  10776. EXPECT_EQ(body, res->body);
  10777. }
  10778. }
  10779. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10780. // gzip-encoded response even when the build has no zlib support.
  10781. static const char GZIPPED_HELLO_WORLD[] = {
  10782. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10783. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10784. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10785. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10786. // A content coding is a whole token, not something the field value merely
  10787. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10788. // as "fibre" look like Brotli, and turned a multi-coding value like
  10789. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10790. // it was never meant to see.
  10791. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10792. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10793. Server svr;
  10794. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10795. res.set_content(body, "image/jpeg");
  10796. res.set_header("Content-Encoding", "fibre");
  10797. });
  10798. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10799. res.set_content(body, "image/jpeg");
  10800. res.set_header("Content-Encoding", "gzip, br");
  10801. });
  10802. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10803. res.set_content(body, "image/jpeg");
  10804. res.set_header("Content-Encoding", "x-zstd-ish");
  10805. });
  10806. auto port = svr.bind_to_any_port(HOST);
  10807. thread t = thread([&]() { svr.listen_after_bind(); });
  10808. auto se = detail::scope_exit([&] {
  10809. svr.stop();
  10810. t.join();
  10811. ASSERT_FALSE(svr.is_running());
  10812. });
  10813. svr.wait_until_ready();
  10814. Client cli(HOST, port);
  10815. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10816. auto res = cli.Get(path);
  10817. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10818. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10819. // Not a coding we recognize, so the payload comes back untouched
  10820. EXPECT_EQ(body, res->body) << path;
  10821. }
  10822. }
  10823. // A content coding cpp-httplib recognizes but was not built with must be
  10824. // reported as such. Handing the still-compressed payload back to the caller
  10825. // would silently corrupt it.
  10826. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10827. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10828. Server svr;
  10829. // "image/jpeg" keeps the server from applying a content coding of its own,
  10830. // so the hand-crafted Content-Encoding below survives.
  10831. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10832. res.set_content(gzipped, "image/jpeg");
  10833. res.set_header("Content-Encoding", "gzip");
  10834. });
  10835. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10836. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10837. res.set_content(gzipped, "image/jpeg");
  10838. res.set_header("Content-Encoding", "GZIP");
  10839. });
  10840. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10841. auto se = detail::scope_exit([&] {
  10842. svr.stop();
  10843. t.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. });
  10846. svr.wait_until_ready();
  10847. Client cli(HOST, PORT);
  10848. {
  10849. auto res = cli.Get("/gzipped");
  10850. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10852. EXPECT_EQ("Hello World!", res->body);
  10853. #else
  10854. ASSERT_FALSE(res);
  10855. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10856. #endif
  10857. }
  10858. {
  10859. // open_stream() must behave the same way.
  10860. auto handle = cli.open_stream("GET", "/gzipped");
  10861. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10862. ASSERT_TRUE(handle.is_valid());
  10863. std::string received;
  10864. char buf[256];
  10865. ssize_t n;
  10866. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10867. received.append(buf, static_cast<size_t>(n));
  10868. }
  10869. EXPECT_EQ("Hello World!", received);
  10870. #else
  10871. EXPECT_FALSE(handle.is_valid());
  10872. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10873. #endif
  10874. }
  10875. {
  10876. // A differently-cased coding must not be mistaken for an unknown one, or
  10877. // the body would be handed back still compressed.
  10878. auto res = cli.Get("/gzipped-uppercase");
  10879. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. EXPECT_EQ("Hello World!", res->body);
  10882. #else
  10883. ASSERT_FALSE(res);
  10884. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10885. #endif
  10886. }
  10887. }
  10888. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10889. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10890. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10891. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10892. // body a second time and appending a second Content-Encoding field line, so
  10893. // clients that decode one coding per listed value handed back raw gzip bytes.
  10894. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10895. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10896. Server svr;
  10897. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10898. // keeps the server from applying a coding of its own.
  10899. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10900. res.set_content(gzipped, "text/plain");
  10901. res.set_header("Content-Encoding", "gzip");
  10902. });
  10903. auto port = svr.bind_to_any_port(HOST);
  10904. thread t = thread([&]() { svr.listen_after_bind(); });
  10905. auto se = detail::scope_exit([&] {
  10906. svr.stop();
  10907. t.join();
  10908. ASSERT_FALSE(svr.is_running());
  10909. });
  10910. svr.wait_until_ready();
  10911. Client cli(HOST, port);
  10912. Headers headers = {{"Accept-Encoding", "gzip"}};
  10913. auto res = cli.Get("/pre-gzipped", headers);
  10914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10915. EXPECT_EQ(StatusCode::OK_200, res->status);
  10916. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10917. EXPECT_EQ("Hello World!", res->body);
  10918. }
  10919. // A chunked provider settles its coding where the headers are written and
  10920. // reuses it at write time. Both ends of that have to hold: a handler's own
  10921. // Content-Encoding suppresses the coding, and a response without one is still
  10922. // compressed as it always was.
  10923. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10924. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10925. const std::string plain = "Hello World! Hello World! Hello World!";
  10926. Server svr;
  10927. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10928. res.set_header("Content-Encoding", "gzip");
  10929. res.set_chunked_content_provider(
  10930. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10931. sink.write(gzipped.data(), gzipped.size());
  10932. sink.done();
  10933. return true;
  10934. });
  10935. });
  10936. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10937. res.set_chunked_content_provider(
  10938. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10939. sink.write(plain.data(), plain.size());
  10940. sink.done();
  10941. return true;
  10942. });
  10943. });
  10944. auto port = svr.bind_to_any_port(HOST);
  10945. thread t = thread([&]() { svr.listen_after_bind(); });
  10946. auto se = detail::scope_exit([&] {
  10947. svr.stop();
  10948. t.join();
  10949. ASSERT_FALSE(svr.is_running());
  10950. });
  10951. svr.wait_until_ready();
  10952. Client cli(HOST, port);
  10953. Headers headers = {{"Accept-Encoding", "gzip"}};
  10954. {
  10955. auto res = cli.Get("/pre-gzipped", headers);
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ(StatusCode::OK_200, res->status);
  10958. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10959. EXPECT_EQ("Hello World!", res->body);
  10960. }
  10961. {
  10962. auto res = cli.Get("/negotiated", headers);
  10963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10964. EXPECT_EQ(StatusCode::OK_200, res->status);
  10965. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10966. EXPECT_EQ(plain, res->body);
  10967. }
  10968. }
  10969. #endif
  10970. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10971. // the same message as the comma-joined one, so both have to be read the same
  10972. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10973. // single gzip coding, and a body the sender says was encoded twice was handed
  10974. // back after one pass, still compressed but presented as decoded.
  10975. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10976. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10977. Server svr;
  10978. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10979. res.set_content(body, "image/jpeg");
  10980. res.headers.emplace("Content-Encoding", "gzip");
  10981. res.headers.emplace("Content-Encoding", "gzip");
  10982. });
  10983. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10984. res.set_content(body, "image/jpeg");
  10985. res.set_header("Content-Encoding", "gzip, gzip");
  10986. });
  10987. auto port = svr.bind_to_any_port(HOST);
  10988. thread t = thread([&]() { svr.listen_after_bind(); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. t.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. Client cli(HOST, port);
  10996. // Two codings is not something cpp-httplib decodes, so both representations
  10997. // take the pass-through path rather than one of them being gunzipped once.
  10998. for (const char *path : {"/split", "/joined"}) {
  10999. auto res = cli.Get(path);
  11000. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11001. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11002. EXPECT_EQ(body, res->body) << path;
  11003. }
  11004. }
  11005. // Regression test for DoS vulnerability: a malicious server sending a response
  11006. // without Content-Length header must not cause unbounded memory consumption on
  11007. // the client side. The client should stop reading after a reasonable limit,
  11008. // similar to the server-side set_payload_max_length protection.
  11009. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11010. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11011. #ifndef _WIN32
  11012. signal(SIGPIPE, SIG_IGN);
  11013. #endif
  11014. auto server_thread = std::thread([] {
  11015. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11016. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11017. default_socket_options(srv);
  11018. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11019. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11020. sockaddr_in addr{};
  11021. addr.sin_family = AF_INET;
  11022. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11023. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11024. int opt = 1;
  11025. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11026. #ifdef _WIN32
  11027. reinterpret_cast<const char *>(&opt),
  11028. #else
  11029. &opt,
  11030. #endif
  11031. sizeof(opt));
  11032. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11033. ::listen(srv, 1);
  11034. sockaddr_in cli_addr{};
  11035. socklen_t cli_len = sizeof(cli_addr);
  11036. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11037. if (cli != INVALID_SOCKET) {
  11038. char buf[4096];
  11039. ::recv(cli, buf, sizeof(buf), 0);
  11040. // Malicious response: no Content-Length, no chunked encoding
  11041. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11042. "Connection: close\r\n"
  11043. "\r\n";
  11044. ::send(cli,
  11045. #ifdef _WIN32
  11046. static_cast<const char *>(response_header.c_str()),
  11047. static_cast<int>(response_header.size()),
  11048. #else
  11049. response_header.c_str(), response_header.size(),
  11050. #endif
  11051. 0);
  11052. // Send 10MB of data
  11053. std::string chunk(64 * 1024, 'A');
  11054. size_t total_sent = 0;
  11055. while (total_sent < MALICIOUS_DATA_SIZE) {
  11056. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11057. auto sent = ::send(cli,
  11058. #ifdef _WIN32
  11059. static_cast<const char *>(chunk.c_str()),
  11060. static_cast<int>(to_send),
  11061. #else
  11062. chunk.c_str(), to_send,
  11063. #endif
  11064. 0);
  11065. if (sent <= 0) break;
  11066. total_sent += static_cast<size_t>(sent);
  11067. }
  11068. detail::close_socket(cli);
  11069. }
  11070. detail::close_socket(srv);
  11071. });
  11072. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11073. size_t total_read = 0;
  11074. {
  11075. Client cli("127.0.0.1", PORT + 2);
  11076. cli.set_read_timeout(5, 0);
  11077. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11078. auto stream = cli.open_stream("GET", "/malicious");
  11079. ASSERT_TRUE(stream.is_valid());
  11080. char buffer[64 * 1024];
  11081. ssize_t n;
  11082. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11083. total_read += static_cast<size_t>(n);
  11084. }
  11085. } // StreamHandle and Client destroyed here, closing the socket
  11086. server_thread.join();
  11087. // With set_payload_max_length, the client must stop reading before consuming
  11088. // all 10MB. The read loop should be cut off at or near the configured limit.
  11089. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11090. << "Client read " << total_read << " bytes, exceeding the configured "
  11091. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11092. }
  11093. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11094. // the entire response body without truncation.
  11095. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11096. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11097. #ifndef _WIN32
  11098. signal(SIGPIPE, SIG_IGN);
  11099. #endif
  11100. auto server_thread = std::thread([] {
  11101. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11102. default_socket_options(srv);
  11103. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11104. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11105. sockaddr_in addr{};
  11106. addr.sin_family = AF_INET;
  11107. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11108. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11109. int opt = 1;
  11110. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11111. #ifdef _WIN32
  11112. reinterpret_cast<const char *>(&opt),
  11113. #else
  11114. &opt,
  11115. #endif
  11116. sizeof(opt));
  11117. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11118. ::listen(srv, 1);
  11119. sockaddr_in cli_addr{};
  11120. socklen_t cli_len = sizeof(cli_addr);
  11121. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11122. if (cli != INVALID_SOCKET) {
  11123. char buf[4096];
  11124. ::recv(cli, buf, sizeof(buf), 0);
  11125. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11126. "Connection: close\r\n"
  11127. "\r\n";
  11128. ::send(cli,
  11129. #ifdef _WIN32
  11130. static_cast<const char *>(response_header.c_str()),
  11131. static_cast<int>(response_header.size()),
  11132. #else
  11133. response_header.c_str(), response_header.size(),
  11134. #endif
  11135. 0);
  11136. std::string chunk(64 * 1024, 'A');
  11137. size_t total_sent = 0;
  11138. while (total_sent < DATA_SIZE) {
  11139. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11140. auto sent = ::send(cli,
  11141. #ifdef _WIN32
  11142. static_cast<const char *>(chunk.c_str()),
  11143. static_cast<int>(to_send),
  11144. #else
  11145. chunk.c_str(), to_send,
  11146. #endif
  11147. 0);
  11148. if (sent <= 0) break;
  11149. total_sent += static_cast<size_t>(sent);
  11150. }
  11151. #ifdef _WIN32
  11152. ::shutdown(cli, SD_SEND);
  11153. #else
  11154. ::shutdown(cli, SHUT_WR);
  11155. #endif
  11156. // Drain until the client closes its end, ensuring all data is delivered
  11157. char drain[1024];
  11158. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11159. detail::close_socket(cli);
  11160. }
  11161. detail::close_socket(srv);
  11162. });
  11163. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11164. size_t total_read = 0;
  11165. {
  11166. Client cli("127.0.0.1", PORT + 2);
  11167. cli.set_read_timeout(5, 0);
  11168. cli.set_payload_max_length(0); // 0 means no limit
  11169. auto stream = cli.open_stream("GET", "/data");
  11170. ASSERT_TRUE(stream.is_valid());
  11171. char buffer[64 * 1024];
  11172. ssize_t n;
  11173. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11174. total_read += static_cast<size_t>(n);
  11175. }
  11176. }
  11177. server_thread.join();
  11178. EXPECT_EQ(total_read, DATA_SIZE)
  11179. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11180. << " bytes without truncation, but only read " << total_read << " bytes.";
  11181. }
  11182. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11183. // enormous Content-Length must not cause the client to pre-allocate a huge
  11184. // response body buffer. The reservation is capped at payload_max_length_, and
  11185. // the read itself fails when the body exceeds the limit.
  11186. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11187. #ifndef _WIN32
  11188. signal(SIGPIPE, SIG_IGN);
  11189. #endif
  11190. auto server_thread = std::thread([] {
  11191. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11192. default_socket_options(srv);
  11193. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11195. sockaddr_in addr{};
  11196. addr.sin_family = AF_INET;
  11197. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11198. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11199. int opt = 1;
  11200. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11201. #ifdef _WIN32
  11202. reinterpret_cast<const char *>(&opt),
  11203. #else
  11204. &opt,
  11205. #endif
  11206. sizeof(opt));
  11207. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11208. ::listen(srv, 1);
  11209. sockaddr_in cli_addr{};
  11210. socklen_t cli_len = sizeof(cli_addr);
  11211. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11212. if (cli != INVALID_SOCKET) {
  11213. char buf[4096];
  11214. ::recv(cli, buf, sizeof(buf), 0);
  11215. // Malicious response: claim a 20GB body but send only a tiny payload.
  11216. std::string response = "HTTP/1.1 200 OK\r\n"
  11217. "Content-Length: 20000000000\r\n"
  11218. "\r\n"
  11219. "abc";
  11220. ::send(cli,
  11221. #ifdef _WIN32
  11222. static_cast<const char *>(response.c_str()),
  11223. static_cast<int>(response.size()),
  11224. #else
  11225. response.c_str(), response.size(),
  11226. #endif
  11227. 0);
  11228. detail::close_socket(cli);
  11229. }
  11230. detail::close_socket(srv);
  11231. });
  11232. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11233. {
  11234. Client cli("127.0.0.1", PORT + 2);
  11235. cli.set_read_timeout(5, 0);
  11236. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11237. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11238. // (server claims more bytes than payload_max_length permits), but it must
  11239. // not exhaust memory before getting there.
  11240. auto res = cli.Get("/malicious");
  11241. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11242. }
  11243. server_thread.join();
  11244. }
  11245. // Verify that content_receiver bypasses the default payload_max_length,
  11246. // allowing streaming downloads larger than 100MB without requiring an explicit
  11247. // set_payload_max_length call.
  11248. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11249. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11250. #ifndef _WIN32
  11251. signal(SIGPIPE, SIG_IGN);
  11252. #endif
  11253. auto server_thread = std::thread([] {
  11254. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11255. default_socket_options(srv);
  11256. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11258. sockaddr_in addr{};
  11259. addr.sin_family = AF_INET;
  11260. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11261. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11262. int opt = 1;
  11263. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11264. #ifdef _WIN32
  11265. reinterpret_cast<const char *>(&opt),
  11266. #else
  11267. &opt,
  11268. #endif
  11269. sizeof(opt));
  11270. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11271. ::listen(srv, 1);
  11272. sockaddr_in cli_addr{};
  11273. socklen_t cli_len = sizeof(cli_addr);
  11274. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11275. if (cli != INVALID_SOCKET) {
  11276. char buf[4096];
  11277. ::recv(cli, buf, sizeof(buf), 0);
  11278. // Response with Content-Length larger than default 100MB limit
  11279. auto content_length = std::to_string(DATA_SIZE);
  11280. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11281. "Content-Length: " +
  11282. content_length +
  11283. "\r\n"
  11284. "Connection: close\r\n"
  11285. "\r\n";
  11286. ::send(cli,
  11287. #ifdef _WIN32
  11288. static_cast<const char *>(response_header.c_str()),
  11289. static_cast<int>(response_header.size()),
  11290. #else
  11291. response_header.c_str(), response_header.size(),
  11292. #endif
  11293. 0);
  11294. std::string chunk(64 * 1024, 'A');
  11295. size_t total_sent = 0;
  11296. while (total_sent < DATA_SIZE) {
  11297. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11298. auto sent = ::send(cli,
  11299. #ifdef _WIN32
  11300. static_cast<const char *>(chunk.c_str()),
  11301. static_cast<int>(to_send),
  11302. #else
  11303. chunk.c_str(), to_send,
  11304. #endif
  11305. 0);
  11306. if (sent <= 0) break;
  11307. total_sent += static_cast<size_t>(sent);
  11308. }
  11309. detail::close_socket(cli);
  11310. }
  11311. detail::close_socket(srv);
  11312. });
  11313. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11314. size_t total_received = 0;
  11315. {
  11316. Client cli("127.0.0.1", PORT + 2);
  11317. cli.set_read_timeout(10, 0);
  11318. // Do NOT call set_payload_max_length — use the default 100MB limit
  11319. auto res =
  11320. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11321. total_received += data_length;
  11322. return true;
  11323. });
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_EQ(StatusCode::OK_200, res->status);
  11326. }
  11327. server_thread.join();
  11328. EXPECT_EQ(total_received, DATA_SIZE)
  11329. << "With content_receiver, the client should read all " << DATA_SIZE
  11330. << " bytes despite the default 100MB payload_max_length, but only read "
  11331. << total_received << " bytes.";
  11332. }
  11333. // Verify that an explicit set_payload_max_length smaller than the response is
  11334. // enforced even when a content_receiver is used.
  11335. TEST(ClientVulnerabilityTest,
  11336. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11337. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11338. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11339. #ifndef _WIN32
  11340. signal(SIGPIPE, SIG_IGN);
  11341. #endif
  11342. auto server_thread = std::thread([] {
  11343. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11344. default_socket_options(srv);
  11345. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11346. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11347. sockaddr_in addr{};
  11348. addr.sin_family = AF_INET;
  11349. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11350. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11351. int opt = 1;
  11352. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11353. #ifdef _WIN32
  11354. reinterpret_cast<const char *>(&opt),
  11355. #else
  11356. &opt,
  11357. #endif
  11358. sizeof(opt));
  11359. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11360. ::listen(srv, 1);
  11361. sockaddr_in cli_addr{};
  11362. socklen_t cli_len = sizeof(cli_addr);
  11363. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11364. if (cli != INVALID_SOCKET) {
  11365. char buf[4096];
  11366. ::recv(cli, buf, sizeof(buf), 0);
  11367. auto content_length = std::to_string(DATA_SIZE);
  11368. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11369. "Content-Length: " +
  11370. content_length +
  11371. "\r\n"
  11372. "Connection: close\r\n"
  11373. "\r\n";
  11374. ::send(cli,
  11375. #ifdef _WIN32
  11376. static_cast<const char *>(response_header.c_str()),
  11377. static_cast<int>(response_header.size()),
  11378. #else
  11379. response_header.c_str(), response_header.size(),
  11380. #endif
  11381. 0);
  11382. std::string chunk(64 * 1024, 'A');
  11383. size_t total_sent = 0;
  11384. while (total_sent < DATA_SIZE) {
  11385. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11386. auto sent = ::send(cli,
  11387. #ifdef _WIN32
  11388. static_cast<const char *>(chunk.c_str()),
  11389. static_cast<int>(to_send),
  11390. #else
  11391. chunk.c_str(), to_send,
  11392. #endif
  11393. 0);
  11394. if (sent <= 0) break;
  11395. total_sent += static_cast<size_t>(sent);
  11396. }
  11397. detail::close_socket(cli);
  11398. }
  11399. detail::close_socket(srv);
  11400. });
  11401. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11402. size_t total_received = 0;
  11403. {
  11404. Client cli("127.0.0.1", PORT + 2);
  11405. cli.set_read_timeout(10, 0);
  11406. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11407. auto res =
  11408. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11409. total_received += data_length;
  11410. return true;
  11411. });
  11412. // Should fail because 200MB exceeds the explicit 150MB limit
  11413. EXPECT_FALSE(res);
  11414. }
  11415. server_thread.join();
  11416. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11417. << "Client with content_receiver should respect the explicit "
  11418. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11419. << total_received << " bytes.";
  11420. }
  11421. // Verify that an explicit set_payload_max_length larger than the response
  11422. // allows the content_receiver to read all data successfully.
  11423. TEST(ClientVulnerabilityTest,
  11424. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11425. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11426. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11427. #ifndef _WIN32
  11428. signal(SIGPIPE, SIG_IGN);
  11429. #endif
  11430. auto server_thread = std::thread([] {
  11431. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11432. default_socket_options(srv);
  11433. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11434. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11435. sockaddr_in addr{};
  11436. addr.sin_family = AF_INET;
  11437. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11438. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11439. int opt = 1;
  11440. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11441. #ifdef _WIN32
  11442. reinterpret_cast<const char *>(&opt),
  11443. #else
  11444. &opt,
  11445. #endif
  11446. sizeof(opt));
  11447. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11448. ::listen(srv, 1);
  11449. sockaddr_in cli_addr{};
  11450. socklen_t cli_len = sizeof(cli_addr);
  11451. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11452. if (cli != INVALID_SOCKET) {
  11453. char buf[4096];
  11454. ::recv(cli, buf, sizeof(buf), 0);
  11455. auto content_length = std::to_string(DATA_SIZE);
  11456. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11457. "Content-Length: " +
  11458. content_length +
  11459. "\r\n"
  11460. "Connection: close\r\n"
  11461. "\r\n";
  11462. ::send(cli,
  11463. #ifdef _WIN32
  11464. static_cast<const char *>(response_header.c_str()),
  11465. static_cast<int>(response_header.size()),
  11466. #else
  11467. response_header.c_str(), response_header.size(),
  11468. #endif
  11469. 0);
  11470. std::string chunk(64 * 1024, 'A');
  11471. size_t total_sent = 0;
  11472. while (total_sent < DATA_SIZE) {
  11473. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11474. auto sent = ::send(cli,
  11475. #ifdef _WIN32
  11476. static_cast<const char *>(chunk.c_str()),
  11477. static_cast<int>(to_send),
  11478. #else
  11479. chunk.c_str(), to_send,
  11480. #endif
  11481. 0);
  11482. if (sent <= 0) break;
  11483. total_sent += static_cast<size_t>(sent);
  11484. }
  11485. #ifdef _WIN32
  11486. ::shutdown(cli, SD_SEND);
  11487. #else
  11488. ::shutdown(cli, SHUT_WR);
  11489. #endif
  11490. char drain[1024];
  11491. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11492. detail::close_socket(cli);
  11493. }
  11494. detail::close_socket(srv);
  11495. });
  11496. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11497. size_t total_received = 0;
  11498. {
  11499. Client cli("127.0.0.1", PORT + 2);
  11500. cli.set_read_timeout(10, 0);
  11501. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11502. auto res =
  11503. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11504. total_received += data_length;
  11505. return true;
  11506. });
  11507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11508. EXPECT_EQ(StatusCode::OK_200, res->status);
  11509. }
  11510. server_thread.join();
  11511. EXPECT_EQ(total_received, DATA_SIZE)
  11512. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11513. << " bytes (larger than " << DATA_SIZE
  11514. << " bytes response), content_receiver should read all data, but only "
  11515. "read "
  11516. << total_received << " bytes.";
  11517. }
  11518. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11519. // Regression test for "zip bomb" attack on the client side: a malicious server
  11520. // sends a small gzip-compressed response that decompresses to a huge payload.
  11521. // The client must enforce payload_max_length on the decompressed size.
  11522. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11523. constexpr size_t DECOMPRESSED_SIZE =
  11524. 10 * 1024 * 1024; // 10MB after decompression
  11525. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11526. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11527. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11528. std::string compressed;
  11529. {
  11530. httplib::detail::gzip_compressor compressor;
  11531. bool ok =
  11532. compressor.compress(uncompressed.data(), uncompressed.size(),
  11533. /*last=*/true, [&](const char *buf, size_t len) {
  11534. compressed.append(buf, len);
  11535. return true;
  11536. });
  11537. ASSERT_TRUE(ok);
  11538. }
  11539. // Sanity: compressed data should be much smaller than the decompressed size
  11540. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11541. #ifndef _WIN32
  11542. signal(SIGPIPE, SIG_IGN);
  11543. #endif
  11544. // Set up the listening socket in the main thread so the server is guaranteed
  11545. // to be ready before the client connects (eliminates race condition).
  11546. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11547. default_socket_options(srv);
  11548. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11550. sockaddr_in addr{};
  11551. addr.sin_family = AF_INET;
  11552. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11553. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11554. int opt = 1;
  11555. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11556. #ifdef _WIN32
  11557. reinterpret_cast<const char *>(&opt),
  11558. #else
  11559. &opt,
  11560. #endif
  11561. sizeof(opt));
  11562. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11563. ASSERT_EQ(0, ::listen(srv, 1));
  11564. auto server_thread = std::thread([&compressed, srv] {
  11565. sockaddr_in cli_addr{};
  11566. socklen_t cli_len = sizeof(cli_addr);
  11567. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11568. if (cli != INVALID_SOCKET) {
  11569. // Read the full HTTP request (until \r\n\r\n)
  11570. char buf[4096];
  11571. size_t total = 0;
  11572. while (total < sizeof(buf)) {
  11573. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11574. if (n <= 0) break;
  11575. total += static_cast<size_t>(n);
  11576. // Check for end of headers
  11577. if (total >= 4) {
  11578. std::string req(buf, total);
  11579. if (req.find("\r\n\r\n") != std::string::npos) break;
  11580. }
  11581. }
  11582. // Malicious response: gzip-compressed body, no Content-Length
  11583. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11584. "Content-Encoding: gzip\r\n"
  11585. "Connection: close\r\n"
  11586. "\r\n";
  11587. ::send(cli,
  11588. #ifdef _WIN32
  11589. static_cast<const char *>(response_header.c_str()),
  11590. static_cast<int>(response_header.size()),
  11591. #else
  11592. response_header.c_str(), response_header.size(),
  11593. #endif
  11594. 0);
  11595. // Send the compressed payload (small on the wire, huge when decompressed)
  11596. size_t total_sent = 0;
  11597. while (total_sent < compressed.size()) {
  11598. auto to_send = std::min(compressed.size() - total_sent,
  11599. static_cast<size_t>(64 * 1024));
  11600. auto sent =
  11601. ::send(cli,
  11602. #ifdef _WIN32
  11603. static_cast<const char *>(compressed.c_str() + total_sent),
  11604. static_cast<int>(to_send),
  11605. #else
  11606. compressed.c_str() + total_sent, to_send,
  11607. #endif
  11608. 0);
  11609. if (sent <= 0) break;
  11610. total_sent += static_cast<size_t>(sent);
  11611. }
  11612. detail::close_socket(cli);
  11613. }
  11614. });
  11615. auto se = detail::scope_exit([&] {
  11616. detail::close_socket(srv);
  11617. server_thread.join();
  11618. });
  11619. size_t total_decompressed = 0;
  11620. {
  11621. Client cli("127.0.0.1", PORT + 3);
  11622. cli.set_read_timeout(5, 0);
  11623. cli.set_decompress(true);
  11624. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11625. auto stream = cli.open_stream("GET", "/zipbomb");
  11626. ASSERT_TRUE(stream.is_valid());
  11627. char buffer[64 * 1024];
  11628. ssize_t n;
  11629. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11630. total_decompressed += static_cast<size_t>(n);
  11631. }
  11632. }
  11633. // The decompressed size must be capped by payload_max_length. Without
  11634. // protection, the client would decompress the full 10MB from a tiny
  11635. // compressed payload, enabling a zip bomb DoS attack.
  11636. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11637. << "Client decompressed " << total_decompressed
  11638. << " bytes from a gzip response. The decompressed size should be "
  11639. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11640. }
  11641. #endif
  11642. TEST(HostAndPortPropertiesTest, NoSSL) {
  11643. httplib::Client cli("www.google.com", 1234);
  11644. ASSERT_EQ("www.google.com", cli.host());
  11645. ASSERT_EQ(1234, cli.port());
  11646. }
  11647. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11648. httplib::Client cli("www.google.com:1234");
  11649. ASSERT_EQ("www.google.com", cli.host());
  11650. ASSERT_EQ(1234, cli.port());
  11651. }
  11652. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11653. // Port number that overflows int — should not crash, client becomes invalid
  11654. httplib::Client cli("http://www.google.com:99999999999999999999");
  11655. ASSERT_FALSE(cli.is_valid());
  11656. }
  11657. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11658. // Port 99999 exceeds valid range (1-65535) — should not crash
  11659. httplib::Client cli("http://www.google.com:99999");
  11660. ASSERT_FALSE(cli.is_valid());
  11661. }
  11662. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11663. httplib::Client cli("http://www.google.com:80abc");
  11664. ASSERT_FALSE(cli.is_valid());
  11665. }
  11666. #ifdef CPPHTTPLIB_SSL_ENABLED
  11667. TEST(HostAndPortPropertiesTest, SSL) {
  11668. httplib::SSLClient cli("www.google.com");
  11669. ASSERT_EQ("www.google.com", cli.host());
  11670. ASSERT_EQ(443, cli.port());
  11671. }
  11672. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11673. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11674. std::string cert;
  11675. read_file(CA_CERT_FILE, cert);
  11676. httplib::SSLClient httplib_client("www.google.com");
  11677. // Load CA store first time
  11678. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11679. // Load CA store second time (update)
  11680. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11681. // Verify client is still valid and can make connections
  11682. httplib_client.enable_server_certificate_verification(true);
  11683. auto res = httplib_client.Get("/");
  11684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11685. // Google may return 200 or 301 depending on various factors
  11686. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11687. res->status == StatusCode::MovedPermanently_301);
  11688. }
  11689. TEST(SSLClientTest, ServerNameIndication_Online) {
  11690. auto host = "httpbingo.org";
  11691. auto path = std::string{"/get"};
  11692. SSLClient cli(host, 443);
  11693. auto res = cli.Get(path);
  11694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11695. ASSERT_EQ(StatusCode::OK_200, res->status);
  11696. }
  11697. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11698. // Use a site that will cause SSL verification failure due to self-signed cert
  11699. SSLClient cli("self-signed.badssl.com", 443);
  11700. cli.enable_server_certificate_verification(true);
  11701. auto res = cli.Get("/");
  11702. ASSERT_TRUE(!res);
  11703. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11704. // Verify backend error is captured for SSLServerVerification
  11705. // This occurs when certificate verification fails
  11706. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11707. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11708. EXPECT_NE(0UL, res.ssl_backend_error());
  11709. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11710. // For OpenSSL, ssl_error is 0 for verification errors
  11711. EXPECT_EQ(0, res.ssl_error());
  11712. #if !defined(_WIN32) || \
  11713. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11714. // On non-Windows or when Windows Schannel is disabled, the error comes
  11715. // from OpenSSL's verification
  11716. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11717. res.ssl_backend_error());
  11718. #endif
  11719. #endif
  11720. }
  11721. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11722. // Use a site where hostname doesn't match the certificate
  11723. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11724. SSLClient cli("wrong.host.badssl.com", 443);
  11725. cli.enable_server_certificate_verification(true);
  11726. cli.enable_server_hostname_verification(true);
  11727. auto res = cli.Get("/");
  11728. ASSERT_TRUE(!res);
  11729. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11730. // Verify backend error is captured for hostname verification failure
  11731. EXPECT_NE(0UL, res.ssl_backend_error());
  11732. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11733. // For OpenSSL, ssl_error is 0 for verification errors
  11734. EXPECT_EQ(0, res.ssl_error());
  11735. #if !defined(_WIN32) || \
  11736. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11737. // On non-Windows or when Windows Schannel is disabled, the error comes
  11738. // from OpenSSL's hostname verification
  11739. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11740. res.ssl_backend_error());
  11741. #endif
  11742. #endif
  11743. }
  11744. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11745. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11746. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11747. SSLClient cli("www.google.com", 443);
  11748. cli.enable_server_certificate_verification(true);
  11749. auto res = cli.Get("/");
  11750. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11751. }
  11752. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11753. SSLClient cli("www.google.com", 443);
  11754. cli.enable_server_certificate_verification(true);
  11755. cli.enable_windows_certificate_verification(false);
  11756. auto res = cli.Get("/");
  11757. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11758. }
  11759. // The server sends an intermediate cross-signed by a root Windows trusts,
  11760. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11761. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11762. SSLClient cli("accounts.spotify.com", 443);
  11763. auto res = cli.Get("/");
  11764. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11765. << " ssl_backend_error=" << res.ssl_backend_error();
  11766. }
  11767. // Windows, not the backend, decides on the chain: the error carries a
  11768. // CryptoAPI trust status, which no backend error for a self-signed
  11769. // certificate has.
  11770. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11771. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11772. ASSERT_TRUE(svr.is_valid());
  11773. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11774. auto se = detail::scope_exit([&] {
  11775. svr.stop();
  11776. t.join();
  11777. ASSERT_FALSE(svr.is_running());
  11778. });
  11779. svr.wait_until_ready();
  11780. SSLClient cli("127.0.0.1", PORT);
  11781. cli.set_connection_timeout(30);
  11782. auto res = cli.Get("/");
  11783. ASSERT_FALSE(res);
  11784. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11785. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11786. << "ssl_backend_error=" << res.ssl_backend_error();
  11787. }
  11788. #endif
  11789. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11790. Client cli("https://google.com");
  11791. auto res = cli.Get("/");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11794. }
  11795. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11796. SSLClient cli("google.com");
  11797. cli.set_ca_cert_path(CA_CERT_FILE);
  11798. auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11801. }
  11802. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11803. SSLClient cli("google.com");
  11804. cli.enable_server_certificate_verification(true);
  11805. cli.set_ca_cert_path("hello");
  11806. auto res = cli.Get("/");
  11807. ASSERT_TRUE(!res);
  11808. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11809. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11810. // should be set
  11811. EXPECT_EQ(0, res.ssl_error());
  11812. // Verify backend error is captured for SSLLoadingCerts
  11813. // This error occurs when loading CA certificates fails
  11814. EXPECT_NE(0UL, res.ssl_backend_error());
  11815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11816. // OpenSSL specific error codes:
  11817. // > openssl errstr 0x80000002
  11818. // error:80000002:system library::No such file or directory
  11819. // > openssl errstr 0xA000126
  11820. // error:0A000126:SSL routines::unexpected eof while reading
  11821. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11822. res.ssl_backend_error() == 0xA000126);
  11823. #endif
  11824. }
  11825. TEST(SSLClientTest, ServerCertificateVerification4) {
  11826. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11827. ASSERT_TRUE(svr.is_valid());
  11828. svr.Get("/test", [&](const Request &, Response &res) {
  11829. res.set_content("test", "text/plain");
  11830. svr.stop();
  11831. ASSERT_TRUE(true);
  11832. });
  11833. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11834. auto se = detail::scope_exit([&] {
  11835. t.join();
  11836. ASSERT_FALSE(svr.is_running());
  11837. });
  11838. svr.wait_until_ready();
  11839. SSLClient cli("127.0.0.1", PORT);
  11840. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11841. cli.enable_server_certificate_verification(true);
  11842. cli.set_connection_timeout(30);
  11843. auto res = cli.Get("/test");
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. ASSERT_EQ(StatusCode::OK_200, res->status);
  11846. }
  11847. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11848. std::string cert;
  11849. read_file(CA_CERT_FILE, cert);
  11850. SSLClient cli("google.com");
  11851. cli.load_ca_cert_store(cert.data(), cert.size());
  11852. const auto res = cli.Get("/");
  11853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11854. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11855. }
  11856. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11857. // clang-format off
  11858. static constexpr char cert[] =
  11859. "GlobalSign Root CA\n"
  11860. "==================\n"
  11861. "-----BEGIN CERTIFICATE-----\n"
  11862. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11863. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11864. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11865. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11866. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11867. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11868. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11869. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11870. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11871. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11872. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11873. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11874. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11875. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11876. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11877. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11878. "-----END CERTIFICATE-----\n";
  11879. // clang-format on
  11880. SSLClient cli("google.com");
  11881. cli.load_ca_cert_store(cert, sizeof(cert));
  11882. const auto res = cli.Get("/");
  11883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11884. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11885. }
  11886. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11887. SSLClient cli("www.youtube.com");
  11888. cli.set_ca_cert_path(CA_CERT_FILE);
  11889. cli.enable_server_certificate_verification(true);
  11890. cli.set_follow_location(true);
  11891. auto res = cli.Get("/");
  11892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11893. ASSERT_EQ(StatusCode::OK_200, res->status);
  11894. }
  11895. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11896. SSLClient cli("wWw.YouTube.Com");
  11897. cli.set_ca_cert_path(CA_CERT_FILE);
  11898. cli.enable_server_certificate_verification(true);
  11899. cli.enable_server_hostname_verification(true);
  11900. cli.set_follow_location(true);
  11901. auto res = cli.Get("/");
  11902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11903. ASSERT_EQ(StatusCode::OK_200, res->status);
  11904. }
  11905. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11906. SSLClient cli("gOoGlE.COm");
  11907. cli.enable_server_certificate_verification(true);
  11908. cli.enable_server_hostname_verification(true);
  11909. cli.set_follow_location(true);
  11910. auto res = cli.Get("/");
  11911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11912. ASSERT_EQ(StatusCode::OK_200, res->status);
  11913. }
  11914. TEST(SSLClientTest, Issue2004_Online) {
  11915. Client client("https://google.com");
  11916. client.set_follow_location(true);
  11917. auto res = client.Get("/");
  11918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11919. ASSERT_EQ(StatusCode::OK_200, res->status);
  11920. auto body = res->body;
  11921. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11922. }
  11923. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11924. // Create SSLClient with invalid cert/key to make is_valid() return false
  11925. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11926. "nonexistent_key.pem");
  11927. // is_valid() should be false due to cert loading failure
  11928. ASSERT_FALSE(cli.is_valid());
  11929. auto res = cli.Get("/");
  11930. ASSERT_FALSE(res);
  11931. EXPECT_EQ(Error::SSLConnection, res.error());
  11932. }
  11933. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11934. // Test for Issue #2251: SSL error not properly reported when client cert
  11935. // and key paths are swapped or mismatched
  11936. // This simulates the scenario where user accidentally swaps the cert and key
  11937. // files
  11938. // Using client cert file as private key and vice versa (completely wrong)
  11939. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11940. // Should fail validation due to cert/key mismatch
  11941. ASSERT_FALSE(cli.is_valid());
  11942. // Attempt to make a request should fail with proper error
  11943. auto res = cli.Get("/");
  11944. ASSERT_FALSE(res);
  11945. EXPECT_EQ(Error::SSLConnection, res.error());
  11946. // SSL error should be recorded in the Result object (this is the key fix for
  11947. // Issue #2251)
  11948. auto backend_error = res.ssl_backend_error();
  11949. EXPECT_NE(0u, backend_error);
  11950. }
  11951. // Tests cert/key mismatch detection at the TLS context level
  11952. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11953. // Test that using mismatched cert/key causes connection failure.
  11954. // We verify this at the SSLClient level rather than through internal
  11955. // TLS API functions.
  11956. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11957. cli.enable_server_certificate_verification(false);
  11958. cli.set_connection_timeout(2);
  11959. // The mismatch should cause a connection or handshake error
  11960. auto res = cli.Get("/test");
  11961. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11962. // Either way, the request should fail
  11963. EXPECT_FALSE(res);
  11964. }
  11965. #endif
  11966. #if 0
  11967. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11968. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11969. ASSERT_TRUE(cli != nullptr);
  11970. cli->set_address_family(AF_INET6);
  11971. cli->set_interface("en0");
  11972. auto res = cli->Get("/get");
  11973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11974. ASSERT_EQ(StatusCode::OK_200, res->status);
  11975. }
  11976. #endif
  11977. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11978. #ifdef CPPHTTPLIB_SSL_ENABLED
  11979. void ClientCertPresent(
  11980. const std::string &client_cert_file,
  11981. const std::string &client_private_key_file,
  11982. const std::string &client_encrypted_private_key_pass = std::string()) {
  11983. using namespace httplib::tls;
  11984. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11985. CLIENT_CA_CERT_DIR);
  11986. ASSERT_TRUE(svr.is_valid());
  11987. svr.Get("/test", [&](const Request &req, Response &res) {
  11988. res.set_content("test", "text/plain");
  11989. auto cert = req.peer_cert();
  11990. ASSERT_TRUE(static_cast<bool>(cert));
  11991. std::string common_name = cert.subject_cn();
  11992. EXPECT_EQ("Common Name", common_name);
  11993. });
  11994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11995. auto se = detail::scope_exit([&] {
  11996. svr.stop();
  11997. t.join();
  11998. ASSERT_FALSE(svr.is_running());
  11999. });
  12000. svr.wait_until_ready();
  12001. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12002. client_encrypted_private_key_pass);
  12003. cli.enable_server_certificate_verification(false);
  12004. cli.set_connection_timeout(30);
  12005. auto res = cli.Get("/test");
  12006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12007. ASSERT_EQ(StatusCode::OK_200, res->status);
  12008. }
  12009. TEST(SSLClientServerTest, ClientCertPresent) {
  12010. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12011. }
  12012. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12013. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12014. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12015. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12016. }
  12017. // PEM memory-based constructor tests (works with all TLS backends)
  12018. void PemMemoryClientCertPresent(
  12019. const std::string &client_cert_file,
  12020. const std::string &client_private_key_file,
  12021. const std::string &client_encrypted_private_key_pass = std::string()) {
  12022. // Read PEM files into memory
  12023. std::string server_cert_pem, server_key_pem;
  12024. std::string client_ca_pem;
  12025. std::string client_cert_pem, client_key_pem;
  12026. read_file(SERVER_CERT_FILE, server_cert_pem);
  12027. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12028. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12029. read_file(client_cert_file, client_cert_pem);
  12030. read_file(client_private_key_file, client_key_pem);
  12031. // Create server with PEM memory
  12032. SSLServer::PemMemory server_pem = {
  12033. server_cert_pem.c_str(),
  12034. server_cert_pem.size(),
  12035. server_key_pem.c_str(),
  12036. server_key_pem.size(),
  12037. client_ca_pem.c_str(),
  12038. client_ca_pem.size(),
  12039. nullptr // no password for server key
  12040. };
  12041. SSLServer svr(server_pem);
  12042. ASSERT_TRUE(svr.is_valid());
  12043. svr.Get("/test", [&](const Request &, Response &res) {
  12044. res.set_content("test", "text/plain");
  12045. });
  12046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12047. auto se = detail::scope_exit([&] {
  12048. svr.stop();
  12049. t.join();
  12050. ASSERT_FALSE(svr.is_running());
  12051. });
  12052. svr.wait_until_ready();
  12053. // Create client with PEM memory
  12054. const char *password = client_encrypted_private_key_pass.empty()
  12055. ? nullptr
  12056. : client_encrypted_private_key_pass.c_str();
  12057. SSLClient::PemMemory client_pem = {
  12058. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12059. client_key_pem.size(), password};
  12060. SSLClient cli(HOST, PORT, client_pem);
  12061. cli.enable_server_certificate_verification(false);
  12062. cli.set_connection_timeout(30);
  12063. auto res = cli.Get("/test");
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. ASSERT_EQ(StatusCode::OK_200, res->status);
  12066. }
  12067. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12068. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12069. }
  12070. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12071. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12072. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12073. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12074. }
  12075. TEST(SSLClientServerTest, ClientCertMissing) {
  12076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12077. CLIENT_CA_CERT_DIR);
  12078. ASSERT_TRUE(svr.is_valid());
  12079. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12081. auto se = detail::scope_exit([&] {
  12082. svr.stop();
  12083. t.join();
  12084. ASSERT_FALSE(svr.is_running());
  12085. });
  12086. svr.wait_until_ready();
  12087. SSLClient cli(HOST, PORT);
  12088. cli.set_connection_timeout(30);
  12089. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12090. // the chain check on Windows, so the result does not depend on the order.
  12091. cli.enable_server_hostname_verification(false);
  12092. auto res = cli.Get("/test");
  12093. ASSERT_TRUE(!res);
  12094. // When client cert is missing and server requires it, connection fails
  12095. // Error type depends on backend implementation
  12096. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12097. res.error() == Error::SSLConnection);
  12098. // Verify backend error is captured
  12099. // Note: This test may have different error codes depending on the exact
  12100. // verification failure
  12101. EXPECT_NE(0UL, res.ssl_backend_error());
  12102. }
  12103. TEST(SSLClientServerTest, TrustDirOptional) {
  12104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12105. ASSERT_TRUE(svr.is_valid());
  12106. svr.Get("/test", [&](const Request &, Response &res) {
  12107. res.set_content("test", "text/plain");
  12108. });
  12109. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12110. auto se = detail::scope_exit([&] {
  12111. svr.stop();
  12112. t.join();
  12113. ASSERT_FALSE(svr.is_running());
  12114. });
  12115. svr.wait_until_ready();
  12116. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12117. cli.enable_server_certificate_verification(false);
  12118. cli.set_connection_timeout(30);
  12119. auto res = cli.Get("/test");
  12120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12121. ASSERT_EQ(StatusCode::OK_200, res->status);
  12122. }
  12123. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12124. class NoListenSSLServer : public SSLServer {
  12125. public:
  12126. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12127. const char *client_ca_cert_file_path,
  12128. const char *client_ca_cert_dir_path = nullptr)
  12129. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12130. client_ca_cert_dir_path),
  12131. stop_(false) {}
  12132. std::atomic_bool stop_;
  12133. private:
  12134. bool process_and_close_socket(socket_t /*sock*/) override {
  12135. // Don't create SSL context
  12136. while (!stop_.load()) {
  12137. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12138. }
  12139. return true;
  12140. }
  12141. };
  12142. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12143. CLIENT_CA_CERT_FILE);
  12144. ASSERT_TRUE(svr.is_valid());
  12145. svr.Get("/test", [&](const Request &, Response &res) {
  12146. res.set_content("test", "text/plain");
  12147. });
  12148. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12149. auto se = detail::scope_exit([&] {
  12150. svr.stop_ = true;
  12151. svr.stop();
  12152. t.join();
  12153. ASSERT_FALSE(svr.is_running());
  12154. });
  12155. svr.wait_until_ready();
  12156. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12157. cli.enable_server_certificate_verification(false);
  12158. cli.set_connection_timeout(1);
  12159. auto res = cli.Get("/test");
  12160. ASSERT_TRUE(!res);
  12161. EXPECT_EQ(Error::SSLConnection, res.error());
  12162. // Timeout results in WantRead error code (maps to backend-specific value)
  12163. EXPECT_NE(0, res.ssl_error());
  12164. }
  12165. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12166. // Test SSLServer with client certificate verification using the standard
  12167. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12169. CLIENT_CA_CERT_DIR);
  12170. ASSERT_TRUE(svr.is_valid());
  12171. svr.Get("/test", [&](const Request &req, Response &res) {
  12172. res.set_content("test", "text/plain");
  12173. auto cert = req.peer_cert();
  12174. ASSERT_TRUE(static_cast<bool>(cert));
  12175. auto common_name = cert.subject_cn();
  12176. EXPECT_EQ("Common Name", common_name);
  12177. });
  12178. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12179. auto se = detail::scope_exit([&] {
  12180. svr.stop();
  12181. t.join();
  12182. ASSERT_FALSE(svr.is_running());
  12183. });
  12184. svr.wait_until_ready();
  12185. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12186. cli.enable_server_certificate_verification(false);
  12187. cli.set_connection_timeout(30);
  12188. auto res = cli.Get("/test");
  12189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12190. ASSERT_EQ(StatusCode::OK_200, res->status);
  12191. }
  12192. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12193. // Verifies that wildcard matching and exact matching work consistently
  12194. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12195. using namespace httplib::tls;
  12196. // We need a running server to test against
  12197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12198. ASSERT_TRUE(svr.is_valid());
  12199. svr.Get("/test", [](const Request &, Response &res) {
  12200. res.set_content("ok", "text/plain");
  12201. });
  12202. thread t([&]() { svr.listen(HOST, PORT); });
  12203. auto se = detail::scope_exit([&] {
  12204. svr.stop();
  12205. t.join();
  12206. });
  12207. svr.wait_until_ready();
  12208. bool verify_callback_called = false;
  12209. bool verify_result_wrong = false;
  12210. SSLClient cli(HOST, PORT);
  12211. cli.enable_server_certificate_verification(true);
  12212. cli.set_ca_cert_path(CA_CERT_FILE);
  12213. cli.set_connection_timeout(5);
  12214. // Note: Test certificate has CN="Common Name", not "localhost"
  12215. bool verify_result_cn = false;
  12216. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12217. verify_callback_called = true;
  12218. if (!ctx.cert) return false;
  12219. // Test 1: "Common Name" should match (our test server cert CN)
  12220. verify_result_cn = ctx.check_hostname("Common Name");
  12221. // Test 2: wrong hostname should not match
  12222. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12223. return true; // Accept for the purpose of this test
  12224. });
  12225. auto res = cli.Get("/test");
  12226. // The request may succeed or fail depending on cert configuration
  12227. // but the callback should have been called
  12228. ASSERT_TRUE(verify_callback_called)
  12229. << "Verify callback should have been called";
  12230. // CN="Common Name" should match our test certificate
  12231. //
  12232. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12233. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12234. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12235. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12236. // <openssl/base.h>, which is included transitively when
  12237. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12238. #if defined(OPENSSL_IS_BORINGSSL)
  12239. EXPECT_FALSE(verify_result_cn)
  12240. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12241. #else
  12242. EXPECT_TRUE(verify_result_cn)
  12243. << "verify_hostname should match 'Common Name' (certificate CN)";
  12244. #endif
  12245. // Wrong hostname should not match
  12246. EXPECT_FALSE(verify_result_wrong)
  12247. << "verify_hostname should not match 'wronghost.example.com'";
  12248. }
  12249. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12250. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12251. // X509_check_ip behavior and must hold for every backend.
  12252. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12253. using namespace httplib::tls;
  12254. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12255. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12256. ASSERT_TRUE(svr.is_valid());
  12257. svr.Get("/test", [](const Request &, Response &res) {
  12258. res.set_content("ok", "text/plain");
  12259. });
  12260. thread t([&]() { svr.listen(HOST, PORT); });
  12261. auto se = detail::scope_exit([&] {
  12262. svr.stop();
  12263. t.join();
  12264. });
  12265. svr.wait_until_ready();
  12266. bool verify_callback_called = false;
  12267. bool ip_matched_via_cn = true;
  12268. SSLClient cli(HOST, PORT);
  12269. cli.enable_server_certificate_verification(true);
  12270. cli.set_ca_cert_path(CA_CERT_FILE);
  12271. cli.set_connection_timeout(5);
  12272. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12273. verify_callback_called = true;
  12274. if (!ctx.cert) return false;
  12275. // The IP appears only in the CN, so it must NOT be accepted.
  12276. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12277. return true; // Accept for the purpose of this test
  12278. });
  12279. cli.Get("/test");
  12280. ASSERT_TRUE(verify_callback_called)
  12281. << "Verify callback should have been called";
  12282. EXPECT_FALSE(ip_matched_via_cn)
  12283. << "An IP host must not be authenticated via the certificate CN";
  12284. }
  12285. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12286. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12287. using namespace httplib::tls;
  12288. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12289. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12290. ASSERT_TRUE(svr.is_valid());
  12291. svr.Get("/test", [](const Request &, Response &res) {
  12292. res.set_content("ok", "text/plain");
  12293. });
  12294. thread t([&]() { svr.listen(HOST, PORT); });
  12295. auto se = detail::scope_exit([&] {
  12296. svr.stop();
  12297. t.join();
  12298. });
  12299. svr.wait_until_ready();
  12300. bool verify_callback_called = false;
  12301. bool san_matched = false;
  12302. bool wrong_ipv6_matched = true;
  12303. bool cn_ipv6_matched = true;
  12304. SSLClient cli(HOST, PORT);
  12305. cli.enable_server_certificate_verification(true);
  12306. cli.set_ca_cert_path(CA_CERT_FILE);
  12307. cli.set_connection_timeout(5);
  12308. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12309. verify_callback_called = true;
  12310. if (!ctx.cert) return false;
  12311. // Matches the IPv6 iPAddress SAN.
  12312. san_matched = ctx.check_hostname("2001:db8::1");
  12313. // A different IPv6 address must not match.
  12314. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12315. // "::1" lives only in the CN, so it must not be accepted.
  12316. cn_ipv6_matched = ctx.check_hostname("::1");
  12317. return true; // Accept for the purpose of this test
  12318. });
  12319. cli.Get("/test");
  12320. ASSERT_TRUE(verify_callback_called)
  12321. << "Verify callback should have been called";
  12322. EXPECT_TRUE(san_matched)
  12323. << "verify_hostname should match an IPv6 iPAddress SAN";
  12324. EXPECT_FALSE(wrong_ipv6_matched)
  12325. << "verify_hostname should not match a non-matching IPv6 address";
  12326. EXPECT_FALSE(cn_ipv6_matched)
  12327. << "An IPv6 host must not be authenticated via the certificate CN";
  12328. }
  12329. #endif
  12330. // mbedTLS-specific callback constructor test
  12331. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12332. #ifdef CPPHTTPLIB_SSL_ENABLED
  12333. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12335. ASSERT_TRUE(svr.is_valid());
  12336. // Set up a handler to verify client certificate is present
  12337. bool client_cert_verified = false;
  12338. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12339. // Verify that client certificate was provided
  12340. client_cert_verified = true;
  12341. res.set_content("success", "text/plain");
  12342. });
  12343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12344. auto se = detail::scope_exit([&] {
  12345. svr.stop();
  12346. t.join();
  12347. ASSERT_FALSE(svr.is_running());
  12348. });
  12349. svr.wait_until_ready();
  12350. // Client with certificate
  12351. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12352. cli.enable_server_certificate_verification(false);
  12353. cli.set_connection_timeout(30);
  12354. auto res = cli.Get("/test");
  12355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12356. ASSERT_EQ(StatusCode::OK_200, res->status);
  12357. ASSERT_TRUE(client_cert_verified);
  12358. EXPECT_EQ("success", res->body);
  12359. }
  12360. #endif
  12361. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12362. // backends
  12363. #ifdef CPPHTTPLIB_SSL_ENABLED
  12364. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12365. using namespace httplib::tls;
  12366. // Test that when client CA cert file is provided,
  12367. // the server properly requests and validates client certificates
  12368. // Create a server with client authentication
  12369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12370. ASSERT_TRUE(svr.is_valid());
  12371. bool handler_called = false;
  12372. svr.Get("/test", [&](const Request &req, Response &res) {
  12373. handler_called = true;
  12374. // Verify that a client certificate was provided
  12375. auto cert = req.peer_cert();
  12376. ASSERT_TRUE(static_cast<bool>(cert));
  12377. // Get the issuer name
  12378. std::string issuer_str = cert.issuer_name();
  12379. ASSERT_FALSE(issuer_str.empty());
  12380. // The client certificate should be issued by our test CA
  12381. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12382. res.set_content("authenticated", "text/plain");
  12383. });
  12384. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12385. auto se = detail::scope_exit([&] {
  12386. svr.stop();
  12387. t.join();
  12388. ASSERT_FALSE(svr.is_running());
  12389. });
  12390. svr.wait_until_ready();
  12391. // Connect with a client certificate issued by the CA
  12392. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12393. cli.enable_server_certificate_verification(false);
  12394. cli.set_connection_timeout(30);
  12395. auto res = cli.Get("/test");
  12396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12397. ASSERT_EQ(StatusCode::OK_200, res->status);
  12398. ASSERT_TRUE(handler_called);
  12399. EXPECT_EQ("authenticated", res->body);
  12400. }
  12401. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12402. using namespace httplib::tls;
  12403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12404. ASSERT_TRUE(svr.is_valid());
  12405. svr.Get("/test", [](const Request &, Response &res) {
  12406. res.set_content("ok", "text/plain");
  12407. });
  12408. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12409. auto se = detail::scope_exit([&] {
  12410. svr.stop();
  12411. t.join();
  12412. });
  12413. svr.wait_until_ready();
  12414. SSLClient cli(HOST, PORT);
  12415. cli.enable_server_certificate_verification(false);
  12416. cli.set_connection_timeout(30);
  12417. bool cert_checked = false;
  12418. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12419. if (ctx.cert) {
  12420. auto sans = ctx.sans();
  12421. // Test certificate may or may not have SANs - just verify the API
  12422. // works If SANs exist, verify the types are valid
  12423. for (const auto &san : sans) {
  12424. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12425. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12426. san.type == SanType::OTHER);
  12427. EXPECT_FALSE(san.value.empty());
  12428. }
  12429. cert_checked = true;
  12430. }
  12431. return true;
  12432. });
  12433. auto res = cli.Get("/test");
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12435. EXPECT_TRUE(cert_checked);
  12436. }
  12437. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12438. using namespace httplib::tls;
  12439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12440. ASSERT_TRUE(svr.is_valid());
  12441. svr.Get("/test", [](const Request &, Response &res) {
  12442. res.set_content("ok", "text/plain");
  12443. });
  12444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12445. auto se = detail::scope_exit([&] {
  12446. svr.stop();
  12447. t.join();
  12448. });
  12449. svr.wait_until_ready();
  12450. SSLClient cli(HOST, PORT);
  12451. cli.enable_server_certificate_verification(false);
  12452. cli.set_connection_timeout(30);
  12453. bool validity_checked = false;
  12454. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12455. if (ctx.cert) {
  12456. time_t not_before = 0, not_after = 0;
  12457. bool result = ctx.validity(not_before, not_after);
  12458. EXPECT_TRUE(result);
  12459. // Verify that not_before < now < not_after for a valid cert
  12460. time_t now = time(nullptr);
  12461. EXPECT_LT(not_before, now);
  12462. EXPECT_GT(not_after, now);
  12463. validity_checked = true;
  12464. }
  12465. return true;
  12466. });
  12467. auto res = cli.Get("/test");
  12468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12469. EXPECT_TRUE(validity_checked);
  12470. }
  12471. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12472. using namespace httplib::tls;
  12473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12474. ASSERT_TRUE(svr.is_valid());
  12475. svr.Get("/test", [](const Request &, Response &res) {
  12476. res.set_content("ok", "text/plain");
  12477. });
  12478. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12479. auto se = detail::scope_exit([&] {
  12480. svr.stop();
  12481. t.join();
  12482. });
  12483. svr.wait_until_ready();
  12484. SSLClient cli(HOST, PORT);
  12485. cli.enable_server_certificate_verification(false);
  12486. cli.set_connection_timeout(30);
  12487. bool serial_checked = false;
  12488. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12489. if (ctx.cert) {
  12490. std::string serial = ctx.serial();
  12491. EXPECT_FALSE(serial.empty());
  12492. // Serial should be a hex string
  12493. for (char c : serial) {
  12494. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12495. (c >= 'a' && c <= 'f'));
  12496. }
  12497. serial_checked = true;
  12498. }
  12499. return true;
  12500. });
  12501. auto res = cli.Get("/test");
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. EXPECT_TRUE(serial_checked);
  12504. }
  12505. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12506. // Test 1: Valid CA file - no error should be recorded
  12507. {
  12508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12509. CLIENT_CA_CERT_FILE);
  12510. ASSERT_TRUE(svr.is_valid());
  12511. // With valid setup, last_ssl_error should be 0
  12512. EXPECT_EQ(0, svr.ssl_last_error());
  12513. }
  12514. // Test 2: Invalid CA file content
  12515. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12516. {
  12517. // Create a temporary file with completely invalid content
  12518. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12519. {
  12520. std::ofstream ofs(temp_invalid_ca);
  12521. ofs << "This is not a certificate file at all\n";
  12522. ofs << "Just plain text content\n";
  12523. }
  12524. // Create server with invalid CA file
  12525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12526. // Clean up temporary file
  12527. std::remove(temp_invalid_ca);
  12528. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12529. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12530. // Note: SSL_CTX_load_verify_locations typically fails first,
  12531. // but our error handling code path is still exercised
  12532. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12533. }
  12534. }
  12535. TEST(VerifyCallbackTest, VerifyContextFields) {
  12536. using namespace httplib::tls;
  12537. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12538. ASSERT_TRUE(svr.is_valid());
  12539. svr.Get("/test", [](const Request &, Response &res) {
  12540. res.set_content("ok", "text/plain");
  12541. });
  12542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12543. auto se = detail::scope_exit([&] {
  12544. svr.stop();
  12545. t.join();
  12546. });
  12547. svr.wait_until_ready();
  12548. SSLClient cli(HOST, PORT);
  12549. cli.enable_server_certificate_verification(false);
  12550. cli.set_connection_timeout(30);
  12551. int callback_count = 0;
  12552. bool saw_leaf_cert = false;
  12553. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12554. if (ctx.cert) {
  12555. callback_count++;
  12556. // We should see at least one certificate (the leaf)
  12557. std::string cn = ctx.subject_cn();
  12558. if (!cn.empty()) { saw_leaf_cert = true; }
  12559. // Verify context fields are populated
  12560. EXPECT_NE(ctx.session, nullptr);
  12561. EXPECT_GE(ctx.depth, 0);
  12562. }
  12563. return true;
  12564. });
  12565. auto res = cli.Get("/test");
  12566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12567. EXPECT_GT(callback_count, 0);
  12568. EXPECT_TRUE(saw_leaf_cert);
  12569. }
  12570. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12571. using httplib::tls::TlsError;
  12572. // Test that verify_error_to_string returns empty for success
  12573. std::string success_str = TlsError::verify_error_to_string(0);
  12574. EXPECT_TRUE(success_str.empty());
  12575. // Test that verify_error_to_string returns non-empty for error codes
  12576. // Using a common error code (certificate expired)
  12577. std::string error_str =
  12578. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12579. EXPECT_FALSE(error_str.empty());
  12580. }
  12581. TEST(SessionVerifierTest, CertificateAccepted) {
  12582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12583. ASSERT_TRUE(svr.is_valid());
  12584. svr.Get("/test", [](const Request &, Response &res) {
  12585. res.set_content("ok", "text/plain");
  12586. });
  12587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. t.join();
  12591. });
  12592. svr.wait_until_ready();
  12593. SSLClient cli(HOST, PORT);
  12594. cli.enable_server_certificate_verification(false);
  12595. cli.set_connection_timeout(30);
  12596. bool callback_called = false;
  12597. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12598. EXPECT_NE(session, nullptr);
  12599. callback_called = true;
  12600. return SSLVerifierResponse::CertificateAccepted;
  12601. });
  12602. auto res = cli.Get("/test");
  12603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12604. EXPECT_EQ(200, res->status);
  12605. EXPECT_TRUE(callback_called);
  12606. }
  12607. TEST(SessionVerifierTest, CertificateRejected) {
  12608. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12609. ASSERT_TRUE(svr.is_valid());
  12610. svr.Get("/test", [](const Request &, Response &res) {
  12611. res.set_content("ok", "text/plain");
  12612. });
  12613. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. t.join();
  12617. });
  12618. svr.wait_until_ready();
  12619. SSLClient cli(HOST, PORT);
  12620. cli.enable_server_certificate_verification(false);
  12621. cli.set_connection_timeout(30);
  12622. bool callback_called = false;
  12623. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12624. EXPECT_NE(session, nullptr);
  12625. callback_called = true;
  12626. return SSLVerifierResponse::CertificateRejected;
  12627. });
  12628. auto res = cli.Get("/test");
  12629. EXPECT_FALSE(res);
  12630. EXPECT_TRUE(callback_called);
  12631. }
  12632. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12634. ASSERT_TRUE(svr.is_valid());
  12635. svr.Get("/test", [](const Request &, Response &res) {
  12636. res.set_content("ok", "text/plain");
  12637. });
  12638. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12639. auto se = detail::scope_exit([&] {
  12640. svr.stop();
  12641. t.join();
  12642. });
  12643. svr.wait_until_ready();
  12644. // NoDecisionMade with verification disabled should succeed (no default check)
  12645. SSLClient cli(HOST, PORT);
  12646. cli.enable_server_certificate_verification(false);
  12647. cli.set_connection_timeout(30);
  12648. bool callback_called = false;
  12649. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12650. EXPECT_NE(session, nullptr);
  12651. callback_called = true;
  12652. return SSLVerifierResponse::NoDecisionMade;
  12653. });
  12654. auto res = cli.Get("/test");
  12655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12656. EXPECT_EQ(200, res->status);
  12657. EXPECT_TRUE(callback_called);
  12658. }
  12659. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12661. ASSERT_TRUE(svr.is_valid());
  12662. svr.Get("/test", [](const Request &, Response &res) {
  12663. res.set_content("ok", "text/plain");
  12664. });
  12665. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12666. auto se = detail::scope_exit([&] {
  12667. svr.stop();
  12668. t.join();
  12669. });
  12670. svr.wait_until_ready();
  12671. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12672. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12673. // so we only check that the request fails, not whether the callback was
  12674. // called.
  12675. SSLClient cli(HOST, PORT);
  12676. cli.enable_server_certificate_verification(true);
  12677. cli.set_connection_timeout(30);
  12678. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12679. EXPECT_NE(session, nullptr);
  12680. return SSLVerifierResponse::NoDecisionMade;
  12681. });
  12682. auto res = cli.Get("/test");
  12683. EXPECT_FALSE(res);
  12684. }
  12685. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12686. // Test SSL server using PemMemory constructor with client CA certificates
  12687. // Read PEM files
  12688. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12689. read_file(SERVER_CERT_FILE, server_cert_pem);
  12690. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12691. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12692. // Create SSLServer with PemMemory constructor including client CA
  12693. SSLServer::PemMemory server_pem = {
  12694. server_cert_pem.c_str(),
  12695. server_cert_pem.size(),
  12696. server_key_pem.c_str(),
  12697. server_key_pem.size(),
  12698. client_ca_pem.c_str(),
  12699. client_ca_pem.size(),
  12700. nullptr // no password for server key
  12701. };
  12702. SSLServer svr(server_pem);
  12703. ASSERT_TRUE(svr.is_valid());
  12704. // No SSL error should be recorded for valid setup
  12705. EXPECT_EQ(0, svr.ssl_last_error());
  12706. // Set up server endpoints
  12707. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12708. res.set_content("ok", "text/plain");
  12709. });
  12710. // Start server in a thread
  12711. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12712. svr.wait_until_ready();
  12713. // Connect with client certificate (using constructor with paths)
  12714. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12715. cli.enable_server_certificate_verification(false);
  12716. auto res = cli.Get("/test-pem-ca");
  12717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12718. EXPECT_EQ(200, res->status);
  12719. EXPECT_EQ("ok", res->body);
  12720. svr.stop();
  12721. server_thread.join();
  12722. }
  12723. #endif
  12724. #ifdef _WIN32
  12725. TEST(CleanupTest, WSACleanup) {
  12726. int ret = WSACleanup();
  12727. ASSERT_EQ(0, ret);
  12728. }
  12729. #endif
  12730. #ifndef CPPHTTPLIB_SSL_ENABLED
  12731. TEST(NoSSLSupport, SimpleInterface) {
  12732. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12733. }
  12734. #endif
  12735. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12736. TEST(InvalidScheme, SimpleInterface) {
  12737. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12738. }
  12739. #endif
  12740. TEST(NoScheme, SimpleInterface) {
  12741. Client cli("yahoo.com:80");
  12742. ASSERT_TRUE(cli.is_valid());
  12743. }
  12744. TEST(SendAPI, SimpleInterface_Online) {
  12745. Client cli("http://yahoo.com");
  12746. Request req;
  12747. req.method = "GET";
  12748. req.path = "/";
  12749. auto res = cli.send(req);
  12750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12751. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12752. }
  12753. TEST(SendAPI, WithParamsInRequest) {
  12754. Server svr;
  12755. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12756. EXPECT_TRUE(req.has_param("test"));
  12757. EXPECT_EQ("test_value", req.get_param_value("test"));
  12758. });
  12759. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12760. auto se = detail::scope_exit([&] {
  12761. svr.stop();
  12762. t.join();
  12763. ASSERT_FALSE(svr.is_running());
  12764. });
  12765. svr.wait_until_ready();
  12766. Client cli(HOST, PORT);
  12767. {
  12768. Request req;
  12769. req.method = "GET";
  12770. req.path = "/";
  12771. req.params.emplace("test", "test_value");
  12772. auto res = cli.send(req);
  12773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12774. }
  12775. {
  12776. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12778. }
  12779. }
  12780. TEST(ClientImplMethods, GetSocketTest) {
  12781. httplib::Server svr;
  12782. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12783. res.status = StatusCode::OK_200;
  12784. });
  12785. auto port = svr.bind_to_any_port("127.0.0.1");
  12786. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12787. auto se = detail::scope_exit([&] {
  12788. svr.stop();
  12789. thread.join();
  12790. ASSERT_FALSE(svr.is_running());
  12791. });
  12792. svr.wait_until_ready();
  12793. {
  12794. httplib::Client cli("127.0.0.1", port);
  12795. cli.set_keep_alive(true);
  12796. // Use the behavior of cpp-httplib of opening the connection
  12797. // only when the first request happens. If that changes,
  12798. // this test would be obsolete.
  12799. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12800. // This also implicitly tests the server. But other tests would fail much
  12801. // earlier than this one to be considered.
  12802. auto res = cli.Get("/");
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. EXPECT_EQ(StatusCode::OK_200, res->status);
  12805. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12806. }
  12807. }
  12808. #ifdef CPPHTTPLIB_SSL_ENABLED
  12809. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12810. Client cli("http://yahoo.com");
  12811. auto res = cli.Get("/");
  12812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12813. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12814. cli.set_follow_location(true);
  12815. res = cli.Get("/");
  12816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12817. EXPECT_EQ(StatusCode::OK_200, res->status);
  12818. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12819. }
  12820. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12821. Client cli("https://yahoo.com");
  12822. auto res = cli.Get("/");
  12823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12824. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12825. cli.set_follow_location(true);
  12826. res = cli.Get("/");
  12827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12828. EXPECT_EQ(StatusCode::OK_200, res->status);
  12829. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12830. }
  12831. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12832. Client cli("https://yahoo.com");
  12833. auto res = cli.Get("/");
  12834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12835. ASSERT_FALSE(!res);
  12836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12837. ASSERT_FALSE(res == nullptr);
  12838. ASSERT_TRUE(res != nullptr);
  12839. EXPECT_EQ(Error::Success, res.error());
  12840. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12841. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12842. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12843. cli.set_follow_location(true);
  12844. res = cli.Get("/");
  12845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12846. EXPECT_EQ(Error::Success, res.error());
  12847. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12848. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12849. EXPECT_EQ(StatusCode::OK_200, res->status);
  12850. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12851. }
  12852. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12853. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12854. Client cli("https://cdnjs.cloudflare.com");
  12855. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12856. Headers{{"Accept-Encoding", "br"}});
  12857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12858. EXPECT_EQ(StatusCode::OK_200, res->status);
  12859. EXPECT_EQ(287630U, res->body.size());
  12860. EXPECT_EQ("application/javascript; charset=utf-8",
  12861. res->get_header_value("Content-Type"));
  12862. }
  12863. #endif
  12864. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12865. #undef REDIR_HOST // Silence compiler warning
  12866. #define REDIR_HOST "https://httpbingo.org"
  12867. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12868. Client cli(REDIR_HOST);
  12869. cli.set_follow_location(true);
  12870. auto res =
  12871. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12873. EXPECT_EQ(StatusCode::OK_200, res->status);
  12874. }
  12875. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12876. Client cli(REDIR_HOST);
  12877. cli.set_follow_location(true);
  12878. Params params;
  12879. params.emplace("url", "http://example.com");
  12880. params.emplace("status_code", "302");
  12881. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12883. EXPECT_EQ(StatusCode::OK_200, res->status);
  12884. }
  12885. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12886. Client cli(REDIR_HOST);
  12887. cli.set_follow_location(true);
  12888. Params params;
  12889. params.emplace("url", "http://example.com");
  12890. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12892. EXPECT_EQ(StatusCode::OK_200, res->status);
  12893. }
  12894. TEST(HttpToHttpsRedirectTest, CertFile) {
  12895. auto ssl_port = PORT + 1;
  12896. Server svr;
  12897. ASSERT_TRUE(svr.is_valid());
  12898. svr.Get("/index", [&](const Request &, Response &res) {
  12899. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12900. "/index");
  12901. svr.stop();
  12902. });
  12903. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12904. ASSERT_TRUE(ssl_svr.is_valid());
  12905. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12906. res.set_content("test", "text/plain");
  12907. ssl_svr.stop();
  12908. });
  12909. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12910. thread t2 =
  12911. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12912. auto se = detail::scope_exit([&] {
  12913. t2.join();
  12914. t.join();
  12915. ASSERT_FALSE(svr.is_running());
  12916. });
  12917. svr.wait_until_ready();
  12918. ssl_svr.wait_until_ready();
  12919. Client cli("127.0.0.1", PORT);
  12920. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12921. cli.enable_server_certificate_verification(true);
  12922. cli.set_follow_location(true);
  12923. cli.set_connection_timeout(30);
  12924. auto res = cli.Get("/index");
  12925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12926. ASSERT_EQ(StatusCode::OK_200, res->status);
  12927. }
  12928. TEST(SSLClientRedirectTest, CertFile) {
  12929. auto ssl_port = PORT + 1;
  12930. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12931. ASSERT_TRUE(ssl_svr1.is_valid());
  12932. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12933. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12934. "/index");
  12935. ssl_svr1.stop();
  12936. });
  12937. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12938. ASSERT_TRUE(ssl_svr2.is_valid());
  12939. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12940. res.set_content("test", "text/plain");
  12941. ssl_svr2.stop();
  12942. });
  12943. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12944. thread t2 =
  12945. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12946. auto se = detail::scope_exit([&] {
  12947. t2.join();
  12948. t.join();
  12949. ASSERT_FALSE(ssl_svr1.is_running());
  12950. });
  12951. ssl_svr1.wait_until_ready();
  12952. ssl_svr2.wait_until_ready();
  12953. SSLClient cli("127.0.0.1", PORT);
  12954. std::string cert;
  12955. read_file(SERVER_CERT2_FILE, cert);
  12956. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12957. cli.enable_server_certificate_verification(true);
  12958. cli.set_follow_location(true);
  12959. cli.set_connection_timeout(30);
  12960. auto res = cli.Get("/index");
  12961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12962. ASSERT_EQ(StatusCode::OK_200, res->status);
  12963. }
  12964. #endif
  12965. #ifdef CPPHTTPLIB_SSL_ENABLED
  12966. // Test that set_ca_cert_store() skips system certs (consistent with
  12967. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12968. // should be trusted - system certs should NOT be loaded.
  12969. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12970. // Load a specific cert that is NOT a system CA cert
  12971. std::string cert;
  12972. read_file(SERVER_CERT2_FILE, cert);
  12973. SSLClient cli("google.com");
  12974. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12975. cli.enable_server_certificate_verification(true);
  12976. // This should FAIL because:
  12977. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12978. // 2. System certs should NOT be loaded when custom store is set
  12979. // If system certs WERE loaded, this would succeed
  12980. auto res = cli.Get("/");
  12981. ASSERT_FALSE(res);
  12982. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12983. }
  12984. // Same as above, but through the native store handle path. Regression test:
  12985. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12986. // merged system certs into the user-provided store.
  12987. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12988. std::string cert;
  12989. read_file(SERVER_CERT2_FILE, cert);
  12990. SSLClient cli("google.com");
  12991. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12992. cli.enable_server_certificate_verification(true);
  12993. auto res = cli.Get("/");
  12994. ASSERT_FALSE(res);
  12995. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12996. }
  12997. // A custom store set via the native handle must still verify a server whose
  12998. // cert it does contain.
  12999. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13000. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13001. ASSERT_TRUE(svr.is_valid());
  13002. svr.Get("/test", [&](const Request &, Response &res) {
  13003. res.set_content("test", "text/plain");
  13004. });
  13005. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13006. auto se = detail::scope_exit([&] {
  13007. svr.stop();
  13008. t.join();
  13009. ASSERT_FALSE(svr.is_running());
  13010. });
  13011. svr.wait_until_ready();
  13012. SSLClient cli("127.0.0.1", PORT);
  13013. std::string cert;
  13014. read_file(SERVER_CERT2_FILE, cert);
  13015. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13016. cli.enable_server_certificate_verification(true);
  13017. cli.set_connection_timeout(30);
  13018. auto res = cli.Get("/test");
  13019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13020. ASSERT_EQ(StatusCode::OK_200, res->status);
  13021. }
  13022. // CA certs loaded through the universal Client must be transferred to the
  13023. // client created internally for following an HTTPS redirect. Regression test:
  13024. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13025. // the CA data for redirect transfer.
  13026. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13027. auto ssl_port = PORT + 1;
  13028. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13029. ASSERT_TRUE(ssl_svr1.is_valid());
  13030. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13031. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13032. "/index");
  13033. });
  13034. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13035. ASSERT_TRUE(ssl_svr2.is_valid());
  13036. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13037. res.set_content("test", "text/plain");
  13038. });
  13039. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13040. thread t2 =
  13041. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13042. auto se = detail::scope_exit([&] {
  13043. ssl_svr2.stop();
  13044. ssl_svr1.stop();
  13045. t2.join();
  13046. t.join();
  13047. ASSERT_FALSE(ssl_svr1.is_running());
  13048. });
  13049. ssl_svr1.wait_until_ready();
  13050. ssl_svr2.wait_until_ready();
  13051. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13052. std::string cert;
  13053. read_file(SERVER_CERT2_FILE, cert);
  13054. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13055. cli.enable_server_certificate_verification(true);
  13056. cli.set_follow_location(true);
  13057. cli.set_connection_timeout(30);
  13058. auto res = cli.Get("/index");
  13059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13060. ASSERT_EQ(StatusCode::OK_200, res->status);
  13061. }
  13062. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13063. // so a host signed by a system CA verifies even though a custom CA is set
  13064. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13065. std::string cert;
  13066. read_file(SERVER_CERT2_FILE, cert);
  13067. SSLClient cli("google.com");
  13068. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13069. cli.enable_system_ca(true);
  13070. cli.enable_server_certificate_verification(true);
  13071. auto res = cli.Get("/");
  13072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13073. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13074. }
  13075. // The custom CA remains effective when combined with the system CA
  13076. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13077. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13078. ASSERT_TRUE(svr.is_valid());
  13079. svr.Get("/test", [&](const Request &, Response &res) {
  13080. res.set_content("test", "text/plain");
  13081. });
  13082. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13083. auto se = detail::scope_exit([&] {
  13084. svr.stop();
  13085. t.join();
  13086. ASSERT_FALSE(svr.is_running());
  13087. });
  13088. svr.wait_until_ready();
  13089. SSLClient cli("127.0.0.1", PORT);
  13090. std::string cert;
  13091. read_file(SERVER_CERT2_FILE, cert);
  13092. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13093. cli.enable_system_ca(true);
  13094. cli.enable_server_certificate_verification(true);
  13095. cli.set_connection_timeout(30);
  13096. auto res = cli.Get("/test");
  13097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13098. ASSERT_EQ(StatusCode::OK_200, res->status);
  13099. }
  13100. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13101. // skip chain verification entirely (only the certificate identity was
  13102. // checked), so a server presenting an untrusted certificate with a matching
  13103. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13104. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13105. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13106. ASSERT_TRUE(svr.is_valid());
  13107. svr.Get("/test", [&](const Request &, Response &res) {
  13108. res.set_content("test", "text/plain");
  13109. });
  13110. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13111. auto se = detail::scope_exit([&] {
  13112. svr.stop();
  13113. t.join();
  13114. ASSERT_FALSE(svr.is_running());
  13115. });
  13116. svr.wait_until_ready();
  13117. SSLClient cli("127.0.0.1", PORT);
  13118. std::string cert;
  13119. // A trusted CA that did not sign the server certificate. The server cert
  13120. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13121. // this connection.
  13122. read_file(CLIENT_CA_CERT_FILE, cert);
  13123. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13124. cli.enable_server_certificate_verification(true);
  13125. cli.set_connection_timeout(30);
  13126. auto res = cli.Get("/test");
  13127. ASSERT_FALSE(res);
  13128. }
  13129. // enable_system_ca(false) prevents system CA loading entirely
  13130. TEST(SSLClientTest, DisableSystemCa_Online) {
  13131. SSLClient cli("google.com");
  13132. cli.enable_system_ca(false);
  13133. cli.enable_server_certificate_verification(true);
  13134. auto res = cli.Get("/");
  13135. ASSERT_FALSE(res);
  13136. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13137. // itself when the CA chain is empty
  13138. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13139. res.error() == Error::SSLConnection);
  13140. }
  13141. // The universal Client forwards enable_system_ca()
  13142. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13143. std::string cert;
  13144. read_file(SERVER_CERT2_FILE, cert);
  13145. Client cli("https://google.com");
  13146. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13147. cli.enable_system_ca(true);
  13148. cli.enable_server_certificate_verification(true);
  13149. auto res = cli.Get("/");
  13150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13151. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13152. }
  13153. // The system CA policy must carry over to the client created internally for
  13154. // following a cross-host HTTPS redirect
  13155. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13156. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13157. ASSERT_TRUE(svr.is_valid());
  13158. svr.Get("/index", [&](const Request &, Response &res) {
  13159. res.set_redirect("https://www.google.com/");
  13160. });
  13161. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13162. auto se = detail::scope_exit([&] {
  13163. svr.stop();
  13164. t.join();
  13165. ASSERT_FALSE(svr.is_running());
  13166. });
  13167. svr.wait_until_ready();
  13168. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13169. std::string cert;
  13170. read_file(SERVER_CERT2_FILE, cert);
  13171. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13172. cli.enable_system_ca(true);
  13173. cli.enable_server_certificate_verification(true);
  13174. cli.set_follow_location(true);
  13175. cli.set_connection_timeout(30);
  13176. // Receiving any response proves the redirect client completed the TLS
  13177. // handshake with a system-CA-signed host
  13178. auto res = cli.Get("/index");
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. }
  13181. TEST(MultipartFormDataTest, LargeData) {
  13182. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13183. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13184. const ContentReader &content_reader) {
  13185. if (req.is_multipart_form_data()) {
  13186. std::vector<FormData> items;
  13187. content_reader(
  13188. [&](const FormData &file) {
  13189. items.push_back(file);
  13190. return true;
  13191. },
  13192. [&](const char *data, size_t data_length) {
  13193. items.back().content.append(data, data_length);
  13194. return true;
  13195. });
  13196. EXPECT_TRUE(std::string(items[0].name) == "document");
  13197. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13198. EXPECT_TRUE(items[0].filename == "2MB_data");
  13199. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13200. EXPECT_TRUE(items[1].name == "hello");
  13201. EXPECT_TRUE(items[1].content == "world");
  13202. EXPECT_TRUE(items[1].filename == "");
  13203. EXPECT_TRUE(items[1].content_type == "");
  13204. } else {
  13205. std::string body;
  13206. content_reader([&](const char *data, size_t data_length) {
  13207. body.append(data, data_length);
  13208. return true;
  13209. });
  13210. }
  13211. });
  13212. auto port = svr.bind_to_any_port(HOST);
  13213. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13214. auto se = detail::scope_exit([&] {
  13215. svr.stop();
  13216. t.join();
  13217. ASSERT_FALSE(svr.is_running());
  13218. });
  13219. svr.wait_until_ready();
  13220. {
  13221. std::string data(1024 * 1024 * 2, '.');
  13222. std::stringstream buffer;
  13223. buffer << data;
  13224. SSLClient cli(HOST, port);
  13225. cli.enable_server_certificate_verification(false);
  13226. UploadFormDataItems items{
  13227. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13228. {"hello", "world", "", ""},
  13229. };
  13230. auto res = cli.Post("/post", items);
  13231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13232. ASSERT_EQ(StatusCode::OK_200, res->status);
  13233. }
  13234. }
  13235. TEST(MultipartFormDataTest, DataProviderItems) {
  13236. std::random_device seed_gen;
  13237. std::mt19937 random(seed_gen());
  13238. std::string rand1;
  13239. rand1.resize(1000);
  13240. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13241. std::string rand2;
  13242. rand2.resize(3000);
  13243. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13245. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13246. const ContentReader &content_reader) {
  13247. ASSERT_FALSE(req.is_multipart_form_data());
  13248. std::string body;
  13249. content_reader([&](const char *data, size_t data_length) {
  13250. body.append(data, data_length);
  13251. return true;
  13252. });
  13253. EXPECT_EQ(body, "");
  13254. });
  13255. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13256. const ContentReader &content_reader) {
  13257. ASSERT_TRUE(req.is_multipart_form_data());
  13258. std::vector<FormData> items;
  13259. content_reader(
  13260. [&](const FormData &file) {
  13261. items.push_back(file);
  13262. return true;
  13263. },
  13264. [&](const char *data, size_t data_length) {
  13265. items.back().content.append(data, data_length);
  13266. return true;
  13267. });
  13268. ASSERT_TRUE(items.size() == 2);
  13269. EXPECT_EQ(std::string(items[0].name), "name1");
  13270. EXPECT_EQ(items[0].content, "Testing123");
  13271. EXPECT_EQ(items[0].filename, "filename1");
  13272. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13273. EXPECT_EQ(items[1].name, "name2");
  13274. EXPECT_EQ(items[1].content, "Testing456");
  13275. EXPECT_EQ(items[1].filename, "");
  13276. EXPECT_EQ(items[1].content_type, "");
  13277. });
  13278. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13279. const ContentReader &content_reader) {
  13280. ASSERT_TRUE(req.is_multipart_form_data());
  13281. std::vector<FormData> items;
  13282. content_reader(
  13283. [&](const FormData &file) {
  13284. items.push_back(file);
  13285. return true;
  13286. },
  13287. [&](const char *data, size_t data_length) {
  13288. items.back().content.append(data, data_length);
  13289. return true;
  13290. });
  13291. ASSERT_TRUE(items.size() == 2);
  13292. EXPECT_EQ(items[0].name, "name3");
  13293. EXPECT_EQ(items[0].content, rand1);
  13294. EXPECT_EQ(items[0].filename, "filename3");
  13295. EXPECT_EQ(items[0].content_type, "");
  13296. EXPECT_EQ(items[1].name, "name4");
  13297. EXPECT_EQ(items[1].content, rand2);
  13298. EXPECT_EQ(items[1].filename, "filename4");
  13299. EXPECT_EQ(items[1].content_type, "");
  13300. });
  13301. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13302. const ContentReader &content_reader) {
  13303. ASSERT_TRUE(req.is_multipart_form_data());
  13304. std::vector<FormData> items;
  13305. content_reader(
  13306. [&](const FormData &file) {
  13307. items.push_back(file);
  13308. return true;
  13309. },
  13310. [&](const char *data, size_t data_length) {
  13311. items.back().content.append(data, data_length);
  13312. return true;
  13313. });
  13314. ASSERT_TRUE(items.size() == 4);
  13315. EXPECT_EQ(std::string(items[0].name), "name1");
  13316. EXPECT_EQ(items[0].content, "Testing123");
  13317. EXPECT_EQ(items[0].filename, "filename1");
  13318. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13319. EXPECT_EQ(items[1].name, "name2");
  13320. EXPECT_EQ(items[1].content, "Testing456");
  13321. EXPECT_EQ(items[1].filename, "");
  13322. EXPECT_EQ(items[1].content_type, "");
  13323. EXPECT_EQ(items[2].name, "name3");
  13324. EXPECT_EQ(items[2].content, rand1);
  13325. EXPECT_EQ(items[2].filename, "filename3");
  13326. EXPECT_EQ(items[2].content_type, "");
  13327. EXPECT_EQ(items[3].name, "name4");
  13328. EXPECT_EQ(items[3].content, rand2);
  13329. EXPECT_EQ(items[3].filename, "filename4");
  13330. EXPECT_EQ(items[3].content_type, "");
  13331. });
  13332. auto port = svr.bind_to_any_port("localhost");
  13333. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13334. auto se = detail::scope_exit([&] {
  13335. svr.stop();
  13336. t.join();
  13337. ASSERT_FALSE(svr.is_running());
  13338. });
  13339. svr.wait_until_ready();
  13340. {
  13341. SSLClient cli("localhost", port);
  13342. cli.enable_server_certificate_verification(false);
  13343. UploadFormDataItems items{
  13344. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13345. {"name2", "Testing456", "", ""}, // not a file
  13346. };
  13347. {
  13348. auto res = cli.Post("/post-none", {}, {}, {});
  13349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13350. ASSERT_EQ(StatusCode::OK_200, res->status);
  13351. }
  13352. FormDataProviderItems providers;
  13353. {
  13354. auto res =
  13355. cli.Post("/post-items", {}, items, providers); // empty providers
  13356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13357. ASSERT_EQ(StatusCode::OK_200, res->status);
  13358. }
  13359. providers.push_back({"name3",
  13360. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13361. // test the offset is given correctly at each step
  13362. if (!offset)
  13363. sink.os.write(rand1.data(), 30);
  13364. else if (offset == 30)
  13365. sink.os.write(rand1.data() + 30, 300);
  13366. else if (offset == 330)
  13367. sink.os.write(rand1.data() + 330, 670);
  13368. else if (offset == rand1.size())
  13369. sink.done();
  13370. return true;
  13371. },
  13372. "filename3",
  13373. {}});
  13374. providers.push_back({"name4",
  13375. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13376. // test the offset is given correctly at each step
  13377. if (!offset)
  13378. sink.os.write(rand2.data(), 2000);
  13379. else if (offset == 2000)
  13380. sink.os.write(rand2.data() + 2000, 1);
  13381. else if (offset == 2001)
  13382. sink.os.write(rand2.data() + 2001, 999);
  13383. else if (offset == rand2.size())
  13384. sink.done();
  13385. return true;
  13386. },
  13387. "filename4",
  13388. {}});
  13389. {
  13390. auto res = cli.Post("/post-providers", {}, {}, providers);
  13391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13392. ASSERT_EQ(StatusCode::OK_200, res->status);
  13393. }
  13394. {
  13395. auto res = cli.Post("/post-both", {}, items, providers);
  13396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13397. ASSERT_EQ(StatusCode::OK_200, res->status);
  13398. }
  13399. }
  13400. }
  13401. TEST(MultipartFormDataTest, BadHeader) {
  13402. Server svr;
  13403. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13404. res.set_content("ok", "text/plain");
  13405. });
  13406. thread t = thread([&] { svr.listen(HOST, PORT); });
  13407. auto se = detail::scope_exit([&] {
  13408. svr.stop();
  13409. t.join();
  13410. ASSERT_FALSE(svr.is_running());
  13411. });
  13412. svr.wait_until_ready();
  13413. const std::string body =
  13414. "This is the preamble. It is to be ignored, though it\r\n"
  13415. "is a handy place for composition agents to include an\r\n"
  13416. "explanatory note to non-MIME conformant readers.\r\n"
  13417. "\r\n"
  13418. "\r\n"
  13419. "--simple boundary\r\n"
  13420. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13421. ": BAD...\r\n"
  13422. "\r\n"
  13423. "value1\r\n"
  13424. "--simple boundary\r\n"
  13425. "Content-Disposition: form-data; name=\"field2\"; "
  13426. "filename=\"example.txt\"\r\n"
  13427. "\r\n"
  13428. "value2\r\n"
  13429. "--simple boundary--\r\n"
  13430. "This is the epilogue. It is also to be ignored.\r\n";
  13431. std::string content_type =
  13432. R"(multipart/form-data; boundary="simple boundary")";
  13433. Client cli(HOST, PORT);
  13434. auto res = cli.Post("/post", body, content_type.c_str());
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13437. }
  13438. TEST(MultipartFormDataTest, WithPreamble) {
  13439. Server svr;
  13440. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13441. res.set_content("ok", "text/plain");
  13442. });
  13443. thread t = thread([&] { svr.listen(HOST, PORT); });
  13444. auto se = detail::scope_exit([&] {
  13445. svr.stop();
  13446. t.join();
  13447. ASSERT_FALSE(svr.is_running());
  13448. });
  13449. svr.wait_until_ready();
  13450. const std::string body =
  13451. "This is the preamble. It is to be ignored, though it\r\n"
  13452. "is a handy place for composition agents to include an\r\n"
  13453. "explanatory note to non-MIME conformant readers.\r\n"
  13454. "\r\n"
  13455. "\r\n"
  13456. "--simple boundary\r\n"
  13457. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13458. "\r\n"
  13459. "value1\r\n"
  13460. "--simple boundary\r\n"
  13461. "Content-Disposition: form-data; name=\"field2\"; "
  13462. "filename=\"example.txt\"\r\n"
  13463. "\r\n"
  13464. "value2\r\n"
  13465. "--simple boundary--\r\n"
  13466. "This is the epilogue. It is also to be ignored.\r\n";
  13467. std::string content_type =
  13468. R"(multipart/form-data; boundary="simple boundary")";
  13469. Client cli(HOST, PORT);
  13470. auto res = cli.Post("/post", body, content_type.c_str());
  13471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13472. EXPECT_EQ(StatusCode::OK_200, res->status);
  13473. }
  13474. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13476. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13477. const ContentReader &content_reader) {
  13478. if (req.is_multipart_form_data()) {
  13479. std::vector<FormData> items;
  13480. content_reader(
  13481. [&](const FormData &file) {
  13482. items.push_back(file);
  13483. return true;
  13484. },
  13485. [&](const char *data, size_t data_length) {
  13486. items.back().content.append(data, data_length);
  13487. return true;
  13488. });
  13489. EXPECT_TRUE(std::string(items[0].name) == "document");
  13490. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13491. EXPECT_TRUE(items[0].filename == "2MB_data");
  13492. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13493. EXPECT_TRUE(items[1].name == "hello");
  13494. EXPECT_TRUE(items[1].content == "world");
  13495. EXPECT_TRUE(items[1].filename == "");
  13496. EXPECT_TRUE(items[1].content_type == "");
  13497. } else {
  13498. std::string body;
  13499. content_reader([&](const char *data, size_t data_length) {
  13500. body.append(data, data_length);
  13501. return true;
  13502. });
  13503. }
  13504. });
  13505. auto port = svr.bind_to_any_port("localhost");
  13506. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13507. auto se = detail::scope_exit([&] {
  13508. svr.stop();
  13509. t.join();
  13510. ASSERT_FALSE(svr.is_running());
  13511. });
  13512. svr.wait_until_ready();
  13513. {
  13514. std::string data(1024 * 1024 * 2, '.');
  13515. std::stringstream buffer;
  13516. buffer << data;
  13517. SSLClient cli("localhost", port);
  13518. cli.enable_server_certificate_verification(false);
  13519. UploadFormDataItems items{
  13520. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13521. {"hello", "world", "", ""},
  13522. };
  13523. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. ASSERT_EQ(StatusCode::OK_200, res->status);
  13526. }
  13527. }
  13528. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13529. std::string data(1024 * 1024 * 2, '&');
  13530. std::stringstream buffer;
  13531. buffer << data;
  13532. Client cli("https://localhost:8080");
  13533. UploadFormDataItems items{
  13534. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13535. {"hello", "world", "", ""},
  13536. };
  13537. for (const char &c : " \t\r\n") {
  13538. auto res =
  13539. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13540. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13541. ASSERT_FALSE(res);
  13542. }
  13543. }
  13544. TEST(MultipartFormDataTest, PutFormData) {
  13545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13546. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13547. const ContentReader &content_reader) {
  13548. if (req.is_multipart_form_data()) {
  13549. std::vector<FormData> items;
  13550. content_reader(
  13551. [&](const FormData &file) {
  13552. items.push_back(file);
  13553. return true;
  13554. },
  13555. [&](const char *data, size_t data_length) {
  13556. items.back().content.append(data, data_length);
  13557. return true;
  13558. });
  13559. EXPECT_TRUE(std::string(items[0].name) == "document");
  13560. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13561. EXPECT_TRUE(items[0].filename == "2MB_data");
  13562. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13563. EXPECT_TRUE(items[1].name == "hello");
  13564. EXPECT_TRUE(items[1].content == "world");
  13565. EXPECT_TRUE(items[1].filename == "");
  13566. EXPECT_TRUE(items[1].content_type == "");
  13567. } else {
  13568. std::string body;
  13569. content_reader([&](const char *data, size_t data_length) {
  13570. body.append(data, data_length);
  13571. return true;
  13572. });
  13573. }
  13574. });
  13575. auto port = svr.bind_to_any_port("localhost");
  13576. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13577. auto se = detail::scope_exit([&] {
  13578. svr.stop();
  13579. t.join();
  13580. ASSERT_FALSE(svr.is_running());
  13581. });
  13582. svr.wait_until_ready();
  13583. {
  13584. std::string data(1024 * 1024 * 2, '&');
  13585. std::stringstream buffer;
  13586. buffer << data;
  13587. SSLClient cli("localhost", port);
  13588. cli.enable_server_certificate_verification(false);
  13589. UploadFormDataItems items{
  13590. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13591. {"hello", "world", "", ""},
  13592. };
  13593. auto res = cli.Put("/put", items);
  13594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13595. ASSERT_EQ(StatusCode::OK_200, res->status);
  13596. }
  13597. }
  13598. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13600. svr.Put("/put_customboundary",
  13601. [&](const Request &req, const Response & /*res*/,
  13602. const ContentReader &content_reader) {
  13603. if (req.is_multipart_form_data()) {
  13604. std::vector<FormData> items;
  13605. content_reader(
  13606. [&](const FormData &file) {
  13607. items.push_back(file);
  13608. return true;
  13609. },
  13610. [&](const char *data, size_t data_length) {
  13611. items.back().content.append(data, data_length);
  13612. return true;
  13613. });
  13614. EXPECT_TRUE(std::string(items[0].name) == "document");
  13615. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13616. EXPECT_TRUE(items[0].filename == "2MB_data");
  13617. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13618. EXPECT_TRUE(items[1].name == "hello");
  13619. EXPECT_TRUE(items[1].content == "world");
  13620. EXPECT_TRUE(items[1].filename == "");
  13621. EXPECT_TRUE(items[1].content_type == "");
  13622. } else {
  13623. std::string body;
  13624. content_reader([&](const char *data, size_t data_length) {
  13625. body.append(data, data_length);
  13626. return true;
  13627. });
  13628. }
  13629. });
  13630. auto port = svr.bind_to_any_port("localhost");
  13631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13632. auto se = detail::scope_exit([&] {
  13633. svr.stop();
  13634. t.join();
  13635. ASSERT_FALSE(svr.is_running());
  13636. });
  13637. svr.wait_until_ready();
  13638. {
  13639. std::string data(1024 * 1024 * 2, '&');
  13640. std::stringstream buffer;
  13641. buffer << data;
  13642. SSLClient cli("localhost", port);
  13643. cli.enable_server_certificate_verification(false);
  13644. UploadFormDataItems items{
  13645. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13646. {"hello", "world", "", ""},
  13647. };
  13648. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. }
  13653. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13654. std::string data(1024 * 1024 * 2, '&');
  13655. std::stringstream buffer;
  13656. buffer << data;
  13657. Client cli("https://localhost:8080");
  13658. cli.enable_server_certificate_verification(false);
  13659. UploadFormDataItems items{
  13660. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13661. {"hello", "world", "", ""},
  13662. };
  13663. for (const char &c : " \t\r\n") {
  13664. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13665. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13666. ASSERT_FALSE(res);
  13667. }
  13668. }
  13669. TEST(MultipartFormDataTest, AlternateFilename) {
  13670. auto handled = false;
  13671. Server svr;
  13672. svr.Post("/test", [&](const Request &req, Response &res) {
  13673. ASSERT_EQ(2u, req.form.files.size());
  13674. ASSERT_EQ(1u, req.form.fields.size());
  13675. // Test files
  13676. const auto &file1 = req.form.get_file("file1");
  13677. ASSERT_EQ("file1", file1.name);
  13678. ASSERT_EQ("A.txt", file1.filename);
  13679. ASSERT_EQ("text/plain", file1.content_type);
  13680. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13681. const auto &file2 = req.form.get_file("file2");
  13682. ASSERT_EQ("file2", file2.name);
  13683. ASSERT_EQ("a.html", file2.filename);
  13684. ASSERT_EQ("text/html", file2.content_type);
  13685. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13686. file2.content);
  13687. // Test text field
  13688. const auto &text = req.form.get_field("text");
  13689. ASSERT_EQ("text default", text);
  13690. res.set_content("ok", "text/plain");
  13691. handled = true;
  13692. });
  13693. thread t = thread([&] { svr.listen(HOST, PORT); });
  13694. auto se = detail::scope_exit([&] {
  13695. svr.stop();
  13696. t.join();
  13697. ASSERT_FALSE(svr.is_running());
  13698. ASSERT_TRUE(handled);
  13699. });
  13700. svr.wait_until_ready();
  13701. auto req = "POST /test HTTP/1.1\r\n"
  13702. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13703. "Content-Length: 399\r\n"
  13704. "\r\n"
  13705. "----------\r\n"
  13706. "Content-Disposition: form-data; name=\"text\"\r\n"
  13707. "\r\n"
  13708. "text default\r\n"
  13709. "----------\r\n"
  13710. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13711. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13712. "Content-Type: text/plain\r\n"
  13713. "\r\n"
  13714. "Content of a.txt.\r\n"
  13715. "\r\n"
  13716. "----------\r\n"
  13717. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13718. "\"a.html\"\r\n"
  13719. "Content-Type: text/html\r\n"
  13720. "\r\n"
  13721. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13722. "\r\n"
  13723. "------------\r\n";
  13724. ASSERT_TRUE(send_request(1, req));
  13725. }
  13726. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13727. auto handled = false;
  13728. Server svr;
  13729. svr.Post("/test", [&](const Request &req, Response &res) {
  13730. // Case-insensitive "utf-8''" prefix with a long value
  13731. const auto &file = req.form.get_file("file1");
  13732. ASSERT_EQ("file1", file.name);
  13733. // 8000 chars exercises both the Content-Disposition parser and the
  13734. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13735. // Prior to the fix, std::regex_match on this header would cause O(N)
  13736. // stack recursion in libstdc++, leading to SIGSEGV.
  13737. std::string expected_filename(8000, 'A');
  13738. ASSERT_EQ(expected_filename, file.filename);
  13739. res.set_content("ok", "text/plain");
  13740. handled = true;
  13741. });
  13742. thread t = thread([&] { svr.listen(HOST, PORT); });
  13743. auto se = detail::scope_exit([&] {
  13744. svr.stop();
  13745. t.join();
  13746. ASSERT_FALSE(svr.is_running());
  13747. ASSERT_TRUE(handled);
  13748. });
  13749. svr.wait_until_ready();
  13750. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13751. // Regression test for GHSA-qq6v-r583-3h69
  13752. std::string long_filename(8000, 'A');
  13753. std::string body = "----------\r\n"
  13754. "Content-Disposition: form-data; name=\"file1\"; "
  13755. "filename*=\"Utf-8''" +
  13756. long_filename +
  13757. "\"\r\n"
  13758. "\r\n"
  13759. "hello\r\n"
  13760. "------------\r\n";
  13761. auto req = "POST /test HTTP/1.1\r\n"
  13762. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13763. "Content-Length: " +
  13764. std::to_string(body.size()) + "\r\n\r\n" + body;
  13765. ASSERT_TRUE(send_request(1, req));
  13766. }
  13767. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13768. auto handled = false;
  13769. Server svr;
  13770. svr.Post("/test", [&](const Request &req, Response &) {
  13771. ASSERT_EQ(2u, req.form.fields.size());
  13772. const auto &text1 = req.form.get_field("text1");
  13773. ASSERT_EQ("text1", text1);
  13774. const auto &text2 = req.form.get_field("text2");
  13775. ASSERT_EQ("text2", text2);
  13776. handled = true;
  13777. });
  13778. thread t = thread([&] { svr.listen(HOST, PORT); });
  13779. auto se = detail::scope_exit([&] {
  13780. svr.stop();
  13781. t.join();
  13782. ASSERT_FALSE(svr.is_running());
  13783. ASSERT_TRUE(handled);
  13784. });
  13785. svr.wait_until_ready();
  13786. auto req = "POST /test HTTP/1.1\r\n"
  13787. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13788. "Content-Length: 146\r\n"
  13789. "\r\n----------\r\n"
  13790. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13791. "\r\n"
  13792. "text1"
  13793. "\r\n----------\r\n"
  13794. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13795. "\r\n"
  13796. "text2"
  13797. "\r\n------------";
  13798. std::string response;
  13799. ASSERT_TRUE(send_request(1, req, &response));
  13800. ASSERT_EQ("200", response.substr(9, 3));
  13801. }
  13802. TEST(MultipartFormDataTest, ContentLength) {
  13803. auto handled = false;
  13804. Server svr;
  13805. svr.Post("/test", [&](const Request &req, Response &) {
  13806. ASSERT_EQ(2u, req.form.fields.size());
  13807. const auto &text1 = req.form.get_field("text1");
  13808. ASSERT_EQ("text1", text1);
  13809. const auto &text2 = req.form.get_field("text2");
  13810. ASSERT_EQ("text2", text2);
  13811. handled = true;
  13812. });
  13813. thread t = thread([&] { svr.listen(HOST, PORT); });
  13814. auto se = detail::scope_exit([&] {
  13815. svr.stop();
  13816. t.join();
  13817. ASSERT_FALSE(svr.is_running());
  13818. ASSERT_TRUE(handled);
  13819. });
  13820. svr.wait_until_ready();
  13821. auto req = "POST /test HTTP/1.1\r\n"
  13822. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13823. "Content-Length: 167\r\n"
  13824. "\r\n----------\r\n"
  13825. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13826. "Content-Length: 5\r\n"
  13827. "\r\n"
  13828. "text1"
  13829. "\r\n----------\r\n"
  13830. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13831. "\r\n"
  13832. "text2"
  13833. "\r\n------------\r\n";
  13834. std::string response;
  13835. ASSERT_TRUE(send_request(1, req, &response));
  13836. ASSERT_EQ("200", response.substr(9, 3));
  13837. }
  13838. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13839. auto handled = false;
  13840. Server svr;
  13841. svr.Post("/test", [&](const Request &req, Response &) {
  13842. ASSERT_EQ(2u, req.form.fields.size());
  13843. const auto &text1 = req.form.get_field("text1");
  13844. ASSERT_EQ("text1", text1);
  13845. // TODO: Add header access for text fields if needed
  13846. const auto &text2 = req.form.get_field("text2");
  13847. ASSERT_EQ("text2", text2);
  13848. // TODO: Header access for text fields needs to be implemented
  13849. // auto &headers = it->second.headers;
  13850. // ASSERT_EQ(3U, headers.size());
  13851. // auto custom_header = headers.find("x-whatever");
  13852. // ASSERT_TRUE(custom_header != headers.end());
  13853. // ASSERT_NE("customvalue", custom_header->second);
  13854. // ASSERT_EQ("CustomValue", custom_header->second);
  13855. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13856. handled = true;
  13857. });
  13858. thread t = thread([&] { svr.listen(HOST, PORT); });
  13859. auto se = detail::scope_exit([&] {
  13860. svr.stop();
  13861. t.join();
  13862. ASSERT_FALSE(svr.is_running());
  13863. ASSERT_TRUE(handled);
  13864. });
  13865. svr.wait_until_ready();
  13866. auto req = "POST /test HTTP/1.1\r\n"
  13867. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13868. "Content-Length: 232\r\n"
  13869. "\r\n----------\r\n"
  13870. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13871. "Content-Length: 5\r\n"
  13872. "X-Test: 1\r\n"
  13873. "\r\n"
  13874. "text1"
  13875. "\r\n----------\r\n"
  13876. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13877. "Content-Type: text/plain\r\n"
  13878. "X-Whatever: CustomValue\r\n"
  13879. "\r\n"
  13880. "text2"
  13881. "\r\n------------\r\n"
  13882. "That should be disregarded. Not even read";
  13883. std::string response;
  13884. ASSERT_TRUE(send_request(1, req, &response));
  13885. ASSERT_EQ("200", response.substr(9, 3));
  13886. }
  13887. TEST(MultipartFormDataTest, LargeHeader) {
  13888. auto handled = false;
  13889. Server svr;
  13890. svr.Post("/test", [&](const Request &req, Response &) {
  13891. ASSERT_EQ(1u, req.form.fields.size());
  13892. const auto &text = req.form.get_field("name1");
  13893. ASSERT_EQ("text1", text);
  13894. handled = true;
  13895. });
  13896. thread t = thread([&] { svr.listen(HOST, PORT); });
  13897. auto se = detail::scope_exit([&] {
  13898. svr.stop();
  13899. t.join();
  13900. ASSERT_FALSE(svr.is_running());
  13901. ASSERT_TRUE(handled);
  13902. });
  13903. svr.wait_until_ready();
  13904. auto boundary = std::string("cpp-httplib-multipart-data");
  13905. std::string content = "--" + boundary +
  13906. "\r\n"
  13907. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13908. "\r\n"
  13909. "text1\r\n"
  13910. "--" +
  13911. boundary + "--\r\n";
  13912. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13913. "Content-Type: multipart/form-data;boundary=" +
  13914. boundary +
  13915. "\r\n"
  13916. "Content-Length: " +
  13917. std::to_string(content.size()) +
  13918. "\r\n"
  13919. "Dummy-Header: ";
  13920. std::string header_suffix = "\r\n"
  13921. "\r\n";
  13922. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13923. size_t header_dummy_size =
  13924. read_buff_size -
  13925. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13926. auto header_dummy = std::string(header_dummy_size, '@');
  13927. auto req = header_prefix + header_dummy + header_suffix + content;
  13928. std::string response;
  13929. ASSERT_TRUE(send_request(1, req, &response));
  13930. ASSERT_EQ("200", response.substr(9, 3));
  13931. }
  13932. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13933. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13934. // (not chunked Transfer-Encoding) after the streaming refactor.
  13935. auto handled = false;
  13936. Server svr;
  13937. svr.Post("/upload", [&](const Request &req, Response &res) {
  13938. auto cl_it = req.headers.find("Content-Length");
  13939. EXPECT_TRUE(cl_it != req.headers.end());
  13940. auto te_it = req.headers.find("Transfer-Encoding");
  13941. EXPECT_TRUE(te_it == req.headers.end());
  13942. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13943. res.set_content("ok", "text/plain");
  13944. handled = true;
  13945. });
  13946. auto port = svr.bind_to_any_port(HOST);
  13947. auto t = thread([&] { svr.listen_after_bind(); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop();
  13950. t.join();
  13951. ASSERT_FALSE(svr.is_running());
  13952. ASSERT_TRUE(handled);
  13953. });
  13954. svr.wait_until_ready();
  13955. UploadFormDataItems items = {
  13956. {"field1", "hello", "", "text/plain"},
  13957. {"file1", "world", "test.txt", "application/octet-stream"},
  13958. };
  13959. Client cli(HOST, port);
  13960. auto res = cli.Post("/upload", {}, items);
  13961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13962. EXPECT_EQ(StatusCode::OK_200, res->status);
  13963. }
  13964. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13965. // Verify that make_multipart_content_provider coalesces many small segments
  13966. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13967. constexpr size_t kItemCount = 1000;
  13968. UploadFormDataItems items;
  13969. items.reserve(kItemCount);
  13970. for (size_t i = 0; i < kItemCount; i++) {
  13971. items.push_back(
  13972. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13973. }
  13974. const std::string boundary = "----test-boundary";
  13975. auto content_length = detail::get_multipart_content_length(items, boundary);
  13976. auto provider = detail::make_multipart_content_provider(items, boundary);
  13977. // Drive the provider the same way write_content_with_progress does
  13978. size_t write_count = 0;
  13979. size_t total_bytes = 0;
  13980. DataSink sink;
  13981. size_t offset = 0;
  13982. sink.write = [&](const char *d, size_t l) -> bool {
  13983. (void)d;
  13984. write_count++;
  13985. total_bytes += l;
  13986. offset += l;
  13987. return true;
  13988. };
  13989. sink.is_writable = []() -> bool { return true; };
  13990. while (offset < content_length) {
  13991. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13992. }
  13993. EXPECT_EQ(content_length, total_bytes);
  13994. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13995. // With buffering into 64KB blocks, write_count should be much smaller.
  13996. auto segment_count = 3 * kItemCount + 1;
  13997. EXPECT_LT(write_count, segment_count / 10);
  13998. }
  13999. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14000. // Integration test: send many UploadFormDataItems and verify the server
  14001. // receives all of them correctly (#2410).
  14002. constexpr size_t kItemCount = 500;
  14003. auto handled = false;
  14004. Server svr;
  14005. svr.Post("/upload", [&](const Request &req, Response &res) {
  14006. EXPECT_EQ(kItemCount, req.form.fields.size());
  14007. for (size_t i = 0; i < kItemCount; i++) {
  14008. auto key = "field" + std::to_string(i);
  14009. auto val = "value" + std::to_string(i);
  14010. auto it = req.form.fields.find(key);
  14011. if (it != req.form.fields.end()) {
  14012. EXPECT_EQ(val, it->second.content);
  14013. } else {
  14014. ADD_FAILURE() << "Missing field: " << key;
  14015. }
  14016. }
  14017. res.set_content("ok", "text/plain");
  14018. handled = true;
  14019. });
  14020. auto port = svr.bind_to_any_port(HOST);
  14021. auto t = thread([&] { svr.listen_after_bind(); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. ASSERT_TRUE(handled);
  14027. });
  14028. svr.wait_until_ready();
  14029. UploadFormDataItems items;
  14030. items.reserve(kItemCount);
  14031. for (size_t i = 0; i < kItemCount; i++) {
  14032. items.push_back(
  14033. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14034. }
  14035. Client cli(HOST, port);
  14036. auto res = cli.Post("/upload", items);
  14037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14038. EXPECT_EQ(StatusCode::OK_200, res->status);
  14039. }
  14040. TEST(MultipartFormDataTest, MakeFileProvider) {
  14041. // Verify make_file_provider sends a file's contents correctly.
  14042. const std::string file_content(4096, 'Z');
  14043. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14044. {
  14045. std::ofstream ofs(tmp_path, std::ios::binary);
  14046. ofs.write(file_content.data(),
  14047. static_cast<std::streamsize>(file_content.size()));
  14048. }
  14049. auto handled = false;
  14050. Server svr;
  14051. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14052. const ContentReader &content_reader) {
  14053. ASSERT_TRUE(req.is_multipart_form_data());
  14054. std::vector<FormData> items;
  14055. content_reader(
  14056. [&](const FormData &file) {
  14057. items.push_back(file);
  14058. return true;
  14059. },
  14060. [&](const char *data, size_t data_length) {
  14061. items.back().content.append(data, data_length);
  14062. return true;
  14063. });
  14064. ASSERT_EQ(1u, items.size());
  14065. EXPECT_EQ("myfile", items[0].name);
  14066. EXPECT_EQ("data.bin", items[0].filename);
  14067. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14068. EXPECT_EQ(file_content, items[0].content);
  14069. handled = true;
  14070. });
  14071. auto port = svr.bind_to_any_port(HOST);
  14072. auto t = thread([&] { svr.listen_after_bind(); });
  14073. auto se = detail::scope_exit([&] {
  14074. svr.stop();
  14075. t.join();
  14076. ASSERT_FALSE(svr.is_running());
  14077. ASSERT_TRUE(handled);
  14078. std::remove(tmp_path.c_str());
  14079. });
  14080. svr.wait_until_ready();
  14081. FormDataProviderItems providers;
  14082. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14083. "application/octet-stream"));
  14084. Client cli(HOST, port);
  14085. auto res = cli.Post("/upload", {}, {}, providers);
  14086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14087. EXPECT_EQ(StatusCode::OK_200, res->status);
  14088. }
  14089. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14090. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14091. // (100) headers is rejected with a 400 Bad Request response.
  14092. Server svr;
  14093. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14094. res.set_content("ok", "text/plain");
  14095. });
  14096. thread t = thread([&] { svr.listen(HOST, PORT); });
  14097. auto se = detail::scope_exit([&] {
  14098. svr.stop();
  14099. t.join();
  14100. ASSERT_FALSE(svr.is_running());
  14101. });
  14102. svr.wait_until_ready();
  14103. // Build a multipart part with 101 custom headers (exceeding
  14104. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14105. std::stringstream body;
  14106. body << "--simpleboundary\r\n"
  14107. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14108. for (int i = 0; i < 101; i++) {
  14109. body << "X-Custom-Header-" << i << ": value\r\n";
  14110. }
  14111. body << "\r\n"
  14112. << "value1\r\n"
  14113. << "--simpleboundary--\r\n";
  14114. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14115. Client cli(HOST, PORT);
  14116. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14119. }
  14120. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14121. // A body that never contains the declared boundary must not be accumulated
  14122. // while the parser waits for it. Buffering it would also make every read
  14123. // rescan everything seen so far, which is quadratic in the body size.
  14124. Server svr;
  14125. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14126. res.set_content("ok", "text/plain");
  14127. });
  14128. auto port = svr.bind_to_any_port(HOST);
  14129. thread t = thread([&] { svr.listen_after_bind(); });
  14130. auto se = detail::scope_exit([&] {
  14131. svr.stop();
  14132. t.join();
  14133. ASSERT_FALSE(svr.is_running());
  14134. });
  14135. svr.wait_until_ready();
  14136. Client cli(HOST, port);
  14137. cli.set_read_timeout(60, 0);
  14138. cli.set_write_timeout(60, 0);
  14139. // '-' is the worst case: it matches the first character of the boundary, so
  14140. // every position has to be checked against it.
  14141. auto post_dashes = [&](size_t size) {
  14142. const std::string body(size, '-');
  14143. auto start = std::chrono::steady_clock::now();
  14144. auto res =
  14145. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14146. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14147. std::chrono::steady_clock::now() - start)
  14148. .count();
  14149. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14150. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14151. return ms;
  14152. };
  14153. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14154. // Windows.
  14155. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14156. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14157. // Comparing the two sizes rather than checking an absolute duration keeps
  14158. // this meaningful across build types and CI load, both of which move the
  14159. // absolute numbers by more than an order of magnitude. Four times the bytes
  14160. // costs about four times the time when parsing is linear, and about sixteen
  14161. // times when the body is buffered and rescanned.
  14162. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14163. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14164. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14165. << "ms, which suggests the body is being buffered and rescanned";
  14166. }
  14167. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14168. // A boundary can only be followed by CRLF or by "--", so anything else is
  14169. // malformed no matter what comes next. The parser must say so right away
  14170. // instead of buffering the rest of the declared body.
  14171. Server svr;
  14172. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14173. res.set_content("ok", "text/plain");
  14174. });
  14175. auto port = svr.bind_to_any_port(HOST);
  14176. thread t = thread([&] { svr.listen_after_bind(); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. ASSERT_FALSE(svr.is_running());
  14181. });
  14182. svr.wait_until_ready();
  14183. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14184. // buffers instead of failing would still be waiting for the remaining bytes.
  14185. const std::string body = "--zzzz\r\n"
  14186. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14187. "\r\n"
  14188. "text1"
  14189. "\r\n--zzzzXX";
  14190. const std::string req = "POST /post HTTP/1.1\r\n"
  14191. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14192. "Content-Length: 1048576\r\n"
  14193. "\r\n" +
  14194. body;
  14195. std::string response;
  14196. ASSERT_TRUE(send_request(3, req, &response, port));
  14197. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14198. EXPECT_EQ("400", response.substr(9, 3));
  14199. }
  14200. // Posts a multipart body split into two writes, so that the server sees the
  14201. // split at whatever offset the caller chose, and expects the single "text1"
  14202. // field to come through.
  14203. static void expect_split_multipart_ok(const std::string &body1,
  14204. const std::string &body2) {
  14205. auto handled = false;
  14206. Server svr;
  14207. svr.Post("/post", [&](const Request &req, Response &) {
  14208. EXPECT_EQ(1u, req.form.fields.size());
  14209. EXPECT_EQ("text1", req.form.get_field("text1"));
  14210. handled = true;
  14211. });
  14212. auto port = svr.bind_to_any_port(HOST);
  14213. thread t = thread([&] { svr.listen_after_bind(); });
  14214. auto se = detail::scope_exit([&] {
  14215. svr.stop();
  14216. t.join();
  14217. ASSERT_FALSE(svr.is_running());
  14218. ASSERT_TRUE(handled);
  14219. });
  14220. svr.wait_until_ready();
  14221. // "Connection: close" makes the server close once it has answered, so the
  14222. // response drain ends immediately instead of idling until the read timeout.
  14223. const std::string head =
  14224. "POST /post HTTP/1.1\r\n"
  14225. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14226. "Connection: close\r\n"
  14227. "Content-Length: " +
  14228. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14229. std::string response;
  14230. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14231. ASSERT_GE(response.size(), 12u) << "no response";
  14232. EXPECT_EQ("200", response.substr(9, 3));
  14233. }
  14234. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14235. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14236. // ignored, including when it does not arrive in the same read as the
  14237. // close-delimiter itself.
  14238. expect_split_multipart_ok("--zzzz\r\n"
  14239. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14240. "\r\n"
  14241. "text1"
  14242. "\r\n--zzzz--",
  14243. "\r\nthis epilogue must be ignored\r\n");
  14244. }
  14245. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14246. // The initial boundary may be preceded by a preamble of any length and may
  14247. // straddle a read boundary. Discarding data while waiting for it must not
  14248. // throw away a partial boundary sitting at the end of the buffer.
  14249. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14250. "zz\r\n"
  14251. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14252. "\r\n"
  14253. "text1"
  14254. "\r\n--zzzz--\r\n");
  14255. }
  14256. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14257. // The received boundary was only checked for being non-empty, so it could be
  14258. // as long as a header is allowed to be. The parser scans the body for
  14259. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14260. // costs a nearly full comparison at nearly every position, making the
  14261. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14262. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14263. Server svr;
  14264. svr.Post("/post", [](const Request &req, Response &res) {
  14265. EXPECT_EQ(1u, req.form.fields.size());
  14266. EXPECT_EQ("text1", req.form.get_field("text1"));
  14267. res.set_content("ok", "text/plain");
  14268. });
  14269. auto port = svr.bind_to_any_port(HOST);
  14270. thread t = thread([&] { svr.listen_after_bind(); });
  14271. auto se = detail::scope_exit([&] {
  14272. svr.stop();
  14273. t.join();
  14274. ASSERT_FALSE(svr.is_running());
  14275. });
  14276. svr.wait_until_ready();
  14277. Client cli(HOST, port);
  14278. auto post_with_boundary_of_length = [&](size_t len) {
  14279. const std::string boundary(len, 'a');
  14280. const std::string body =
  14281. "--" + boundary +
  14282. "\r\n"
  14283. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14284. "\r\n"
  14285. "text1"
  14286. "\r\n--" +
  14287. boundary + "--\r\n";
  14288. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14289. };
  14290. auto res = post_with_boundary_of_length(70);
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. EXPECT_EQ(StatusCode::OK_200, res->status);
  14293. res = post_with_boundary_of_length(71);
  14294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14295. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14296. }
  14297. TEST(MakeFileBodyTest, Basic) {
  14298. const std::string file_content(4096, 'Z');
  14299. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14300. {
  14301. std::ofstream ofs(tmp_path, std::ios::binary);
  14302. ofs.write(file_content.data(),
  14303. static_cast<std::streamsize>(file_content.size()));
  14304. }
  14305. auto handled = false;
  14306. Server svr;
  14307. svr.Post("/upload", [&](const Request &req, Response &res) {
  14308. EXPECT_EQ(file_content, req.body);
  14309. handled = true;
  14310. res.status = StatusCode::OK_200;
  14311. });
  14312. auto port = svr.bind_to_any_port(HOST);
  14313. auto t = thread([&] { svr.listen_after_bind(); });
  14314. auto se = detail::scope_exit([&] {
  14315. svr.stop();
  14316. t.join();
  14317. ASSERT_FALSE(svr.is_running());
  14318. ASSERT_TRUE(handled);
  14319. std::remove(tmp_path.c_str());
  14320. });
  14321. svr.wait_until_ready();
  14322. auto fb = make_file_body(tmp_path);
  14323. ASSERT_GT(fb.first, 0u);
  14324. Client cli(HOST, port);
  14325. auto res =
  14326. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14328. EXPECT_EQ(StatusCode::OK_200, res->status);
  14329. }
  14330. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14331. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14332. {
  14333. std::ofstream ofs(path, std::ios::binary);
  14334. const std::string content(100, 'A');
  14335. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14336. }
  14337. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14338. auto body = make_file_body(path);
  14339. ASSERT_EQ(100u, body.first);
  14340. ASSERT_TRUE(static_cast<bool>(body.second));
  14341. // Rewritten shorter after its length was measured - and, on a server, after
  14342. // that length has already gone out as Content-Length.
  14343. {
  14344. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14345. const std::string content(10, 'A');
  14346. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14347. }
  14348. std::string written;
  14349. DataSink sink;
  14350. sink.write = [&](const char *d, size_t l) {
  14351. written.append(d, l);
  14352. return true;
  14353. };
  14354. // The provider has to report failure. write_content_with_progress() advances
  14355. // its offset only by what was written, so a provider that returns true
  14356. // without completing the length it promised is called again straight away,
  14357. // and again.
  14358. EXPECT_FALSE(body.second(0, body.first, sink));
  14359. EXPECT_EQ(std::string(10, 'A'), written);
  14360. }
  14361. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14362. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14363. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14364. {
  14365. std::ofstream ofs(path, std::ios::binary);
  14366. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14367. }
  14368. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14369. auto body = make_file_body(path);
  14370. ASSERT_EQ(content.size(), body.first);
  14371. ASSERT_TRUE(static_cast<bool>(body.second));
  14372. std::string written;
  14373. DataSink sink;
  14374. sink.write = [&](const char *d, size_t l) {
  14375. written.append(d, l);
  14376. return true;
  14377. };
  14378. EXPECT_TRUE(body.second(0, body.first, sink));
  14379. EXPECT_EQ(content, written);
  14380. }
  14381. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14382. static constexpr unsigned int number_of_tasks{1000000};
  14383. std::atomic_uint count{0};
  14384. std::unique_ptr<TaskQueue> task_queue{
  14385. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14386. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14387. auto queued = task_queue->enqueue(
  14388. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14389. EXPECT_TRUE(queued);
  14390. }
  14391. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14392. task_queue->shutdown();
  14393. #else
  14394. EXPECT_NO_THROW(task_queue->shutdown());
  14395. #endif
  14396. EXPECT_EQ(number_of_tasks, count.load());
  14397. }
  14398. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14399. static constexpr unsigned int number_of_tasks{1000000};
  14400. static constexpr unsigned int qlimit{2};
  14401. unsigned int queued_count{0};
  14402. std::atomic_uint count{0};
  14403. std::unique_ptr<TaskQueue> task_queue{
  14404. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14405. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14406. if (task_queue->enqueue(
  14407. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14408. queued_count++;
  14409. }
  14410. }
  14411. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14412. task_queue->shutdown();
  14413. #else
  14414. EXPECT_NO_THROW(task_queue->shutdown());
  14415. #endif
  14416. EXPECT_EQ(queued_count, count.load());
  14417. EXPECT_TRUE(queued_count <= number_of_tasks);
  14418. EXPECT_TRUE(queued_count >= qlimit);
  14419. }
  14420. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14421. // Use a short idle timeout so a dynamic thread spawns, times out and
  14422. // exits during the test, and the pool keeps working afterwards.
  14423. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14424. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14425. /*idle_timeout_sec=*/1}};
  14426. std::atomic_uint count{0};
  14427. std::condition_variable cv;
  14428. std::mutex mtx;
  14429. bool release = false;
  14430. // Block the base thread so the second task spawns a dynamic thread.
  14431. EXPECT_TRUE(task_queue->enqueue([&] {
  14432. std::unique_lock<std::mutex> lock(mtx);
  14433. while (!release) {
  14434. cv.wait(lock);
  14435. }
  14436. count++;
  14437. }));
  14438. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14439. // Let the dynamic thread finish its task and exceed the idle timeout.
  14440. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14441. {
  14442. std::unique_lock<std::mutex> lock(mtx);
  14443. release = true;
  14444. }
  14445. cv.notify_all();
  14446. // The pool must still accept and run tasks after the dynamic thread exited.
  14447. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14448. task_queue->shutdown();
  14449. EXPECT_EQ(3u, count.load());
  14450. }
  14451. TEST(TaskQueueTest, MaxQueuedRequests) {
  14452. static constexpr unsigned int qlimit{3};
  14453. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14454. std::condition_variable sem_cv;
  14455. std::mutex sem_mtx;
  14456. int credits = 0;
  14457. bool queued;
  14458. /* Fill up the queue with tasks that will block until we give them credits to
  14459. * complete. */
  14460. for (unsigned int n = 0; n <= qlimit;) {
  14461. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14462. std::unique_lock<std::mutex> lock(sem_mtx);
  14463. while (credits <= 0) {
  14464. sem_cv.wait(lock);
  14465. }
  14466. /* Consume the credit and signal the test code if they are all gone. */
  14467. if (--credits == 0) { sem_cv.notify_one(); }
  14468. });
  14469. if (n < qlimit) {
  14470. /* The first qlimit enqueues must succeed. */
  14471. EXPECT_TRUE(queued);
  14472. } else {
  14473. /* The last one will succeed only when the worker thread
  14474. * starts and dequeues the first blocking task. Although
  14475. * not necessary for the correctness of this test, we sleep for
  14476. * a short while to avoid busy waiting. */
  14477. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14478. }
  14479. if (queued) { n++; }
  14480. }
  14481. /* Further enqueues must fail since the queue is full. */
  14482. for (auto i = 0; i < 4; i++) {
  14483. queued = task_queue->enqueue([] {});
  14484. EXPECT_FALSE(queued);
  14485. }
  14486. /* Give the credits to allow the previous tasks to complete. */
  14487. {
  14488. std::unique_lock<std::mutex> lock(sem_mtx);
  14489. credits += qlimit + 1;
  14490. }
  14491. sem_cv.notify_all();
  14492. /* Wait for all the credits to be consumed. */
  14493. {
  14494. std::unique_lock<std::mutex> lock(sem_mtx);
  14495. while (credits > 0) {
  14496. sem_cv.wait(lock);
  14497. }
  14498. }
  14499. /* Check that we are able again to enqueue at least qlimit tasks. */
  14500. for (unsigned int i = 0; i < qlimit; i++) {
  14501. queued = task_queue->enqueue([] {});
  14502. EXPECT_TRUE(queued);
  14503. }
  14504. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14505. task_queue->shutdown();
  14506. #else
  14507. EXPECT_NO_THROW(task_queue->shutdown());
  14508. #endif
  14509. }
  14510. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14511. Server svr;
  14512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14513. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14514. });
  14515. svr.Get("/hello", [](const Request &req, Response &res) {
  14516. res.set_content(req.get_param_value("key"), "text/plain");
  14517. });
  14518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14519. auto se = detail::scope_exit([&] {
  14520. svr.stop();
  14521. thread.join();
  14522. ASSERT_FALSE(svr.is_running());
  14523. });
  14524. svr.wait_until_ready();
  14525. {
  14526. Client cli(HOST, PORT);
  14527. cli.set_follow_location(true);
  14528. auto res = cli.Get("/");
  14529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14530. EXPECT_EQ(StatusCode::OK_200, res->status);
  14531. EXPECT_EQ("val&key2=val2", res->body);
  14532. }
  14533. }
  14534. #endif
  14535. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14536. Server svr;
  14537. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14538. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14539. });
  14540. svr.Get("/hello", [](const Request &req, Response &res) {
  14541. res.set_content(req.get_param_value("key"), "text/plain");
  14542. });
  14543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14544. auto se = detail::scope_exit([&] {
  14545. svr.stop();
  14546. thread.join();
  14547. ASSERT_FALSE(svr.is_running());
  14548. });
  14549. svr.wait_until_ready();
  14550. {
  14551. Client cli(HOST, PORT);
  14552. cli.set_follow_location(true);
  14553. auto res = cli.Get("/");
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. EXPECT_EQ(StatusCode::OK_200, res->status);
  14556. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14557. }
  14558. }
  14559. TEST(RedirectTest, RedirectWithPlusInPath) {
  14560. Server svr;
  14561. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14562. res.set_redirect("/a+b");
  14563. });
  14564. // Route pattern uses regex; escape + as \\+
  14565. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14566. res.set_content(req.path, "text/plain");
  14567. });
  14568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14569. auto se = detail::scope_exit([&] {
  14570. svr.stop();
  14571. thread.join();
  14572. ASSERT_FALSE(svr.is_running());
  14573. });
  14574. svr.wait_until_ready();
  14575. {
  14576. Client cli(HOST, PORT);
  14577. cli.set_follow_location(true);
  14578. auto res = cli.Get("/");
  14579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14580. EXPECT_EQ(StatusCode::OK_200, res->status);
  14581. EXPECT_EQ("/a+b", res->body);
  14582. }
  14583. }
  14584. TEST(RedirectTest, ResolveRelativeLocation) {
  14585. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14586. const std::vector<std::pair<std::string, std::string>> cases = {
  14587. {"g", "/b/c/g"},
  14588. {"./g", "/b/c/g"},
  14589. {"g/", "/b/c/g/"},
  14590. {"?y", "/b/c/d;p?y"},
  14591. {"g?y", "/b/c/g?y"},
  14592. {"#s", "/b/c/d;p?q#s"},
  14593. {"g#s", "/b/c/g#s"},
  14594. {"g?y#s", "/b/c/g?y#s"},
  14595. {";x", "/b/c/;x"},
  14596. {"g;x", "/b/c/g;x"},
  14597. {".", "/b/c/"},
  14598. {"./", "/b/c/"},
  14599. {"..", "/b/"},
  14600. {"../", "/b/"},
  14601. {"../g", "/b/g"},
  14602. {"../..", "/"},
  14603. {"../../", "/"},
  14604. {"../../g", "/g"},
  14605. {"../../../g", "/g"},
  14606. {"g.", "/b/c/g."},
  14607. {".g", "/b/c/.g"},
  14608. {"g..", "/b/c/g.."},
  14609. {"..g", "/b/c/..g"},
  14610. {"./../g", "/b/g"},
  14611. {"./g/.", "/b/c/g/"},
  14612. {"g/./h", "/b/c/g/h"},
  14613. {"g/../h", "/b/c/h"},
  14614. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14615. {"g;x=1/../y", "/b/c/y"},
  14616. {"g?y/./x", "/b/c/g?y/./x"},
  14617. {"g#s/../x", "/b/c/g#s/../x"},
  14618. // Not relative-path references, so left for parse_url.
  14619. {"/g", "/g"},
  14620. {"//g", "//g"},
  14621. {"http://g/x", "http://g/x"},
  14622. {"g:h", "g:h"},
  14623. };
  14624. for (const auto &c : cases) {
  14625. EXPECT_EQ(c.second,
  14626. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14627. << c.first;
  14628. }
  14629. }
  14630. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14631. Server svr;
  14632. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14633. res.set_redirect(req.get_param_value("to"));
  14634. });
  14635. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14636. res.set_content(req.target, "text/plain");
  14637. });
  14638. svr.Get("/other", [](const Request &req, Response &res) {
  14639. res.set_content(req.target, "text/plain");
  14640. });
  14641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14642. auto se = detail::scope_exit([&] {
  14643. svr.stop();
  14644. thread.join();
  14645. ASSERT_FALSE(svr.is_running());
  14646. });
  14647. svr.wait_until_ready();
  14648. const std::vector<std::pair<std::string, std::string>> cases = {
  14649. {"next", "/dir/next"},
  14650. {"./next?x=1", "/dir/next?x=1"},
  14651. {"../other", "/other"},
  14652. };
  14653. for (const auto &c : cases) {
  14654. Client cli(HOST, PORT);
  14655. cli.set_follow_location(true);
  14656. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14657. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14658. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14659. EXPECT_EQ(c.second, res->body) << c.first;
  14660. }
  14661. }
  14662. #ifdef CPPHTTPLIB_SSL_ENABLED
  14663. TEST(RedirectTest, Issue2185_Online) {
  14664. SSLClient client("github.com");
  14665. client.set_follow_location(true);
  14666. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14667. "Coollab-Windows.zip");
  14668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14669. EXPECT_EQ(StatusCode::OK_200, res->status);
  14670. EXPECT_EQ(9920427U, res->body.size());
  14671. }
  14672. #endif
  14673. TEST(VulnerabilityTest, CRLFInjection) {
  14674. Server svr;
  14675. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14676. res.set_content("Hello 1", "text/plain");
  14677. });
  14678. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14679. res.set_content("Hello 2", "text/plain");
  14680. });
  14681. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14682. res.set_content("Hello 3", "text/plain");
  14683. });
  14684. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14685. res.set_content("Hello 4", "text/plain");
  14686. });
  14687. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14688. for (const auto &x : req.headers) {
  14689. auto key = x.first;
  14690. EXPECT_STRNE("evil", key.c_str());
  14691. }
  14692. });
  14693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14694. auto se = detail::scope_exit([&] {
  14695. svr.stop();
  14696. thread.join();
  14697. ASSERT_FALSE(svr.is_running());
  14698. });
  14699. svr.wait_until_ready();
  14700. {
  14701. Client cli(HOST, PORT);
  14702. cli.Post("/test1", "A=B",
  14703. "application/x-www-form-urlencoded\r\nevil: hello1");
  14704. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14705. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14706. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14707. }
  14708. }
  14709. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14710. auto server_thread = std::thread([] {
  14711. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14712. default_socket_options(srv);
  14713. sockaddr_in addr{};
  14714. addr.sin_family = AF_INET;
  14715. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14716. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14717. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14718. ::listen(srv, 1);
  14719. sockaddr_in cli_addr{};
  14720. socklen_t cli_len = sizeof(cli_addr);
  14721. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14722. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14723. std::string buf_all;
  14724. char buf[2048];
  14725. ssize_t n;
  14726. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14727. buf_all.append(buf, static_cast<size_t>(n));
  14728. size_t pos;
  14729. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14730. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14731. auto e = request_block.find("\r\n");
  14732. if (e != std::string::npos) {
  14733. auto request_line = request_block.substr(0, e);
  14734. std::string msg =
  14735. "CRLF injection detected in request line: '" + request_line + "'";
  14736. EXPECT_FALSE(true) << msg;
  14737. }
  14738. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14739. ::send(cli,
  14740. #ifdef _WIN32
  14741. static_cast<const char *>(resp.c_str()),
  14742. static_cast<int>(resp.size()),
  14743. #else
  14744. resp.c_str(), resp.size(),
  14745. #endif
  14746. 0);
  14747. buf_all.erase(0, pos + 4);
  14748. }
  14749. }
  14750. detail::close_socket(cli);
  14751. detail::close_socket(srv);
  14752. });
  14753. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14754. auto cli = Client("127.0.0.1", PORT + 1);
  14755. auto headers = Headers{
  14756. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14757. {"Connection", "keep-alive"}};
  14758. auto res = cli.Get("/hi", headers);
  14759. EXPECT_FALSE(res);
  14760. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14761. server_thread.join();
  14762. }
  14763. // A request rejected before any byte reaches the socket must fail right away
  14764. // instead of waiting for a response the server will never send.
  14765. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14766. // The kernel completes the TCP handshake from the listen backlog, so the
  14767. // client connects, but nothing ever reads, responds or closes.
  14768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14769. default_socket_options(srv);
  14770. sockaddr_in addr{};
  14771. addr.sin_family = AF_INET;
  14772. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14773. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14774. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14775. ASSERT_EQ(0, ::listen(srv, 8));
  14776. auto cli = Client("127.0.0.1", PORT + 1);
  14777. cli.set_read_timeout(10, 0);
  14778. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14779. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14780. std::chrono::steady_clock::now() - start)
  14781. .count();
  14782. };
  14783. {
  14784. Request req;
  14785. req.method = "GE T";
  14786. req.path = "/";
  14787. auto start = std::chrono::steady_clock::now();
  14788. auto res = cli.send(req);
  14789. EXPECT_FALSE(res);
  14790. EXPECT_EQ(Error::Write, res.error());
  14791. EXPECT_LT(elapsed_ms(start), 1000);
  14792. }
  14793. {
  14794. auto start = std::chrono::steady_clock::now();
  14795. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14796. EXPECT_FALSE(res);
  14797. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14798. EXPECT_LT(elapsed_ms(start), 1000);
  14799. }
  14800. EXPECT_FALSE(cli.is_socket_open());
  14801. detail::close_socket(srv);
  14802. }
  14803. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14804. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14805. default_socket_options(srv);
  14806. sockaddr_in addr{};
  14807. addr.sin_family = AF_INET;
  14808. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14809. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14810. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14811. ASSERT_EQ(0, ::listen(srv, 1));
  14812. std::string received;
  14813. auto server_thread = std::thread([&] {
  14814. auto sock = ::accept(srv, nullptr, nullptr);
  14815. if (sock == INVALID_SOCKET) { return; }
  14816. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14817. char buf[2048];
  14818. ssize_t n;
  14819. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14820. received.append(buf, static_cast<size_t>(n));
  14821. }
  14822. detail::close_socket(sock);
  14823. });
  14824. {
  14825. auto cli = Client("127.0.0.1", PORT + 1);
  14826. // "Z" sorts after the default headers, so writing straight to the socket
  14827. // would have sent the request line and those headers before the rejection.
  14828. auto handle =
  14829. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14830. EXPECT_FALSE(handle.is_valid());
  14831. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14832. }
  14833. server_thread.join();
  14834. detail::close_socket(srv);
  14835. EXPECT_TRUE(received.empty()) << received;
  14836. }
  14837. TEST(PathParamsTest, StaticMatch) {
  14838. const auto pattern = "/users/all";
  14839. detail::PathParamsMatcher matcher(pattern);
  14840. Request request;
  14841. request.path = "/users/all";
  14842. ASSERT_TRUE(matcher.match(request));
  14843. std::unordered_map<std::string, std::string> expected_params = {};
  14844. EXPECT_EQ(request.path_params, expected_params);
  14845. }
  14846. TEST(PathParamsTest, StaticMismatch) {
  14847. const auto pattern = "/users/all";
  14848. detail::PathParamsMatcher matcher(pattern);
  14849. Request request;
  14850. request.path = "/users/1";
  14851. ASSERT_FALSE(matcher.match(request));
  14852. }
  14853. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14854. const auto pattern = "/users/:id/subscriptions";
  14855. detail::PathParamsMatcher matcher(pattern);
  14856. Request request;
  14857. request.path = "/users/42/subscriptions";
  14858. ASSERT_TRUE(matcher.match(request));
  14859. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14860. EXPECT_EQ(request.path_params, expected_params);
  14861. }
  14862. TEST(PathParamsTest, SingleParamInTheEnd) {
  14863. const auto pattern = "/users/:id";
  14864. detail::PathParamsMatcher matcher(pattern);
  14865. Request request;
  14866. request.path = "/users/24";
  14867. ASSERT_TRUE(matcher.match(request));
  14868. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14869. EXPECT_EQ(request.path_params, expected_params);
  14870. }
  14871. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14872. const auto pattern = "/users/:id/";
  14873. detail::PathParamsMatcher matcher(pattern);
  14874. Request request;
  14875. request.path = "/users/42/";
  14876. ASSERT_TRUE(matcher.match(request));
  14877. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14878. EXPECT_EQ(request.path_params, expected_params);
  14879. }
  14880. TEST(PathParamsTest, EmptyParam) {
  14881. const auto pattern = "/users/:id/";
  14882. detail::PathParamsMatcher matcher(pattern);
  14883. Request request;
  14884. request.path = "/users//";
  14885. ASSERT_TRUE(matcher.match(request));
  14886. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14887. EXPECT_EQ(request.path_params, expected_params);
  14888. }
  14889. TEST(PathParamsTest, FragmentMismatch) {
  14890. const auto pattern = "/users/:id/";
  14891. detail::PathParamsMatcher matcher(pattern);
  14892. Request request;
  14893. request.path = "/admins/24/";
  14894. ASSERT_FALSE(matcher.match(request));
  14895. }
  14896. TEST(PathParamsTest, ExtraFragments) {
  14897. const auto pattern = "/users/:id";
  14898. detail::PathParamsMatcher matcher(pattern);
  14899. Request request;
  14900. request.path = "/users/42/subscriptions";
  14901. ASSERT_FALSE(matcher.match(request));
  14902. }
  14903. TEST(PathParamsTest, MissingTrailingParam) {
  14904. const auto pattern = "/users/:id";
  14905. detail::PathParamsMatcher matcher(pattern);
  14906. Request request;
  14907. request.path = "/users";
  14908. ASSERT_FALSE(matcher.match(request));
  14909. }
  14910. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14911. const auto pattern = "/users/:id/subscriptions";
  14912. detail::PathParamsMatcher matcher(pattern);
  14913. Request request;
  14914. request.path = "/users/subscriptions";
  14915. ASSERT_FALSE(matcher.match(request));
  14916. }
  14917. TEST(PathParamsTest, MultipleParams) {
  14918. const auto pattern = "/users/:userid/subscriptions/:subid";
  14919. detail::PathParamsMatcher matcher(pattern);
  14920. Request request;
  14921. request.path = "/users/42/subscriptions/2";
  14922. ASSERT_TRUE(matcher.match(request));
  14923. std::unordered_map<std::string, std::string> expected_params = {
  14924. {"userid", "42"}, {"subid", "2"}};
  14925. EXPECT_EQ(request.path_params, expected_params);
  14926. }
  14927. TEST(PathParamsTest, SequenceOfParams) {
  14928. const auto pattern = "/values/:x/:y/:z";
  14929. detail::PathParamsMatcher matcher(pattern);
  14930. Request request;
  14931. request.path = "/values/1/2/3";
  14932. ASSERT_TRUE(matcher.match(request));
  14933. std::unordered_map<std::string, std::string> expected_params = {
  14934. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14935. EXPECT_EQ(request.path_params, expected_params);
  14936. }
  14937. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14938. const auto pattern = "/prefix:suffix";
  14939. detail::PathParamsMatcher matcher(pattern);
  14940. Request request;
  14941. request.path = "/prefix:suffix";
  14942. ASSERT_TRUE(matcher.match(request));
  14943. const std::unordered_map<std::string, std::string> expected_params = {};
  14944. EXPECT_EQ(request.path_params, expected_params);
  14945. }
  14946. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14947. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14948. // calling thread's stack on a long enough path for a quantified pattern;
  14949. // RegexMatcher must refuse to run regex matching on paths beyond
  14950. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14951. detail::RegexMatcher matcher("/files/(.*)");
  14952. Request within_limit;
  14953. within_limit.path = "/files/" + std::string(10, 'A');
  14954. EXPECT_TRUE(matcher.match(within_limit));
  14955. Request over_limit;
  14956. over_limit.path =
  14957. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14958. EXPECT_FALSE(matcher.match(over_limit));
  14959. }
  14960. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14961. Server svr;
  14962. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14963. res.set_content("ok", "text/plain");
  14964. });
  14965. auto port = svr.bind_to_any_port(HOST);
  14966. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14967. auto se = detail::scope_exit([&] {
  14968. svr.stop();
  14969. thread.join();
  14970. ASSERT_FALSE(svr.is_running());
  14971. });
  14972. svr.wait_until_ready();
  14973. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14974. // request URI limit; this used to be able to crash the process.
  14975. std::string path =
  14976. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14977. std::string req = "GET " + path +
  14978. " HTTP/1.1\r\n"
  14979. "Host: " +
  14980. std::string(HOST) + ":" + std::to_string(port) +
  14981. "\r\n"
  14982. "Connection: close\r\n"
  14983. "\r\n";
  14984. std::string response;
  14985. ASSERT_TRUE(send_request(5, req, &response, port));
  14986. EXPECT_NE(std::string::npos, response.find("404"));
  14987. }
  14988. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14989. Server svr;
  14990. auto handler = [](const Request & /*req*/, Response &res) {
  14991. res.set_content("hit", "text/plain");
  14992. };
  14993. // No regex metacharacter, so this one is compared literally
  14994. svr.Get("/literal/route", handler);
  14995. // '.' is a regex metacharacter, so this one must keep regex semantics
  14996. svr.Get("/a.c", handler);
  14997. auto port = svr.bind_to_any_port(HOST);
  14998. std::thread t([&]() { svr.listen_after_bind(); });
  14999. auto se = detail::scope_exit([&] {
  15000. svr.stop();
  15001. t.join();
  15002. ASSERT_FALSE(svr.is_running());
  15003. });
  15004. svr.wait_until_ready();
  15005. Client cli(HOST, port);
  15006. struct {
  15007. const char *path;
  15008. int status;
  15009. } cases[] = {
  15010. {"/literal/route", StatusCode::OK_200},
  15011. {"/literal/routes", StatusCode::NotFound_404},
  15012. {"/literal/rout", StatusCode::NotFound_404},
  15013. {"/abc", StatusCode::OK_200},
  15014. {"/a.c", StatusCode::OK_200},
  15015. };
  15016. for (const auto &x : cases) {
  15017. auto res = cli.Get(x.path);
  15018. ASSERT_TRUE(res) << x.path;
  15019. EXPECT_EQ(x.status, res->status) << x.path;
  15020. }
  15021. }
  15022. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15023. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15024. // from exhausting the stack, so it must only constrain routes that actually
  15025. // run a regular expression. A literal route is matched by comparison and
  15026. // stays usable at any length.
  15027. Server svr;
  15028. const std::string pattern =
  15029. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15030. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15031. res.set_content("hit", "text/plain");
  15032. });
  15033. auto port = svr.bind_to_any_port(HOST);
  15034. std::thread t([&]() { svr.listen_after_bind(); });
  15035. auto se = detail::scope_exit([&] {
  15036. svr.stop();
  15037. t.join();
  15038. ASSERT_FALSE(svr.is_running());
  15039. });
  15040. svr.wait_until_ready();
  15041. Client cli(HOST, port);
  15042. auto res = cli.Get(pattern);
  15043. ASSERT_TRUE(res);
  15044. EXPECT_EQ(StatusCode::OK_200, res->status);
  15045. }
  15046. TEST(ParseUrlTest, VariousPatterns) {
  15047. {
  15048. detail::UrlComponents uc;
  15049. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15050. EXPECT_EQ("http", uc.scheme);
  15051. EXPECT_EQ("example.com", uc.host);
  15052. EXPECT_EQ("8080", uc.port);
  15053. EXPECT_EQ("/path", uc.path);
  15054. EXPECT_EQ("?q=1", uc.query);
  15055. }
  15056. {
  15057. detail::UrlComponents uc;
  15058. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15059. EXPECT_EQ("https", uc.scheme);
  15060. EXPECT_EQ("example.com", uc.host);
  15061. EXPECT_TRUE(uc.port.empty());
  15062. EXPECT_EQ("/path", uc.path);
  15063. }
  15064. {
  15065. detail::UrlComponents uc;
  15066. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15067. EXPECT_EQ("::1", uc.host);
  15068. EXPECT_EQ("8080", uc.port);
  15069. EXPECT_EQ("/path", uc.path);
  15070. }
  15071. {
  15072. detail::UrlComponents uc;
  15073. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15074. }
  15075. {
  15076. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15077. // the path while the connection still targets the bracketed host.
  15078. detail::UrlComponents uc;
  15079. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15080. }
  15081. {
  15082. detail::UrlComponents uc;
  15083. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15084. }
  15085. {
  15086. detail::UrlComponents uc;
  15087. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15088. EXPECT_EQ("::1", uc.host);
  15089. EXPECT_TRUE(uc.port.empty());
  15090. EXPECT_EQ("/path", uc.path);
  15091. }
  15092. {
  15093. detail::UrlComponents uc;
  15094. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15095. EXPECT_TRUE(uc.scheme.empty());
  15096. EXPECT_EQ("example.com", uc.host);
  15097. EXPECT_EQ("/path", uc.path);
  15098. EXPECT_EQ("?q=1", uc.query);
  15099. }
  15100. {
  15101. detail::UrlComponents uc;
  15102. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15103. EXPECT_TRUE(uc.host.empty());
  15104. EXPECT_EQ("/path", uc.path);
  15105. EXPECT_EQ("?q=1", uc.query);
  15106. }
  15107. {
  15108. detail::UrlComponents uc;
  15109. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15110. EXPECT_EQ("example.com", uc.host);
  15111. EXPECT_EQ("8080", uc.port);
  15112. }
  15113. {
  15114. // Unix socket path — must not be parsed as host
  15115. detail::UrlComponents uc;
  15116. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15117. EXPECT_TRUE(uc.host.empty());
  15118. }
  15119. {
  15120. detail::UrlComponents uc;
  15121. ASSERT_TRUE(detail::parse_url("", uc));
  15122. EXPECT_TRUE(uc.host.empty());
  15123. EXPECT_TRUE(uc.path.empty());
  15124. }
  15125. {
  15126. detail::UrlComponents uc;
  15127. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15128. }
  15129. {
  15130. detail::UrlComponents uc;
  15131. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15132. }
  15133. {
  15134. // Accepted by parse_url; callers restrict to http/https
  15135. detail::UrlComponents uc;
  15136. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15137. EXPECT_EQ("ftp", uc.scheme);
  15138. }
  15139. {
  15140. detail::UrlComponents uc;
  15141. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15142. }
  15143. {
  15144. detail::UrlComponents uc;
  15145. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15146. }
  15147. }
  15148. TEST(ParseUrlTest, FragmentHandling) {
  15149. {
  15150. detail::UrlComponents uc;
  15151. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15152. EXPECT_EQ("/path", uc.path);
  15153. EXPECT_TRUE(uc.query.empty());
  15154. }
  15155. {
  15156. detail::UrlComponents uc;
  15157. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15158. EXPECT_TRUE(uc.path.empty());
  15159. EXPECT_TRUE(uc.query.empty());
  15160. }
  15161. }
  15162. TEST(ParseUrlTest, UserinfoHandling) {
  15163. // Userinfo with @ but no colon — host includes @
  15164. detail::UrlComponents uc;
  15165. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15166. EXPECT_EQ("user@host.com", uc.host);
  15167. EXPECT_EQ("/path", uc.path);
  15168. }
  15169. TEST(ParseUrlTest, IPv6EdgeCases) {
  15170. {
  15171. detail::UrlComponents uc;
  15172. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15173. EXPECT_TRUE(uc.scheme.empty());
  15174. EXPECT_EQ("::1", uc.host);
  15175. EXPECT_EQ("8080", uc.port);
  15176. }
  15177. {
  15178. // Zone ID '%25' is not in [a-fA-F0-9:]
  15179. detail::UrlComponents uc;
  15180. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15181. }
  15182. }
  15183. TEST(ParseUrlTest, SchemeEdgeCases) {
  15184. {
  15185. detail::UrlComponents uc;
  15186. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15187. }
  15188. {
  15189. detail::UrlComponents uc;
  15190. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15191. }
  15192. {
  15193. detail::UrlComponents uc;
  15194. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15195. }
  15196. }
  15197. TEST(ParseUrlTest, PortEdgeCases) {
  15198. {
  15199. detail::UrlComponents uc;
  15200. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15201. EXPECT_TRUE(uc.port.empty());
  15202. EXPECT_EQ("/path", uc.path);
  15203. }
  15204. {
  15205. // parse_url accepts any port string; validation is done by parse_port
  15206. detail::UrlComponents uc;
  15207. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15208. EXPECT_EQ("abc", uc.port);
  15209. }
  15210. }
  15211. TEST(ParseUrlTest, WebSocketPatterns) {
  15212. {
  15213. detail::UrlComponents uc;
  15214. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15215. EXPECT_EQ("ws", uc.scheme);
  15216. EXPECT_EQ("echo.example.com", uc.host);
  15217. EXPECT_EQ("8080", uc.port);
  15218. EXPECT_EQ("/ws", uc.path);
  15219. }
  15220. {
  15221. detail::UrlComponents uc;
  15222. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15223. EXPECT_EQ("wss", uc.scheme);
  15224. EXPECT_EQ("echo.example.com", uc.host);
  15225. EXPECT_TRUE(uc.port.empty());
  15226. EXPECT_EQ("/ws", uc.path);
  15227. }
  15228. }
  15229. TEST(ParseUrlTest, QueryOnly) {
  15230. detail::UrlComponents uc;
  15231. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15232. EXPECT_TRUE(uc.host.empty());
  15233. EXPECT_TRUE(uc.path.empty());
  15234. EXPECT_EQ("?q=1&r=2", uc.query);
  15235. }
  15236. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15237. detail::UrlComponents uc;
  15238. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15239. EXPECT_TRUE(uc.scheme.empty());
  15240. EXPECT_EQ("example.com", uc.host);
  15241. EXPECT_EQ("443", uc.port);
  15242. EXPECT_EQ("/path", uc.path);
  15243. }
  15244. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15245. // If ipv6 regex working, regex match codepath is taken.
  15246. // else port will default to 80 in Client impl
  15247. int clientImplMagicPort = 80;
  15248. int port = 4321;
  15249. // above ports must be different to avoid false negative
  15250. EXPECT_NE(clientImplMagicPort, port);
  15251. std::string ipV6TestURL = "http://[ff06::c3]";
  15252. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15253. CLIENT_PRIVATE_KEY_FILE);
  15254. EXPECT_EQ(cli.port(), port);
  15255. }
  15256. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15257. auto file_path = "./www/dir/index.html";
  15258. auto dir_path = "./www/dir";
  15259. detail::FileStat stat_file(file_path);
  15260. EXPECT_TRUE(stat_file.is_file());
  15261. EXPECT_FALSE(stat_file.is_dir());
  15262. detail::FileStat stat_dir(dir_path);
  15263. EXPECT_FALSE(stat_dir.is_file());
  15264. EXPECT_TRUE(stat_dir.is_dir());
  15265. }
  15266. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15267. // IPv4 with default HTTP port (80)
  15268. EXPECT_EQ("example.com",
  15269. detail::make_host_and_port_string("example.com", 80, false));
  15270. // IPv4 with default HTTPS port (443)
  15271. EXPECT_EQ("example.com",
  15272. detail::make_host_and_port_string("example.com", 443, true));
  15273. // IPv4 with non-default HTTP port
  15274. EXPECT_EQ("example.com:8080",
  15275. detail::make_host_and_port_string("example.com", 8080, false));
  15276. // IPv4 with non-default HTTPS port
  15277. EXPECT_EQ("example.com:8443",
  15278. detail::make_host_and_port_string("example.com", 8443, true));
  15279. // IPv6 with default HTTP port (80)
  15280. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15281. // IPv6 with default HTTPS port (443)
  15282. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15283. // IPv6 with non-default HTTP port
  15284. EXPECT_EQ("[::1]:8080",
  15285. detail::make_host_and_port_string("::1", 8080, false));
  15286. // IPv6 with non-default HTTPS port
  15287. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15288. // IPv6 full address with default port
  15289. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15290. detail::make_host_and_port_string(
  15291. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15292. // IPv6 full address with non-default port
  15293. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15294. detail::make_host_and_port_string(
  15295. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15296. // IPv6 localhost with non-default port
  15297. EXPECT_EQ("[::1]:3000",
  15298. detail::make_host_and_port_string("::1", 3000, false));
  15299. // IPv6 with zone ID (link-local address) with default port
  15300. EXPECT_EQ("[fe80::1%eth0]",
  15301. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15302. // IPv6 with zone ID (link-local address) with non-default port
  15303. EXPECT_EQ("[fe80::1%eth0]:8080",
  15304. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15305. // Edge case: Port 443 with is_ssl=false (should add port)
  15306. EXPECT_EQ("example.com:443",
  15307. detail::make_host_and_port_string("example.com", 443, false));
  15308. // Edge case: Port 80 with is_ssl=true (should add port)
  15309. EXPECT_EQ("example.com:80",
  15310. detail::make_host_and_port_string("example.com", 80, true));
  15311. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15312. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15313. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15314. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15315. // Security fix: Already bracketed IPv6 should not get double brackets
  15316. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15317. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15318. EXPECT_EQ("[::1]:8080",
  15319. detail::make_host_and_port_string("[::1]", 8080, false));
  15320. EXPECT_EQ("[2001:db8::1]:8080",
  15321. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15322. EXPECT_EQ("[fe80::1%eth0]",
  15323. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15324. EXPECT_EQ("[fe80::1%eth0]:8080",
  15325. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15326. // Edge case: Empty host (should return as-is)
  15327. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15328. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15329. // This is a known limitation but shouldn't crash
  15330. EXPECT_EQ("[host:name]",
  15331. detail::make_host_and_port_string("host:name", 80, false));
  15332. // Port number edge cases (no validation, but should not crash)
  15333. EXPECT_EQ("example.com:0",
  15334. detail::make_host_and_port_string("example.com", 0, false));
  15335. EXPECT_EQ("example.com:-1",
  15336. detail::make_host_and_port_string("example.com", -1, false));
  15337. EXPECT_EQ("example.com:65535",
  15338. detail::make_host_and_port_string("example.com", 65535, false));
  15339. EXPECT_EQ("example.com:65536",
  15340. detail::make_host_and_port_string("example.com", 65536, false));
  15341. }
  15342. #ifdef CPPHTTPLIB_SSL_ENABLED
  15343. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15344. httplib::SSLClient cli("roblox.com", 443);
  15345. cli.set_follow_location(true);
  15346. auto res = cli.Get("/");
  15347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15348. EXPECT_EQ(StatusCode::OK_200, res->status);
  15349. }
  15350. #endif
  15351. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15352. Server svr;
  15353. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15354. EXPECT_EQ(res.status, 400);
  15355. });
  15356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15357. auto se = detail::scope_exit([&] {
  15358. svr.stop();
  15359. thread.join();
  15360. ASSERT_FALSE(svr.is_running());
  15361. });
  15362. svr.wait_until_ready();
  15363. Client cli(HOST, PORT);
  15364. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15365. }
  15366. TEST(InvalidHeaderCharsTest, is_field_name) {
  15367. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15368. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15369. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15370. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15371. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15372. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15373. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15374. EXPECT_FALSE(detail::fields::is_field_name(""));
  15375. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15376. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15377. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15378. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15379. }
  15380. TEST(InvalidHeaderCharsTest, is_field_value) {
  15381. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15382. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15383. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15384. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15385. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15386. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15387. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15388. EXPECT_TRUE(detail::fields::is_field_value(""));
  15389. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15390. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15391. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15392. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15393. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15394. }
  15395. TEST(InvalidHeaderCharsTest, OnServer) {
  15396. Server svr;
  15397. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15398. std::string header = "Not Set";
  15399. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15400. res.set_header(header, "value");
  15401. res.set_content("Page Content Page Content", "text/plain");
  15402. });
  15403. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15404. std::string header = "Not Set";
  15405. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15406. res.set_header("X-Test", header);
  15407. res.set_content("Page Content Page Content", "text/plain");
  15408. });
  15409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15410. auto se = detail::scope_exit([&] {
  15411. svr.stop();
  15412. thread.join();
  15413. ASSERT_FALSE(svr.is_running());
  15414. });
  15415. svr.wait_until_ready();
  15416. Client cli(HOST, PORT);
  15417. {
  15418. auto res = cli.Get(
  15419. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15421. EXPECT_EQ("Page Content Page Content", res->body);
  15422. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15423. }
  15424. {
  15425. auto res = cli.Get(
  15426. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15428. EXPECT_EQ("Page Content Page Content", res->body);
  15429. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15430. }
  15431. }
  15432. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15433. auto handled = false;
  15434. Server svr;
  15435. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15436. thread t = thread([&] { svr.listen(HOST, PORT); });
  15437. auto se = detail::scope_exit([&] {
  15438. svr.stop();
  15439. t.join();
  15440. ASSERT_FALSE(svr.is_running());
  15441. ASSERT_FALSE(handled);
  15442. });
  15443. svr.wait_until_ready();
  15444. auto req = "POST /test HTTP/1.1\r\n"
  15445. "Content-Length: x\r\n"
  15446. "\r\n";
  15447. std::string response;
  15448. ASSERT_TRUE(send_request(1, req, &response));
  15449. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15450. response.substr(0, response.find("\r\n")));
  15451. }
  15452. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15453. // case-insensitive, and a server that receives a 100-continue expectation in
  15454. // an HTTP/1.0 request MUST ignore it.
  15455. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15456. std::string response;
  15457. ASSERT_TRUE(send_request(1, req, &response, port));
  15458. *got_100 = response.find("100 Continue") != std::string::npos;
  15459. }
  15460. class ExpectTokenTest : public ::testing::Test {
  15461. protected:
  15462. void SetUp() override {
  15463. svr_.Post("/p", [](const Request &, Response &res) {
  15464. res.set_content("ok", "text/plain");
  15465. });
  15466. port_ = svr_.bind_to_any_port(HOST);
  15467. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15468. svr_.wait_until_ready();
  15469. }
  15470. void TearDown() override {
  15471. svr_.stop();
  15472. if (thread_.joinable()) { thread_.join(); }
  15473. }
  15474. std::string request(const char *version, const char *expect_value) const {
  15475. return std::string("POST /p ") + version +
  15476. "\r\n"
  15477. "Host: localhost\r\n"
  15478. "Content-Length: 2\r\n"
  15479. "Connection: close\r\n"
  15480. "Expect: " +
  15481. expect_value +
  15482. "\r\n"
  15483. "\r\n"
  15484. "hi";
  15485. }
  15486. Server svr_;
  15487. int port_ = 0;
  15488. thread thread_;
  15489. };
  15490. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15491. bool got_100 = false;
  15492. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15493. EXPECT_TRUE(got_100);
  15494. }
  15495. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15496. bool got_100 = true;
  15497. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15498. EXPECT_FALSE(got_100);
  15499. }
  15500. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15501. bool got_100 = false;
  15502. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15503. EXPECT_TRUE(got_100);
  15504. }
  15505. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15506. bool got_100 = false;
  15507. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15508. EXPECT_TRUE(got_100);
  15509. }
  15510. // `100 Continue` is sent only when the server starts reading the body, so a
  15511. // request rejected before that never invites the client to send it. The
  15512. // requests below carry the expectation but withhold the body, as a client
  15513. // waiting for `100 Continue` would.
  15514. // A POST that expects `100 Continue` and withholds its two-byte body.
  15515. static std::string expect_headers_only(const std::string &path) {
  15516. return "POST " + path +
  15517. " HTTP/1.1\r\n"
  15518. "Host: localhost\r\n"
  15519. "Content-Length: 2\r\n"
  15520. "Expect: 100-continue\r\n"
  15521. "\r\n";
  15522. }
  15523. class ExpectLazyContinueTest : public ::testing::Test {
  15524. protected:
  15525. void SetUp() override {
  15526. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15527. if (req.path == "/pre-routing") {
  15528. res.status = StatusCode::Unauthorized_401;
  15529. return Server::HandlerResponse::Handled;
  15530. }
  15531. return Server::HandlerResponse::Unhandled;
  15532. });
  15533. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15534. if (req.matched_route == "/pre-request") {
  15535. res.status = StatusCode::Forbidden_403;
  15536. return Server::HandlerResponse::Handled;
  15537. }
  15538. return Server::HandlerResponse::Unhandled;
  15539. });
  15540. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15541. res.set_content("ok", "text/plain");
  15542. });
  15543. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15544. res.set_content("ok", "text/plain");
  15545. });
  15546. svr_.Post("/reader-used", [](const Request &, Response &res,
  15547. const ContentReader &content_reader) {
  15548. std::string body;
  15549. content_reader([&](const char *data, size_t len) {
  15550. body.append(data, len);
  15551. return true;
  15552. });
  15553. res.set_content(body, "text/plain");
  15554. });
  15555. svr_.Post("/reader-unused",
  15556. [](const Request &, Response &res, const ContentReader &) {
  15557. res.set_content("ignored", "text/plain");
  15558. });
  15559. port_ = svr_.bind_to_any_port(HOST);
  15560. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15561. svr_.wait_until_ready();
  15562. }
  15563. void TearDown() override {
  15564. svr_.stop();
  15565. if (thread_.joinable()) { thread_.join(); }
  15566. }
  15567. // Sends `req` and reads until the server closes the connection. Returns
  15568. // false if the read had to wait for the client-side timeout instead.
  15569. bool send_until_closed(const std::string &req, std::string *resp) const {
  15570. auto start = std::chrono::steady_clock::now();
  15571. if (!send_request(3, req, resp, port_)) { return false; }
  15572. auto elapsed = std::chrono::steady_clock::now() - start;
  15573. return elapsed < std::chrono::seconds(2);
  15574. }
  15575. // The final response comes without `100 Continue`, and the server closes
  15576. // the connection since the body may or may not follow.
  15577. void expect_final_without_interim(const std::string &path,
  15578. const char *status_line) const {
  15579. std::string resp;
  15580. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15581. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15582. EXPECT_EQ(0u, resp.find(status_line));
  15583. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15584. }
  15585. Server svr_;
  15586. int port_ = 0;
  15587. thread thread_;
  15588. };
  15589. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15590. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15591. }
  15592. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15593. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15594. }
  15595. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15596. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15597. }
  15598. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15599. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15600. }
  15601. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15602. // The body follows once `100 Continue` has had time to arrive.
  15603. auto req = expect_headers_only("/reader-used");
  15604. req.insert(req.size() - 2, "Connection: close\r\n");
  15605. std::string resp;
  15606. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15607. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15608. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15609. EXPECT_NE(std::string::npos, resp.find("hi"));
  15610. }
  15611. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15612. // Large enough for the client to add `Expect: 100-continue` itself.
  15613. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15614. std::atomic<bool> body_sent{false};
  15615. Client cli(HOST, port_);
  15616. auto res = cli.Post(
  15617. "/pre-request", length,
  15618. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15619. body_sent = true;
  15620. std::string chunk(len, 'x');
  15621. sink.write(chunk.data(), chunk.size());
  15622. return true;
  15623. },
  15624. "application/octet-stream");
  15625. ASSERT_TRUE(res);
  15626. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15627. EXPECT_FALSE(body_sent);
  15628. }
  15629. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15630. Server svr;
  15631. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15632. return StatusCode::ExpectationFailed_417;
  15633. });
  15634. svr.Post("/p", [](const Request &, Response &res) {
  15635. res.set_content("ok", "text/plain");
  15636. });
  15637. auto port = svr.bind_to_any_port(HOST);
  15638. thread t = thread([&] { svr.listen_after_bind(); });
  15639. auto se = detail::scope_exit([&] {
  15640. svr.stop();
  15641. t.join();
  15642. });
  15643. svr.wait_until_ready();
  15644. std::string resp;
  15645. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15646. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15647. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15648. // Exactly one response: the route handler must not run after the 417.
  15649. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15650. }
  15651. #ifndef _WIN32
  15652. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15653. static constexpr char reject[] = "Unauthorized";
  15654. static constexpr char accept[] = "Upload accepted";
  15655. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15656. Server svr;
  15657. svr.set_expect_100_continue_handler(
  15658. [](const Request & /*req*/, Response &res) {
  15659. res.status = StatusCode::Unauthorized_401;
  15660. res.set_content(reject, "text/plain");
  15661. return res.status;
  15662. });
  15663. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15664. res.set_content(accept, "text/plain");
  15665. });
  15666. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15667. auto se = detail::scope_exit([&] {
  15668. svr.stop();
  15669. thread.join();
  15670. ASSERT_FALSE(svr.is_running());
  15671. });
  15672. svr.wait_until_ready();
  15673. {
  15674. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15675. curl_easy_init(), &curl_easy_cleanup};
  15676. ASSERT_NE(curl, nullptr);
  15677. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15678. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15679. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15680. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15681. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15682. &curl_slist_free_all};
  15683. ASSERT_NE(list, nullptr);
  15684. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15685. struct read_data {
  15686. size_t read_size;
  15687. size_t total_size;
  15688. } data = {0, total_size};
  15689. using read_callback_t =
  15690. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15691. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15692. void *userdata) -> size_t {
  15693. read_data *d = (read_data *)userdata;
  15694. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15695. std::fill_n(ptr, size * nmemb, 'A');
  15696. d->read_size += size * nmemb;
  15697. return size * nmemb;
  15698. };
  15699. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15700. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15701. std::vector<char> buffer;
  15702. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15703. using write_callback_t =
  15704. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15705. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15706. void *userdata) -> size_t {
  15707. std::vector<char> *buf = (std::vector<char> *)userdata;
  15708. buf->reserve(buf->size() + size * nmemb + 1);
  15709. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15710. return size * nmemb;
  15711. };
  15712. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15713. {
  15714. const auto res = curl_easy_perform(curl.get());
  15715. ASSERT_EQ(res, CURLE_OK);
  15716. }
  15717. {
  15718. auto response_code = long{};
  15719. const auto res =
  15720. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15721. ASSERT_EQ(res, CURLE_OK);
  15722. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15723. }
  15724. {
  15725. auto dl = curl_off_t{};
  15726. const auto res =
  15727. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15728. ASSERT_EQ(res, CURLE_OK);
  15729. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15730. }
  15731. {
  15732. buffer.push_back('\0');
  15733. ASSERT_STRCASEEQ(buffer.data(), reject);
  15734. }
  15735. }
  15736. }
  15737. #endif
  15738. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15739. // Regression test for #2458.
  15740. //
  15741. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15742. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15743. // ticket can make the client socket spuriously readable during the
  15744. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15745. // the client withholds the body and then blocks reading a response that never
  15746. // comes, failing with `Failed to read connection`.
  15747. //
  15748. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15749. // within the timeout. This raw OpenSSL server deliberately never sends
  15750. // `100 Continue`; the client must still deliver the body and receive 200.
  15751. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15752. signal(SIGPIPE, SIG_IGN);
  15753. const auto port = PORT + 4;
  15754. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15755. ASSERT_NE(srv, INVALID_SOCKET);
  15756. int opt = 1;
  15757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15758. sockaddr_in addr{};
  15759. addr.sin_family = AF_INET;
  15760. addr.sin_port = htons(static_cast<uint16_t>(port));
  15761. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15762. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15763. ASSERT_EQ(0, ::listen(srv, 1));
  15764. std::atomic<size_t> server_body_bytes{0};
  15765. auto server_thread = std::thread([&] {
  15766. sockaddr_in cli_addr{};
  15767. socklen_t cli_len = sizeof(cli_addr);
  15768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15769. if (cli == INVALID_SOCKET) { return; }
  15770. // Bound the lifetime of the server side so a buggy client (which never
  15771. // sends the body) cannot make this thread block forever on join.
  15772. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15773. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15774. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15775. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15776. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15777. SSL *ssl = SSL_new(ctx);
  15778. SSL_set_fd(ssl, static_cast<int>(cli));
  15779. if (SSL_accept(ssl) > 0) {
  15780. // Read the request headers. Reading here also flushes the TLS 1.3
  15781. // session tickets to the client. Deliberately do NOT send
  15782. // `100 Continue`.
  15783. std::string buf;
  15784. char tmp[1024];
  15785. while (buf.find("\r\n\r\n") == std::string::npos) {
  15786. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15787. if (n <= 0) { break; }
  15788. buf.append(tmp, static_cast<size_t>(n));
  15789. }
  15790. // A correct client sends the body now; count what arrives.
  15791. auto pos = buf.find("\r\n\r\n");
  15792. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15793. while (body < 4096) {
  15794. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15795. if (n <= 0) { break; }
  15796. body += static_cast<size_t>(n);
  15797. }
  15798. server_body_bytes = body;
  15799. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15800. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15801. SSL_shutdown(ssl);
  15802. }
  15803. SSL_free(ssl);
  15804. detail::close_socket(cli);
  15805. SSL_CTX_free(ctx);
  15806. });
  15807. auto se = detail::scope_exit([&] {
  15808. server_thread.join();
  15809. detail::close_socket(srv);
  15810. });
  15811. SSLClient cli("127.0.0.1", port);
  15812. cli.enable_server_certificate_verification(false);
  15813. cli.set_connection_timeout(5, 0);
  15814. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15815. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15816. std::string body(4096, 'A');
  15817. auto res = cli.Put("/api/test", body, "application/json");
  15818. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15819. EXPECT_EQ(StatusCode::OK_200, res->status);
  15820. EXPECT_EQ(body.size(), server_body_bytes.load());
  15821. }
  15822. #endif
  15823. template <typename S, typename C>
  15824. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15825. svr.Get("/stream", [&](const Request &, Response &res) {
  15826. auto data = new std::string("01234567890123456789");
  15827. res.set_content_provider(
  15828. data->size(), "text/plain",
  15829. [&, data](size_t offset, size_t length, DataSink &sink) {
  15830. const size_t DATA_CHUNK_SIZE = 4;
  15831. const auto &d = *data;
  15832. std::this_thread::sleep_for(std::chrono::seconds(1));
  15833. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15834. return true;
  15835. },
  15836. [data](bool success) {
  15837. EXPECT_FALSE(success);
  15838. delete data;
  15839. });
  15840. });
  15841. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15842. auto i = new size_t(0);
  15843. res.set_content_provider(
  15844. "text/plain",
  15845. [i](size_t, DataSink &sink) {
  15846. if (*i < 5) {
  15847. std::this_thread::sleep_for(std::chrono::seconds(1));
  15848. sink.write("abcd", 4);
  15849. (*i)++;
  15850. } else {
  15851. sink.done();
  15852. }
  15853. return true;
  15854. },
  15855. [i](bool success) {
  15856. EXPECT_FALSE(success);
  15857. delete i;
  15858. });
  15859. });
  15860. svr.Get("/chunked", [&](const Request &, Response &res) {
  15861. auto i = new size_t(0);
  15862. res.set_chunked_content_provider(
  15863. "text/plain",
  15864. [i](size_t, DataSink &sink) {
  15865. if (*i < 5) {
  15866. std::this_thread::sleep_for(std::chrono::seconds(1));
  15867. sink.os << "abcd";
  15868. (*i)++;
  15869. } else {
  15870. sink.done();
  15871. }
  15872. return true;
  15873. },
  15874. [i](bool success) {
  15875. EXPECT_FALSE(success);
  15876. delete i;
  15877. });
  15878. });
  15879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15880. auto se = detail::scope_exit([&] {
  15881. svr.stop();
  15882. listen_thread.join();
  15883. ASSERT_FALSE(svr.is_running());
  15884. });
  15885. svr.wait_until_ready();
  15886. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15887. {
  15888. auto start = std::chrono::steady_clock::now();
  15889. auto res = cli.Get("/stream");
  15890. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15891. std::chrono::steady_clock::now() - start)
  15892. .count();
  15893. ASSERT_FALSE(res);
  15894. EXPECT_EQ(Error::Read, res.error());
  15895. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15896. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15897. }
  15898. {
  15899. auto start = std::chrono::steady_clock::now();
  15900. auto res = cli.Get("/stream_without_length");
  15901. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15902. std::chrono::steady_clock::now() - start)
  15903. .count();
  15904. ASSERT_FALSE(res);
  15905. EXPECT_EQ(Error::Read, res.error());
  15906. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15907. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15908. }
  15909. {
  15910. auto start = std::chrono::steady_clock::now();
  15911. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15912. EXPECT_EQ("abcd", string(data, data_length));
  15913. return true;
  15914. });
  15915. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15916. std::chrono::steady_clock::now() - start)
  15917. .count();
  15918. ASSERT_FALSE(res);
  15919. EXPECT_EQ(Error::Read, res.error());
  15920. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15921. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15922. }
  15923. }
  15924. TEST(MaxTimeoutTest, ContentStream) {
  15925. time_t timeout = 2000;
  15926. time_t threshold = 200;
  15927. Server svr;
  15928. Client cli("localhost", PORT);
  15929. max_timeout_test(svr, cli, timeout, threshold);
  15930. }
  15931. #ifdef CPPHTTPLIB_SSL_ENABLED
  15932. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15933. time_t timeout = 2000;
  15934. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15936. SSLClient cli("localhost", PORT);
  15937. cli.enable_server_certificate_verification(false);
  15938. max_timeout_test(svr, cli, timeout, threshold);
  15939. }
  15940. #endif
  15941. class EventDispatcher {
  15942. public:
  15943. EventDispatcher() {}
  15944. bool wait_event(DataSink *sink) {
  15945. unique_lock<mutex> lk(m_);
  15946. int id = id_;
  15947. // Wait with timeout to prevent hanging if client disconnects
  15948. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15949. [&] { return cid_ == id; })) {
  15950. return false; // Timeout occurred
  15951. }
  15952. sink->write(message_.data(), message_.size());
  15953. return true;
  15954. }
  15955. void send_event(const string &message) {
  15956. lock_guard<mutex> lk(m_);
  15957. cid_ = id_++;
  15958. message_ = message;
  15959. cv_.notify_all();
  15960. }
  15961. private:
  15962. mutex m_;
  15963. condition_variable cv_;
  15964. atomic_int id_{0};
  15965. atomic_int cid_{-1};
  15966. string message_;
  15967. };
  15968. TEST(ClientInThreadTest, Issue2068) {
  15969. EventDispatcher ed;
  15970. Server svr;
  15971. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15972. res.set_chunked_content_provider("text/event-stream",
  15973. [&](size_t /*offset*/, DataSink &sink) {
  15974. return ed.wait_event(&sink);
  15975. });
  15976. });
  15977. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15978. svr.wait_until_ready();
  15979. thread event_thread([&] {
  15980. int id = 0;
  15981. while (svr.is_running()) {
  15982. this_thread::sleep_for(chrono::milliseconds(500));
  15983. std::stringstream ss;
  15984. ss << "data: " << id << "\n\n";
  15985. ed.send_event(ss.str());
  15986. id++;
  15987. }
  15988. });
  15989. auto se = detail::scope_exit([&] {
  15990. svr.stop();
  15991. listen_thread.join();
  15992. event_thread.join();
  15993. ASSERT_FALSE(svr.is_running());
  15994. });
  15995. {
  15996. auto client = detail::make_unique<Client>(HOST, PORT);
  15997. client->set_read_timeout(std::chrono::minutes(10));
  15998. std::atomic<bool> stop{false};
  15999. std::thread t([&] {
  16000. client->Get("/event1",
  16001. [&](const char *, size_t) -> bool { return !stop; });
  16002. });
  16003. std::this_thread::sleep_for(std::chrono::seconds(2));
  16004. stop = true;
  16005. client->stop();
  16006. t.join();
  16007. // Reset client after thread has finished
  16008. client.reset();
  16009. }
  16010. }
  16011. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16012. auto handled = false;
  16013. Server svr;
  16014. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16015. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16016. auto se = detail::scope_exit([&] {
  16017. svr.stop();
  16018. t.join();
  16019. ASSERT_FALSE(svr.is_running());
  16020. ASSERT_FALSE(handled);
  16021. });
  16022. svr.wait_until_ready();
  16023. // Two Content-Length headers with different values — must be rejected
  16024. auto req = "POST /test HTTP/1.1\r\n"
  16025. "Content-Length: 5\r\n"
  16026. "Content-Length: 10\r\n"
  16027. "\r\n"
  16028. "hello";
  16029. std::string response;
  16030. ASSERT_TRUE(send_request(1, req, &response));
  16031. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16032. response.substr(0, response.find("\r\n")));
  16033. }
  16034. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16035. auto handled = false;
  16036. Server svr;
  16037. svr.Post("/test", [&](const Request &, Response &res) {
  16038. handled = true;
  16039. res.set_content("ok", "text/plain");
  16040. });
  16041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16042. auto se = detail::scope_exit([&] {
  16043. svr.stop();
  16044. t.join();
  16045. ASSERT_FALSE(svr.is_running());
  16046. ASSERT_TRUE(handled);
  16047. });
  16048. svr.wait_until_ready();
  16049. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16050. auto req = "POST /test HTTP/1.1\r\n"
  16051. "Content-Length: 5\r\n"
  16052. "Content-Length: 5\r\n"
  16053. "\r\n"
  16054. "hello";
  16055. std::string response;
  16056. ASSERT_TRUE(send_request(1, req, &response));
  16057. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16058. }
  16059. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16060. Server svr;
  16061. svr.Get("/", [](const Request &req, Response &res) {
  16062. EXPECT_EQ(2U, req.trailers.size());
  16063. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16064. // Denied
  16065. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16066. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16067. // Accepted
  16068. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16069. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16070. EXPECT_TRUE(req.has_trailer("X-World"));
  16071. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16072. res.set_content("ok", "text/plain");
  16073. });
  16074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16075. auto se = detail::scope_exit([&] {
  16076. svr.stop();
  16077. t.join();
  16078. ASSERT_FALSE(svr.is_running());
  16079. });
  16080. svr.wait_until_ready();
  16081. const std::string req = "GET / HTTP/1.1\r\n"
  16082. "Transfer-Encoding: chunked\r\n"
  16083. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16084. "\r\n"
  16085. "0\r\n"
  16086. "Content-Length: 10\r\n"
  16087. "Host: internal.local\r\n"
  16088. "Content-Type: malicious/content\r\n"
  16089. "Cookie: any\r\n"
  16090. "Set-Cookie: any\r\n"
  16091. "X-Forwarded-For: attacker.com\r\n"
  16092. "X-Real-Ip: 1.1.1.1\r\n"
  16093. "X-Hello: hello\r\n"
  16094. "X-World: world\r\n"
  16095. "\r\n";
  16096. std::string res;
  16097. ASSERT_TRUE(send_request(1, req, &res));
  16098. }
  16099. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16100. // several field lines, and the combined value is what has to be parsed. A
  16101. // Trailer field split across lines therefore declares every name it lists;
  16102. // reading only the first line silently drops the trailers the later lines
  16103. // declare. The prohibited-trailer filter still applies to every line.
  16104. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16105. Server svr;
  16106. size_t observed_trailer_count = 0;
  16107. std::string observed_hello;
  16108. std::string observed_world;
  16109. bool observed_content_length = true;
  16110. svr.Get("/", [&](const Request &req, Response &res) {
  16111. observed_trailer_count = req.trailers.size();
  16112. observed_hello = req.get_trailer_value("X-Hello");
  16113. observed_world = req.get_trailer_value("X-World");
  16114. observed_content_length = req.has_trailer("Content-Length");
  16115. res.set_content("ok", "text/plain");
  16116. });
  16117. auto port = svr.bind_to_any_port(HOST);
  16118. thread t = thread([&]() { svr.listen_after_bind(); });
  16119. auto se = detail::scope_exit([&] {
  16120. svr.stop();
  16121. t.join();
  16122. ASSERT_FALSE(svr.is_running());
  16123. });
  16124. svr.wait_until_ready();
  16125. const std::string req = "GET / HTTP/1.1\r\n"
  16126. "Transfer-Encoding: chunked\r\n"
  16127. "Trailer: X-Hello\r\n"
  16128. "Trailer: X-World, Content-Length\r\n"
  16129. "\r\n"
  16130. "0\r\n"
  16131. "X-Hello: hello\r\n"
  16132. "X-World: world\r\n"
  16133. "Content-Length: 10\r\n"
  16134. "\r\n";
  16135. std::string res;
  16136. ASSERT_TRUE(send_request(1, req, &res, port));
  16137. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16138. // Accepted: both field lines contribute to the declared set
  16139. EXPECT_EQ(2U, observed_trailer_count);
  16140. EXPECT_EQ(observed_hello, "hello");
  16141. EXPECT_EQ(observed_world, "world");
  16142. // Denied: a prohibited name stays prohibited on a later field line
  16143. EXPECT_FALSE(observed_content_length);
  16144. }
  16145. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16146. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16147. // unbounded run of fields that are never declared, because the counter would
  16148. // only advance for declared fields.
  16149. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16150. Server svr;
  16151. bool handler_called = false;
  16152. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16153. handler_called = true;
  16154. res.set_content("ok", "text/plain");
  16155. });
  16156. auto port = svr.bind_to_any_port(HOST);
  16157. thread t = thread([&]() { svr.listen_after_bind(); });
  16158. auto se = detail::scope_exit([&] {
  16159. svr.stop();
  16160. t.join();
  16161. ASSERT_FALSE(svr.is_running());
  16162. });
  16163. svr.wait_until_ready();
  16164. // Declare nothing, then send far more undeclared trailer fields than the
  16165. // header-count limit. Parsing must stop and reject the request rather than
  16166. // read every line.
  16167. std::string req = "GET / HTTP/1.1\r\n"
  16168. "Transfer-Encoding: chunked\r\n"
  16169. "\r\n"
  16170. "0\r\n";
  16171. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16172. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16173. }
  16174. req += "\r\n";
  16175. std::string res;
  16176. ASSERT_TRUE(send_request(1, req, &res, port));
  16177. // The request is rejected before the handler runs.
  16178. EXPECT_FALSE(handler_called);
  16179. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16180. }
  16181. // The set of declared trailer names is capped so a peer cannot grow it without
  16182. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16183. // declared past the cap is not honored, even if the field is actually sent.
  16184. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16185. Server svr;
  16186. // One name inside the cap and one past it, so the test tracks the cap rather
  16187. // than a fixed count.
  16188. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16189. const std::string within_cap_name = "X-T-0";
  16190. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16191. bool observed_within_cap = false;
  16192. bool observed_past_cap = false;
  16193. svr.Get("/", [&](const Request &req, Response &res) {
  16194. observed_within_cap = req.has_trailer(within_cap_name);
  16195. observed_past_cap = req.has_trailer(past_cap_name);
  16196. res.set_content("ok", "text/plain");
  16197. });
  16198. auto port = svr.bind_to_any_port(HOST);
  16199. thread t = thread([&]() { svr.listen_after_bind(); });
  16200. auto se = detail::scope_exit([&] {
  16201. svr.stop();
  16202. t.join();
  16203. ASSERT_FALSE(svr.is_running());
  16204. });
  16205. svr.wait_until_ready();
  16206. // Declare more trailer names than the cap in a single Trailer field, then
  16207. // actually send the first (within the cap) and the last (past it).
  16208. std::string trailer_decl = "Trailer: ";
  16209. for (int i = 0; i < declared_count; i++) {
  16210. if (i != 0) { trailer_decl += ", "; }
  16211. trailer_decl += "X-T-" + std::to_string(i);
  16212. }
  16213. trailer_decl += "\r\n";
  16214. const std::string req = "GET / HTTP/1.1\r\n"
  16215. "Transfer-Encoding: chunked\r\n" +
  16216. trailer_decl +
  16217. "\r\n"
  16218. "0\r\n" +
  16219. within_cap_name + ": a\r\n" + past_cap_name +
  16220. ": b\r\n"
  16221. "\r\n";
  16222. std::string res;
  16223. ASSERT_TRUE(send_request(1, req, &res, port));
  16224. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16225. // A name within the cap is honored; one declared past the cap is dropped.
  16226. EXPECT_TRUE(observed_within_cap);
  16227. EXPECT_FALSE(observed_past_cap);
  16228. }
  16229. // A direct client that is not listed in trusted_proxies must not be able to
  16230. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16231. // the peer address on the actual TCP connection determines whether the
  16232. // header is honored.
  16233. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16234. Server svr;
  16235. // Deliberately does NOT include the loopback address the test client
  16236. // actually connects from, so the direct connection is not a trusted proxy.
  16237. svr.set_trusted_proxies({"203.0.113.66"});
  16238. std::string observed_remote_addr;
  16239. svr.Get("/ip", [&](const Request &req, Response &res) {
  16240. observed_remote_addr = req.remote_addr;
  16241. res.set_content("ok", "text/plain");
  16242. });
  16243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16244. auto se = detail::scope_exit([&] {
  16245. svr.stop();
  16246. t.join();
  16247. ASSERT_FALSE(svr.is_running());
  16248. });
  16249. svr.wait_until_ready();
  16250. Client cli(HOST, PORT);
  16251. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16253. EXPECT_EQ(StatusCode::OK_200, res->status);
  16254. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16255. // ignored entirely and the real connection-level address retained.
  16256. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16257. observed_remote_addr == "127.0.0.1");
  16258. }
  16259. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16260. Server svr;
  16261. std::string observed_remote_addr;
  16262. std::string observed_xff;
  16263. svr.Get("/ip", [&](const Request &req, Response &res) {
  16264. observed_remote_addr = req.remote_addr;
  16265. observed_xff = req.get_header_value("X-Forwarded-For");
  16266. res.set_content("ok", "text/plain");
  16267. });
  16268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16269. auto se = detail::scope_exit([&] {
  16270. svr.stop();
  16271. t.join();
  16272. ASSERT_FALSE(svr.is_running());
  16273. });
  16274. svr.wait_until_ready();
  16275. Client cli(HOST, PORT);
  16276. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16278. EXPECT_EQ(StatusCode::OK_200, res->status);
  16279. EXPECT_EQ(observed_xff, "203.0.113.66");
  16280. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16281. observed_remote_addr == "127.0.0.1");
  16282. }
  16283. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16284. Server svr;
  16285. svr.set_trusted_proxies({"203.0.113.66"});
  16286. std::string observed_remote_addr;
  16287. std::string observed_xff;
  16288. svr.Get("/ip", [&](const Request &req, Response &res) {
  16289. observed_remote_addr = req.remote_addr;
  16290. observed_xff = req.get_header_value("X-Forwarded-For");
  16291. res.set_content("ok", "text/plain");
  16292. });
  16293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16294. auto se = detail::scope_exit([&] {
  16295. svr.stop();
  16296. t.join();
  16297. ASSERT_FALSE(svr.is_running());
  16298. });
  16299. svr.wait_until_ready();
  16300. Client cli(HOST, PORT);
  16301. auto res = cli.Get("/ip");
  16302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16303. EXPECT_EQ(StatusCode::OK_200, res->status);
  16304. EXPECT_EQ(observed_xff, "");
  16305. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16306. observed_remote_addr == "127.0.0.1");
  16307. }
  16308. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16309. Server svr;
  16310. // Include the loopback address the test client actually connects from, so
  16311. // the direct connection itself is recognized as the trusted proxy hop.
  16312. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16313. std::string observed_remote_addr;
  16314. std::string observed_xff;
  16315. svr.Get("/ip", [&](const Request &req, Response &res) {
  16316. observed_remote_addr = req.remote_addr;
  16317. observed_xff = req.get_header_value("X-Forwarded-For");
  16318. res.set_content("ok", "text/plain");
  16319. });
  16320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16321. auto se = detail::scope_exit([&] {
  16322. svr.stop();
  16323. t.join();
  16324. ASSERT_FALSE(svr.is_running());
  16325. });
  16326. svr.wait_until_ready();
  16327. Client cli(HOST, PORT);
  16328. auto res = cli.Get(
  16329. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16331. EXPECT_EQ(StatusCode::OK_200, res->status);
  16332. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16333. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16334. }
  16335. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16336. Server svr;
  16337. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16338. std::string observed_remote_addr;
  16339. std::string observed_xff;
  16340. svr.Get("/ip", [&](const Request &req, Response &res) {
  16341. observed_remote_addr = req.remote_addr;
  16342. observed_xff = req.get_header_value("X-Forwarded-For");
  16343. res.set_content("ok", "text/plain");
  16344. });
  16345. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16346. auto se = detail::scope_exit([&] {
  16347. svr.stop();
  16348. t.join();
  16349. ASSERT_FALSE(svr.is_running());
  16350. });
  16351. svr.wait_until_ready();
  16352. Client cli(HOST, PORT);
  16353. auto res = cli.Get(
  16354. "/ip",
  16355. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16357. EXPECT_EQ(StatusCode::OK_200, res->status);
  16358. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16359. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16360. }
  16361. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16362. Server svr;
  16363. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16364. std::string observed_remote_addr;
  16365. std::string observed_xff;
  16366. svr.Get("/ip", [&](const Request &req, Response &res) {
  16367. observed_remote_addr = req.remote_addr;
  16368. observed_xff = req.get_header_value("X-Forwarded-For");
  16369. res.set_content("ok", "text/plain");
  16370. });
  16371. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16372. auto se = detail::scope_exit([&] {
  16373. svr.stop();
  16374. t.join();
  16375. ASSERT_FALSE(svr.is_running());
  16376. });
  16377. svr.wait_until_ready();
  16378. Client cli(HOST, PORT);
  16379. auto res = cli.Get(
  16380. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16382. EXPECT_EQ(StatusCode::OK_200, res->status);
  16383. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16384. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16385. // and must not be selected.
  16386. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16387. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16388. }
  16389. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16390. Server svr;
  16391. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16392. std::string observed_remote_addr;
  16393. svr.Get("/ip", [&](const Request &req, Response &res) {
  16394. observed_remote_addr = req.remote_addr;
  16395. res.set_content("ok", "text/plain");
  16396. });
  16397. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16398. auto se = detail::scope_exit([&] {
  16399. svr.stop();
  16400. t.join();
  16401. ASSERT_FALSE(svr.is_running());
  16402. });
  16403. svr.wait_until_ready();
  16404. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16405. // a forged address and the trusted proxy's own address; the forged value must
  16406. // not win over the address the trusted proxy actually recorded.
  16407. Client cli(HOST, PORT);
  16408. auto res = cli.Get(
  16409. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16411. EXPECT_EQ(StatusCode::OK_200, res->status);
  16412. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16413. }
  16414. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16415. Server svr;
  16416. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16417. std::string observed_remote_addr;
  16418. std::string observed_xff;
  16419. svr.Get("/ip", [&](const Request &req, Response &res) {
  16420. observed_remote_addr = req.remote_addr;
  16421. observed_xff = req.get_header_value("X-Forwarded-For");
  16422. res.set_content("ok", "text/plain");
  16423. });
  16424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16425. auto se = detail::scope_exit([&] {
  16426. svr.stop();
  16427. t.join();
  16428. ASSERT_FALSE(svr.is_running());
  16429. });
  16430. svr.wait_until_ready();
  16431. Client cli(HOST, PORT);
  16432. auto res = cli.Get(
  16433. "/ip",
  16434. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16436. EXPECT_EQ(StatusCode::OK_200, res->status);
  16437. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16438. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16439. }
  16440. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16441. Server svr;
  16442. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16443. std::string observed_remote_addr;
  16444. std::string observed_xff;
  16445. svr.Get("/ip", [&](const Request &req, Response &res) {
  16446. observed_remote_addr = req.remote_addr;
  16447. observed_xff = req.get_header_value("X-Forwarded-For");
  16448. res.set_content("ok", "text/plain");
  16449. });
  16450. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16451. auto se = detail::scope_exit([&] {
  16452. svr.stop();
  16453. t.join();
  16454. ASSERT_FALSE(svr.is_running());
  16455. });
  16456. svr.wait_until_ready();
  16457. std::string raw_req =
  16458. "GET /ip HTTP/1.1\r\n"
  16459. "Host: localhost\r\n"
  16460. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16461. "Connection: close\r\n"
  16462. "\r\n";
  16463. std::string out;
  16464. ASSERT_TRUE(send_request(5, raw_req, &out));
  16465. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16466. // Header parser trims surrounding whitespace of the header value
  16467. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16468. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16469. }
  16470. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16471. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16472. // their own X-Forwarded-For as a separate field line rather than extending the
  16473. // one the client sent, so every occurrence has to be taken into account.
  16474. // Reading only the first one hands back the address the client chose.
  16475. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16476. Server svr;
  16477. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16478. std::string observed_remote_addr;
  16479. size_t observed_xff_count = 0;
  16480. svr.Get("/ip", [&](const Request &req, Response &res) {
  16481. observed_remote_addr = req.remote_addr;
  16482. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16483. res.set_content("ok", "text/plain");
  16484. });
  16485. auto port = svr.bind_to_any_port(HOST);
  16486. thread t = thread([&]() { svr.listen_after_bind(); });
  16487. auto se = detail::scope_exit([&] {
  16488. svr.stop();
  16489. t.join();
  16490. ASSERT_FALSE(svr.is_running());
  16491. });
  16492. svr.wait_until_ready();
  16493. // The client supplies the first field line; the trusted proxy appends the
  16494. // address it observed as a second one.
  16495. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16496. "Host: localhost\r\n"
  16497. "X-Forwarded-For: 1.2.3.4\r\n"
  16498. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16499. "Connection: close\r\n"
  16500. "\r\n";
  16501. std::string out;
  16502. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16503. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16504. EXPECT_EQ(observed_xff_count, 2U);
  16505. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16506. // The same chain spread over one field line per hop derives the same client
  16507. // address, i.e. the split and the comma-joined representations agree.
  16508. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16509. "Host: localhost\r\n"
  16510. "X-Forwarded-For: 1.2.3.4\r\n"
  16511. "X-Forwarded-For: 198.51.100.23\r\n"
  16512. "X-Forwarded-For: 192.0.2.45\r\n"
  16513. "Connection: close\r\n"
  16514. "\r\n";
  16515. out.clear();
  16516. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16517. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16518. EXPECT_EQ(observed_xff_count, 3U);
  16519. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16520. }
  16521. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16522. // crash the server (it used to call front() on an empty vector inside
  16523. // get_client_ip). The connection-level remote address must be retained instead.
  16524. static void run_malformed_xff_test(const std::string &xff_value) {
  16525. Server svr;
  16526. svr.set_trusted_proxies({"192.0.2.45"});
  16527. std::string observed_remote_addr;
  16528. svr.Get("/ip", [&](const Request &req, Response &res) {
  16529. observed_remote_addr = req.remote_addr;
  16530. res.set_content("ok", "text/plain");
  16531. });
  16532. int port = 0;
  16533. thread t = thread([&]() {
  16534. port = svr.bind_to_any_port(HOST);
  16535. svr.listen_after_bind();
  16536. });
  16537. auto se = detail::scope_exit([&] {
  16538. svr.stop();
  16539. t.join();
  16540. ASSERT_FALSE(svr.is_running());
  16541. });
  16542. svr.wait_until_ready();
  16543. Client cli(HOST, port);
  16544. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16546. EXPECT_EQ(StatusCode::OK_200, res->status);
  16547. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16548. observed_remote_addr == "127.0.0.1");
  16549. }
  16550. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16551. run_malformed_xff_test("");
  16552. }
  16553. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16554. run_malformed_xff_test(",");
  16555. }
  16556. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16557. run_malformed_xff_test(", , ,");
  16558. }
  16559. // The same rule applies to Accept: a request whose acceptable types are spread
  16560. // over several field lines must be negotiated against all of them.
  16561. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16562. // case-insensitive connection options. Comparing the whole field value against
  16563. // one option misses a client that sends several of them, and misses every
  16564. // casing but the one written in the comparison.
  16565. //
  16566. // Sends req, reads the response, then reuses the same socket for a second
  16567. // request to find out whether the server kept the connection.
  16568. static void probe_connection_reuse(int port, const std::string &req,
  16569. bool *announced_close, bool *reusable) {
  16570. auto error = Error::Success;
  16571. auto sock = detail::create_client_socket(
  16572. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16573. /*connection_timeout_sec=*/5, 0,
  16574. /*read_timeout_sec=*/1, 0,
  16575. /*write_timeout_sec=*/5, 0, std::string(), error);
  16576. ASSERT_NE(sock, INVALID_SOCKET);
  16577. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16578. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16579. "Host: localhost\r\n"
  16580. "Connection: close\r\n"
  16581. "\r\n";
  16582. std::string first_response;
  16583. std::string second_response;
  16584. detail::process_client_socket(
  16585. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16586. [&](Stream &strm) {
  16587. if (strm.write(req.data(), req.size()) !=
  16588. static_cast<ssize_t>(req.size())) {
  16589. return false;
  16590. }
  16591. char buf[512];
  16592. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16593. // Headers plus the two-byte body of the handler below
  16594. while (reader.getline()) {
  16595. first_response += reader.ptr();
  16596. if (first_response.find("ok") != std::string::npos) { break; }
  16597. }
  16598. if (strm.write(second.data(), second.size()) !=
  16599. static_cast<ssize_t>(second.size())) {
  16600. return true;
  16601. }
  16602. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16603. while (reader2.getline()) {
  16604. second_response += reader2.ptr();
  16605. if (second_response.find("ok") != std::string::npos) { break; }
  16606. }
  16607. return true;
  16608. });
  16609. *announced_close =
  16610. first_response.find("Connection: close") != std::string::npos;
  16611. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16612. }
  16613. class ConnectionTokenTest : public ::testing::Test {
  16614. protected:
  16615. void SetUp() override {
  16616. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16617. res.set_content("ok", "text/plain");
  16618. });
  16619. port_ = svr_.bind_to_any_port(HOST);
  16620. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16621. svr_.wait_until_ready();
  16622. }
  16623. void TearDown() override {
  16624. svr_.stop();
  16625. if (thread_.joinable()) { thread_.join(); }
  16626. }
  16627. Server svr_;
  16628. int port_ = 0;
  16629. thread thread_;
  16630. };
  16631. // "close" alongside another option still closes the connection, and the
  16632. // response says so rather than leaving the peer to discover it.
  16633. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16634. bool announced_close = false;
  16635. bool reusable = true;
  16636. probe_connection_reuse(port_,
  16637. "GET /keepalive HTTP/1.1\r\n"
  16638. "Host: localhost\r\n"
  16639. "Connection: keep-alive, close\r\n"
  16640. "\r\n",
  16641. &announced_close, &reusable);
  16642. EXPECT_TRUE(announced_close);
  16643. EXPECT_FALSE(reusable);
  16644. }
  16645. // "close" split over two field lines is the same list, so it is honored too.
  16646. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16647. bool announced_close = false;
  16648. bool reusable = true;
  16649. probe_connection_reuse(port_,
  16650. "GET /keepalive HTTP/1.1\r\n"
  16651. "Host: localhost\r\n"
  16652. "Connection: keep-alive\r\n"
  16653. "Connection: close\r\n"
  16654. "\r\n",
  16655. &announced_close, &reusable);
  16656. EXPECT_TRUE(announced_close);
  16657. EXPECT_FALSE(reusable);
  16658. }
  16659. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16660. // keep-alive in the spelling everyone actually sends keeps its connection.
  16661. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16662. bool announced_close = false;
  16663. bool reusable = false;
  16664. probe_connection_reuse(port_,
  16665. "GET /keepalive HTTP/1.0\r\n"
  16666. "Host: localhost\r\n"
  16667. "Connection: keep-alive\r\n"
  16668. "\r\n",
  16669. &announced_close, &reusable);
  16670. EXPECT_FALSE(announced_close);
  16671. EXPECT_TRUE(reusable);
  16672. }
  16673. // A token the value merely contains is not the token itself.
  16674. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16675. bool announced_close = false;
  16676. bool reusable = false;
  16677. probe_connection_reuse(port_,
  16678. "GET /keepalive HTTP/1.1\r\n"
  16679. "Host: localhost\r\n"
  16680. "Connection: notclose\r\n"
  16681. "\r\n",
  16682. &announced_close, &reusable);
  16683. EXPECT_FALSE(announced_close);
  16684. EXPECT_TRUE(reusable);
  16685. }
  16686. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16687. Server svr;
  16688. std::vector<std::string> observed_types;
  16689. svr.Get("/", [&](const Request &req, Response &res) {
  16690. observed_types = req.accept_content_types;
  16691. res.set_content("ok", "text/plain");
  16692. });
  16693. auto port = svr.bind_to_any_port(HOST);
  16694. thread t = thread([&]() { svr.listen_after_bind(); });
  16695. auto se = detail::scope_exit([&] {
  16696. svr.stop();
  16697. t.join();
  16698. ASSERT_FALSE(svr.is_running());
  16699. });
  16700. svr.wait_until_ready();
  16701. Client cli(HOST, port);
  16702. Headers headers;
  16703. headers.emplace("Accept", "text/plain;q=0.5");
  16704. headers.emplace("Accept", "application/json");
  16705. auto res = cli.Get("/", headers);
  16706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16707. EXPECT_EQ(StatusCode::OK_200, res->status);
  16708. // Sorted by q-value, so the second field line's type comes first
  16709. ASSERT_EQ(2U, observed_types.size());
  16710. EXPECT_EQ("application/json", observed_types[0]);
  16711. EXPECT_EQ("text/plain", observed_types[1]);
  16712. }
  16713. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16714. // empty field line must not contribute a bare comma to the combined value.
  16715. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16716. Server svr;
  16717. std::vector<std::string> observed_types;
  16718. svr.Get("/", [&](const Request &req, Response &res) {
  16719. observed_types = req.accept_content_types;
  16720. res.set_content("ok", "text/plain");
  16721. });
  16722. auto port = svr.bind_to_any_port(HOST);
  16723. thread t = thread([&]() { svr.listen_after_bind(); });
  16724. auto se = detail::scope_exit([&] {
  16725. svr.stop();
  16726. t.join();
  16727. ASSERT_FALSE(svr.is_running());
  16728. });
  16729. svr.wait_until_ready();
  16730. // Empty first field line, then a real one
  16731. std::string raw_req = "GET / HTTP/1.1\r\n"
  16732. "Host: localhost\r\n"
  16733. "Accept:\r\n"
  16734. "Accept: application/json\r\n"
  16735. "Connection: close\r\n"
  16736. "\r\n";
  16737. std::string out;
  16738. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16739. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16740. ASSERT_EQ(1U, observed_types.size());
  16741. EXPECT_EQ("application/json", observed_types[0]);
  16742. }
  16743. // The skip in get_combined_header_value() is what keeps an empty field line
  16744. // from contributing a bare comma. Only a trailing empty field line exercises
  16745. // it: a leading one is already covered by the "combined is still empty" check,
  16746. // and parse_accept_header() now ignores the empty element either way, so the
  16747. // request-level test above can no longer tell the two apart.
  16748. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16749. Headers headers;
  16750. headers.emplace("Accept", "text/html");
  16751. headers.emplace("Accept", "");
  16752. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16753. headers.clear();
  16754. headers.emplace("Accept", "");
  16755. headers.emplace("Accept", "application/json");
  16756. EXPECT_EQ("application/json",
  16757. detail::get_combined_header_value(headers, "Accept"));
  16758. }
  16759. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16760. // An encoding offered on a later Accept-Encoding field line is still offered.
  16761. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16762. Server svr;
  16763. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16764. res.set_content(std::string(1024, 'x'), "text/plain");
  16765. });
  16766. auto port = svr.bind_to_any_port(HOST);
  16767. thread t = thread([&]() { svr.listen_after_bind(); });
  16768. auto se = detail::scope_exit([&] {
  16769. svr.stop();
  16770. t.join();
  16771. ASSERT_FALSE(svr.is_running());
  16772. });
  16773. svr.wait_until_ready();
  16774. Client cli(HOST, port);
  16775. cli.set_decompress(false);
  16776. Headers headers;
  16777. headers.emplace("Accept-Encoding", "identity");
  16778. headers.emplace("Accept-Encoding", "gzip");
  16779. auto res = cli.Get("/", headers);
  16780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16781. EXPECT_EQ(StatusCode::OK_200, res->status);
  16782. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16783. }
  16784. #endif
  16785. #ifndef _WIN32
  16786. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16787. Server svr;
  16788. svr.Post("/post", [&](const Request &req, Response &res) {
  16789. res.set_content(req.body, "text/plain");
  16790. });
  16791. svr.Put("/put", [&](const Request &req, Response &res) {
  16792. res.set_content(req.body, "text/plain");
  16793. });
  16794. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16795. res.set_content(req.body, "text/plain");
  16796. });
  16797. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16798. res.set_content(req.body, "text/plain");
  16799. });
  16800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16801. auto se = detail::scope_exit([&] {
  16802. svr.stop();
  16803. t.join();
  16804. ASSERT_FALSE(svr.is_running());
  16805. });
  16806. svr.wait_until_ready();
  16807. std::string resp;
  16808. // POST without Content-Length
  16809. ASSERT_TRUE(send_request(5,
  16810. "POST /post HTTP/1.1\r\n"
  16811. "Host: localhost\r\n"
  16812. "Connection: close\r\n"
  16813. "\r\n",
  16814. &resp));
  16815. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16816. // PUT without Content-Length
  16817. resp.clear();
  16818. ASSERT_TRUE(send_request(5,
  16819. "PUT /put HTTP/1.1\r\n"
  16820. "Host: localhost\r\n"
  16821. "Connection: close\r\n"
  16822. "\r\n",
  16823. &resp));
  16824. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16825. // PATCH without Content-Length
  16826. resp.clear();
  16827. ASSERT_TRUE(send_request(5,
  16828. "PATCH /patch HTTP/1.1\r\n"
  16829. "Host: localhost\r\n"
  16830. "Connection: close\r\n"
  16831. "\r\n",
  16832. &resp));
  16833. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16834. // DELETE without Content-Length
  16835. resp.clear();
  16836. ASSERT_TRUE(send_request(5,
  16837. "DELETE /delete HTTP/1.1\r\n"
  16838. "Host: localhost\r\n"
  16839. "Connection: close\r\n"
  16840. "\r\n",
  16841. &resp));
  16842. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16843. }
  16844. #endif
  16845. //==============================================================================
  16846. // open_stream() Tests
  16847. //==============================================================================
  16848. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16849. std::string result;
  16850. char buf[8192];
  16851. ssize_t n;
  16852. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16853. result.append(buf, static_cast<size_t>(n));
  16854. }
  16855. return result;
  16856. }
  16857. // Mock stream for unit tests
  16858. class MockStream : public Stream {
  16859. public:
  16860. std::string data;
  16861. size_t pos = 0;
  16862. ssize_t error_after = -1; // -1 = no error
  16863. explicit MockStream(const std::string &d, ssize_t err = -1)
  16864. : data(d), error_after(err) {}
  16865. bool is_readable() const override { return true; }
  16866. bool wait_readable() const override { return true; }
  16867. bool wait_writable() const override { return true; }
  16868. ssize_t read(char *ptr, size_t size) override {
  16869. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16870. if (pos >= data.size()) return 0;
  16871. size_t limit =
  16872. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16873. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16874. std::memcpy(ptr, data.data() + pos, to_read);
  16875. pos += to_read;
  16876. return static_cast<ssize_t>(to_read);
  16877. }
  16878. ssize_t write(const char *, size_t) override { return -1; }
  16879. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16880. ip = "127.0.0.1";
  16881. port = 0;
  16882. }
  16883. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16884. ip = "127.0.0.1";
  16885. port = 0;
  16886. }
  16887. socket_t socket() const override { return INVALID_SOCKET; }
  16888. time_t duration() const override { return 0; }
  16889. };
  16890. TEST(StreamHandleTest, Basic) {
  16891. ClientImpl::StreamHandle handle;
  16892. EXPECT_FALSE(handle.is_valid());
  16893. handle.response = detail::make_unique<Response>();
  16894. handle.error = Error::Connection;
  16895. EXPECT_FALSE(handle.is_valid());
  16896. handle.error = Error::Success;
  16897. EXPECT_TRUE(handle.is_valid());
  16898. }
  16899. TEST(BodyReaderTest, Basic) {
  16900. MockStream stream("Hello, World!");
  16901. detail::BodyReader reader;
  16902. reader.stream = &stream;
  16903. reader.content_length = 13;
  16904. char buf[32];
  16905. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16906. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16907. EXPECT_TRUE(reader.eof);
  16908. }
  16909. TEST(BodyReaderTest, NoStream) {
  16910. detail::BodyReader reader;
  16911. char buf[32];
  16912. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16913. EXPECT_EQ(Error::Connection, reader.last_error);
  16914. }
  16915. TEST(BodyReaderTest, Error) {
  16916. MockStream stream("Hello, World!", 5);
  16917. detail::BodyReader reader;
  16918. reader.stream = &stream;
  16919. reader.content_length = 13;
  16920. char buf[32];
  16921. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16922. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16923. EXPECT_EQ(Error::Read, reader.last_error);
  16924. }
  16925. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16926. // Mock-based StreamHandle tests relying on private internals are removed.
  16927. class OpenStreamTest : public ::testing::Test {
  16928. protected:
  16929. void SetUp() override {
  16930. svr_.Get("/hello", [](const Request &, Response &res) {
  16931. res.set_content("Hello World!", "text/plain");
  16932. });
  16933. svr_.Get("/large", [](const Request &, Response &res) {
  16934. res.set_content(std::string(10000, 'X'), "text/plain");
  16935. });
  16936. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16937. res.set_content("Hello World!", "image/jpeg");
  16938. res.set_header("Content-Encoding", "UTF-8");
  16939. });
  16940. svr_.Get("/chunked", [](const Request &, Response &res) {
  16941. res.set_chunked_content_provider("text/plain",
  16942. [](size_t offset, DataSink &sink) {
  16943. if (offset < 15) {
  16944. sink.write("chunk", 5);
  16945. return true;
  16946. }
  16947. sink.done();
  16948. return true;
  16949. });
  16950. });
  16951. svr_.Get("/compressible", [](const Request &, Response &res) {
  16952. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16953. DataSink &sink) {
  16954. if (offset < 100 * 1024) {
  16955. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16956. sink.write(chunk.data(), chunk.size());
  16957. return true;
  16958. }
  16959. sink.done();
  16960. return true;
  16961. });
  16962. });
  16963. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16964. [](const Request & /*req*/, Response &res) {
  16965. auto i = new int(0);
  16966. res.set_header("Trailer", "Content-Length, X-Allowed");
  16967. res.set_chunked_content_provider(
  16968. "text/plain",
  16969. [i](size_t /*offset*/, DataSink &sink) {
  16970. switch (*i) {
  16971. case 0: sink.os << "123"; break;
  16972. case 1: sink.os << "456"; break;
  16973. case 2: sink.os << "789"; break;
  16974. case 3: {
  16975. sink.done_with_trailer(
  16976. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16977. } break;
  16978. }
  16979. (*i)++;
  16980. return true;
  16981. },
  16982. [i](bool success) {
  16983. EXPECT_TRUE(success);
  16984. delete i;
  16985. });
  16986. });
  16987. // Echo headers endpoint for header-related tests
  16988. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16989. std::string body;
  16990. for (const auto &h : req.headers) {
  16991. body.append(h.first);
  16992. body.push_back(':');
  16993. body.append(h.second);
  16994. body.push_back('\n');
  16995. }
  16996. res.set_content(body, "text/plain");
  16997. });
  16998. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16999. std::string body;
  17000. for (const auto &h : req.headers) {
  17001. body.append(h.first);
  17002. body.push_back(':');
  17003. body.append(h.second);
  17004. body.push_back('\n');
  17005. }
  17006. res.set_content(body, "text/plain");
  17007. });
  17008. port_ = svr_.bind_to_any_port("127.0.0.1");
  17009. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17010. svr_.wait_until_ready();
  17011. }
  17012. void TearDown() override {
  17013. svr_.stop();
  17014. if (thread_.joinable()) thread_.join();
  17015. }
  17016. Server svr_;
  17017. std::thread thread_;
  17018. int port_ = 0;
  17019. };
  17020. TEST_F(OpenStreamTest, Basic) {
  17021. Client cli("127.0.0.1", port_);
  17022. auto handle = cli.open_stream("GET", "/hello");
  17023. EXPECT_TRUE(handle.is_valid());
  17024. EXPECT_EQ("Hello World!", read_all(handle));
  17025. }
  17026. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17027. Client cli("127.0.0.1", port_);
  17028. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17029. ASSERT_TRUE(handle.is_valid());
  17030. EXPECT_EQ("Hello World!", read_all(handle));
  17031. }
  17032. TEST_F(OpenStreamTest, SmallBuffer) {
  17033. Client cli("127.0.0.1", port_);
  17034. auto handle = cli.open_stream("GET", "/hello");
  17035. std::string result;
  17036. char buf[4];
  17037. ssize_t n;
  17038. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17039. result.append(buf, static_cast<size_t>(n));
  17040. EXPECT_EQ("Hello World!", result);
  17041. }
  17042. TEST_F(OpenStreamTest, DefaultHeaders) {
  17043. Client cli("127.0.0.1", port_);
  17044. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17045. {
  17046. auto handle = cli.open_stream("GET", "/echo-headers");
  17047. ASSERT_TRUE(handle.is_valid());
  17048. auto body = read_all(handle);
  17049. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17050. std::string::npos);
  17051. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17052. std::string::npos);
  17053. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17054. }
  17055. // open_stream POST with body and no explicit content_type should NOT add
  17056. // text/plain Content-Type (behavior differs from non-streaming path), but
  17057. // should include Content-Length
  17058. {
  17059. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17060. ASSERT_TRUE(handle.is_valid());
  17061. auto body = read_all(handle);
  17062. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17063. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17064. }
  17065. // open_stream POST with explicit Content-Type should preserve it
  17066. {
  17067. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17068. {{"Content-Type", "application/custom"}},
  17069. "{}", "application/custom");
  17070. ASSERT_TRUE(handle.is_valid());
  17071. auto body = read_all(handle);
  17072. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17073. }
  17074. // User-specified User-Agent must not be overwritten for stream API
  17075. {
  17076. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17077. {{"User-Agent", "MyAgent/1.2"}});
  17078. ASSERT_TRUE(handle.is_valid());
  17079. auto body = read_all(handle);
  17080. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17081. }
  17082. }
  17083. TEST_F(OpenStreamTest, Large) {
  17084. Client cli("127.0.0.1", port_);
  17085. auto handle = cli.open_stream("GET", "/large");
  17086. EXPECT_EQ(10000u, read_all(handle).size());
  17087. }
  17088. TEST_F(OpenStreamTest, ConnectionError) {
  17089. Client cli("127.0.0.1", 9999);
  17090. auto handle = cli.open_stream("GET", "/hello");
  17091. EXPECT_FALSE(handle.is_valid());
  17092. }
  17093. TEST_F(OpenStreamTest, Chunked) {
  17094. Client cli("127.0.0.1", port_);
  17095. auto handle = cli.open_stream("GET", "/chunked");
  17096. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17097. "Transfer-Encoding") == "chunked");
  17098. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17099. }
  17100. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17101. Client cli("127.0.0.1", port_);
  17102. auto handle =
  17103. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17104. ASSERT_TRUE(handle.is_valid());
  17105. // Consume body to allow trailers to be received/parsed
  17106. auto body = read_all(handle);
  17107. // Explicitly parse trailers (ensure trailers are available for assertion)
  17108. handle.parse_trailers_if_needed();
  17109. EXPECT_EQ(std::string("123456789"), body);
  17110. // The response should include a Trailer header declaring both names
  17111. ASSERT_TRUE(handle.response);
  17112. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17113. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17114. handle.response->get_header_value("Trailer"));
  17115. // Prohibited trailer must not be present
  17116. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17117. // Allowed trailer should be present
  17118. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17119. EXPECT_EQ(std::string("yes"),
  17120. handle.response->get_trailer_value("X-Allowed"));
  17121. // Verify trailers are NOT present as regular headers
  17122. EXPECT_EQ(std::string(""),
  17123. handle.response->get_header_value("Content-Length"));
  17124. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17125. }
  17126. static std::thread serve_single_response(std::promise<int> &port_promise,
  17127. const std::string &response) {
  17128. return std::thread([&port_promise, response] {
  17129. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17130. default_socket_options(srv);
  17131. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17132. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17133. sockaddr_in addr{};
  17134. addr.sin_family = AF_INET;
  17135. addr.sin_port = htons(0); // Let OS assign a free port
  17136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17137. int opt = 1;
  17138. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17139. #ifdef _WIN32
  17140. reinterpret_cast<const char *>(&opt),
  17141. #else
  17142. &opt,
  17143. #endif
  17144. sizeof(opt));
  17145. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17146. ::listen(srv, 1) != 0) {
  17147. port_promise.set_value(-1);
  17148. detail::close_socket(srv);
  17149. return;
  17150. }
  17151. socklen_t addr_len = sizeof(addr);
  17152. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17153. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17154. sockaddr_in cli_addr{};
  17155. socklen_t cli_len = sizeof(cli_addr);
  17156. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17157. if (cli != INVALID_SOCKET) {
  17158. // Read the complete HTTP request (until the blank line that terminates
  17159. // headers) before sending the response. If the server closes the socket
  17160. // while the client's request data is still unread in the kernel receive
  17161. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17162. // connection on both sides: it discards the client's receive buffer
  17163. // (which already holds our response) and causes any in-progress write on
  17164. // the client to fail with ECONNRESET. Reading all request data first
  17165. // ensures close() emits a graceful FIN.
  17166. {
  17167. char rbuf[256];
  17168. std::string req;
  17169. while (req.find("\r\n\r\n") == std::string::npos) {
  17170. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17171. if (n <= 0) { break; }
  17172. req.append(rbuf, static_cast<size_t>(n));
  17173. }
  17174. }
  17175. ::send(cli,
  17176. #ifdef _WIN32
  17177. static_cast<const char *>(response.c_str()),
  17178. static_cast<int>(response.size()),
  17179. #else
  17180. response.c_str(), response.size(),
  17181. #endif
  17182. 0);
  17183. detail::close_socket(cli);
  17184. }
  17185. detail::close_socket(srv);
  17186. });
  17187. }
  17188. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17189. #ifndef _WIN32
  17190. signal(SIGPIPE, SIG_IGN);
  17191. #endif
  17192. std::promise<int> port_promise;
  17193. auto port_future = port_promise.get_future();
  17194. auto server_thread =
  17195. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17196. "Content-Type: text/plain\r\n"
  17197. "Content-Length: not-a-number\r\n"
  17198. "Connection: close\r\n"
  17199. "\r\n"
  17200. "hello");
  17201. auto port = port_future.get();
  17202. ASSERT_GT(port, 0);
  17203. Client cli("127.0.0.1", port);
  17204. auto handle = cli.open_stream("GET", "/");
  17205. EXPECT_FALSE(handle.is_valid());
  17206. server_thread.join();
  17207. }
  17208. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17209. #ifndef _WIN32
  17210. signal(SIGPIPE, SIG_IGN);
  17211. #endif
  17212. std::promise<int> port_promise;
  17213. auto port_future = port_promise.get_future();
  17214. auto server_thread = serve_single_response(
  17215. port_promise, "HTTP/1.1 200 OK\r\n"
  17216. "Content-Type: text/plain\r\n"
  17217. "Content-Length: 99999999999999999999999999\r\n"
  17218. "Connection: close\r\n"
  17219. "\r\n"
  17220. "hello");
  17221. auto port = port_future.get();
  17222. ASSERT_GT(port, 0);
  17223. // Historically std::stoull would throw std::out_of_range here and crash
  17224. // the process, then parsing silently clamped to a bogus framing length and
  17225. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17226. // so the stream fails to open, matching the not-a-number case above. The
  17227. // process still must NOT terminate.
  17228. Client cli("127.0.0.1", port);
  17229. auto handle = cli.open_stream("GET", "/");
  17230. EXPECT_FALSE(handle.is_valid());
  17231. server_thread.join();
  17232. }
  17233. // Serves `response` to the single request `fn` makes with a fresh client.
  17234. template <typename Fn>
  17235. static void with_single_response(const std::string &response, Fn fn) {
  17236. #ifndef _WIN32
  17237. signal(SIGPIPE, SIG_IGN);
  17238. #endif
  17239. std::promise<int> port_promise;
  17240. auto port_future = port_promise.get_future();
  17241. auto server_thread = serve_single_response(port_promise, response);
  17242. auto se = detail::scope_exit([&] { server_thread.join(); });
  17243. auto port = port_future.get();
  17244. ASSERT_GT(port, 0);
  17245. Client cli("127.0.0.1", port);
  17246. fn(cli);
  17247. }
  17248. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17249. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17250. // the chunked coding and drop Content-Length, so a front-end that trusts
  17251. // Content-Length would disagree about where the body ends (response
  17252. // smuggling). The client must reject such a response.
  17253. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17254. for (const char *te : {"chunked", "gzip, chunked"}) {
  17255. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17256. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17257. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17258. "5\r\nhello\r\n0\r\n\r\n";
  17259. with_single_response(response, [&](Client &cli) {
  17260. auto res = cli.Get("/");
  17261. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17262. EXPECT_EQ(Error::Read, res.error()) << te;
  17263. });
  17264. with_single_response(response, [&](Client &cli) {
  17265. auto handle = cli.open_stream("GET", "/");
  17266. EXPECT_FALSE(handle.is_valid()) << te;
  17267. EXPECT_EQ(Error::Read, handle.error) << te;
  17268. });
  17269. }
  17270. }
  17271. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17272. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17273. // closing the connection (unlike a request, which must be rejected).
  17274. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17275. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17276. "Transfer-Encoding: chunked\r\n"
  17277. "Connection: close\r\n"
  17278. "\r\n"
  17279. "5\r\nhello\r\n0\r\n\r\n",
  17280. "HTTP/1.1 200 OK\r\n"
  17281. "Transfer-Encoding: gzip\r\n"
  17282. "Connection: close\r\n"
  17283. "\r\n"
  17284. "hello"}) {
  17285. with_single_response(response, [&](Client &cli) {
  17286. auto res = cli.Get("/");
  17287. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17288. EXPECT_EQ("hello", res->body);
  17289. });
  17290. with_single_response(response, [&](Client &cli) {
  17291. auto handle = cli.open_stream("GET", "/");
  17292. ASSERT_TRUE(handle.is_valid()) << response;
  17293. EXPECT_EQ("hello", read_all(handle));
  17294. });
  17295. }
  17296. }
  17297. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17298. // framing headers describe nothing to read and must not be rejected.
  17299. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17300. const std::string framing = "Content-Length: 5\r\n"
  17301. "Transfer-Encoding: chunked\r\n"
  17302. "Connection: close\r\n"
  17303. "\r\n";
  17304. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17305. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17306. });
  17307. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17308. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17309. });
  17310. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17311. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17312. with_single_response(response, [&](Client &cli) {
  17313. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17314. });
  17315. with_single_response(response, [&](Client &cli) {
  17316. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17317. });
  17318. }
  17319. }
  17320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17321. TEST_F(OpenStreamTest, Gzip) {
  17322. Client cli("127.0.0.1", port_);
  17323. auto handle = cli.open_stream("GET", "/compressible", {},
  17324. {{"Accept-Encoding", "gzip"}});
  17325. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17326. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17327. }
  17328. #endif
  17329. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17330. TEST_F(OpenStreamTest, Brotli) {
  17331. Client cli("127.0.0.1", port_);
  17332. auto handle =
  17333. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17334. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17335. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17336. }
  17337. #endif
  17338. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17339. TEST_F(OpenStreamTest, Zstd) {
  17340. Client cli("127.0.0.1", port_);
  17341. auto handle = cli.open_stream("GET", "/compressible", {},
  17342. {{"Accept-Encoding", "zstd"}});
  17343. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17344. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17345. }
  17346. #endif
  17347. #ifdef CPPHTTPLIB_SSL_ENABLED
  17348. class SSLOpenStreamTest : public ::testing::Test {
  17349. protected:
  17350. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17351. void SetUp() override {
  17352. svr_.Get("/hello", [](const Request &, Response &res) {
  17353. res.set_content("Hello SSL World!", "text/plain");
  17354. });
  17355. svr_.Get("/chunked", [](const Request &, Response &res) {
  17356. res.set_chunked_content_provider("text/plain",
  17357. [](size_t offset, DataSink &sink) {
  17358. if (offset < 15) {
  17359. sink.write("chunk", 5);
  17360. return true;
  17361. }
  17362. sink.done();
  17363. return true;
  17364. });
  17365. });
  17366. svr_.Post("/echo", [](const Request &req, Response &res) {
  17367. res.set_content(req.body, req.get_header_value("Content-Type"));
  17368. });
  17369. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17370. std::string body = req.body;
  17371. res.set_chunked_content_provider(
  17372. "text/plain", [body](size_t offset, DataSink &sink) {
  17373. if (offset < body.size()) {
  17374. sink.write(body.data() + offset, body.size() - offset);
  17375. }
  17376. sink.done();
  17377. return true;
  17378. });
  17379. });
  17380. port_ = svr_.bind_to_any_port("127.0.0.1");
  17381. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17382. svr_.wait_until_ready();
  17383. }
  17384. void TearDown() override {
  17385. svr_.stop();
  17386. if (thread_.joinable()) thread_.join();
  17387. }
  17388. SSLServer svr_;
  17389. std::thread thread_;
  17390. int port_ = 0;
  17391. };
  17392. TEST_F(SSLOpenStreamTest, Basic) {
  17393. SSLClient cli("127.0.0.1", port_);
  17394. cli.enable_server_certificate_verification(false);
  17395. auto handle = cli.open_stream("GET", "/hello");
  17396. ASSERT_TRUE(handle.is_valid());
  17397. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17398. }
  17399. TEST_F(SSLOpenStreamTest, Chunked) {
  17400. SSLClient cli("127.0.0.1", port_);
  17401. cli.enable_server_certificate_verification(false);
  17402. auto handle = cli.open_stream("GET", "/chunked");
  17403. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17404. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17405. "Transfer-Encoding") == "chunked");
  17406. auto body = read_all(handle);
  17407. EXPECT_EQ("chunkchunkchunk", body);
  17408. }
  17409. TEST_F(SSLOpenStreamTest, Post) {
  17410. SSLClient cli("127.0.0.1", port_);
  17411. cli.enable_server_certificate_verification(false);
  17412. auto handle =
  17413. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17414. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17415. EXPECT_EQ(200, handle.response->status);
  17416. auto body = read_all(handle);
  17417. EXPECT_EQ("Hello SSL POST", body);
  17418. }
  17419. TEST_F(SSLOpenStreamTest, PostChunked) {
  17420. SSLClient cli("127.0.0.1", port_);
  17421. cli.enable_server_certificate_verification(false);
  17422. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17423. "Chunked SSL Data", "text/plain");
  17424. ASSERT_TRUE(handle.is_valid());
  17425. EXPECT_EQ(200, handle.response->status);
  17426. auto body = read_all(handle);
  17427. EXPECT_EQ("Chunked SSL Data", body);
  17428. }
  17429. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17430. // Content-Length is terminated by the server closing the connection. When the
  17431. // SSL peer sends a close_notify after the body, the client must treat it as a
  17432. // clean EOF and return a successful response rather than an error.
  17433. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17435. ASSERT_TRUE(svr.is_valid());
  17436. svr.set_keep_alive_max_count(1);
  17437. const std::string expected_body = "Hello from connection-close response!";
  17438. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17439. res.set_content_provider("text/plain",
  17440. [&](size_t offset, DataSink &sink) -> bool {
  17441. if (offset < expected_body.size()) {
  17442. sink.write(expected_body.data() + offset,
  17443. expected_body.size() - offset);
  17444. }
  17445. sink.done();
  17446. return true;
  17447. });
  17448. });
  17449. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17450. auto se = detail::scope_exit([&] {
  17451. svr.stop();
  17452. listen_thread.join();
  17453. ASSERT_FALSE(svr.is_running());
  17454. });
  17455. svr.wait_until_ready();
  17456. SSLClient cli(HOST, PORT);
  17457. cli.enable_server_certificate_verification(false);
  17458. auto res = cli.Get("/no-content-length");
  17459. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17460. EXPECT_EQ(StatusCode::OK_200, res->status);
  17461. EXPECT_EQ(expected_body, res->body);
  17462. }
  17463. #endif // CPPHTTPLIB_SSL_ENABLED
  17464. //==============================================================================
  17465. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17466. // results for various scenarios.
  17467. //==============================================================================
  17468. TEST(ParityTest, GetVsOpenStream) {
  17469. Server svr;
  17470. const std::string path = "/parity";
  17471. const std::string content = "Parity test content: hello world";
  17472. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17473. res.set_content(content, "text/plain");
  17474. });
  17475. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17476. auto se = detail::scope_exit([&] {
  17477. svr.stop();
  17478. t.join();
  17479. ASSERT_FALSE(svr.is_running());
  17480. });
  17481. svr.wait_until_ready();
  17482. Client cli(HOST, PORT);
  17483. // Non-stream path
  17484. auto r1 = cli.Get(path);
  17485. ASSERT_TRUE(r1);
  17486. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17487. // Stream path
  17488. auto h = cli.open_stream("GET", path);
  17489. ASSERT_TRUE(h.is_valid());
  17490. EXPECT_EQ(r1->body, read_all(h));
  17491. }
  17492. // Helper to compress data with provided compressor type T
  17493. template <typename Compressor>
  17494. static std::string compress_payload_for_parity(const std::string &in) {
  17495. std::string out;
  17496. Compressor compressor;
  17497. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17498. [&](const char *data, size_t n) {
  17499. out.append(data, n);
  17500. return true;
  17501. });
  17502. EXPECT_TRUE(ok);
  17503. return out;
  17504. }
  17505. // Helper function for compression parity tests
  17506. template <typename Compressor>
  17507. static void test_compression_parity(const std::string &original,
  17508. const std::string &path,
  17509. const std::string &encoding) {
  17510. const std::string compressed =
  17511. compress_payload_for_parity<Compressor>(original);
  17512. Server svr;
  17513. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17514. res.set_content(compressed, "application/octet-stream");
  17515. res.set_header("Content-Encoding", encoding);
  17516. });
  17517. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. t.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. });
  17523. svr.wait_until_ready();
  17524. Client cli(HOST, PORT);
  17525. // Non-streaming
  17526. {
  17527. auto res = cli.Get(path);
  17528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17529. EXPECT_EQ(StatusCode::OK_200, res->status);
  17530. EXPECT_EQ(original, res->body);
  17531. }
  17532. // Streaming
  17533. {
  17534. auto h = cli.open_stream("GET", path);
  17535. ASSERT_TRUE(h.is_valid());
  17536. EXPECT_EQ(original, read_all(h));
  17537. }
  17538. }
  17539. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17540. TEST(ParityTest, Gzip) {
  17541. test_compression_parity<detail::gzip_compressor>(
  17542. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17543. }
  17544. #endif
  17545. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17546. TEST(ParityTest, Brotli) {
  17547. test_compression_parity<detail::brotli_compressor>(
  17548. "Hello, brotli parity test payload", "/parity-br", "br");
  17549. }
  17550. #endif
  17551. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17552. TEST(ParityTest, Zstd) {
  17553. test_compression_parity<detail::zstd_compressor>(
  17554. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17555. }
  17556. #endif
  17557. //==============================================================================
  17558. // New Stream API Tests
  17559. //==============================================================================
  17560. inline std::string read_body(httplib::stream::Result &result) {
  17561. std::string body;
  17562. while (result.next()) {
  17563. body.append(result.data(), result.size());
  17564. }
  17565. return body;
  17566. }
  17567. TEST(ClientConnectionTest, Basic) {
  17568. httplib::ClientConnection conn;
  17569. EXPECT_FALSE(conn.is_open());
  17570. conn.sock = 1;
  17571. EXPECT_TRUE(conn.is_open());
  17572. httplib::ClientConnection conn2(std::move(conn));
  17573. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17574. conn2.sock = INVALID_SOCKET;
  17575. }
  17576. // Unified test server for all stream::* tests
  17577. class StreamApiTest : public ::testing::Test {
  17578. protected:
  17579. void SetUp() override {
  17580. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17581. res.set_content("Hello World!", "text/plain");
  17582. });
  17583. svr_.Get("/echo-params",
  17584. [](const httplib::Request &req, httplib::Response &res) {
  17585. std::string r;
  17586. for (const auto &p : req.params) {
  17587. if (!r.empty()) r += "&";
  17588. r += p.first + "=" + p.second;
  17589. }
  17590. res.set_content(r, "text/plain");
  17591. });
  17592. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17593. res.set_content(req.body, req.get_header_value("Content-Type"));
  17594. });
  17595. svr_.Post("/echo-headers",
  17596. [](const httplib::Request &req, httplib::Response &res) {
  17597. std::string r;
  17598. for (const auto &h : req.headers)
  17599. r += h.first + ": " + h.second + "\n";
  17600. res.set_content(r, "text/plain");
  17601. });
  17602. svr_.Post("/echo-params",
  17603. [](const httplib::Request &req, httplib::Response &res) {
  17604. std::string r = "params:";
  17605. for (const auto &p : req.params)
  17606. r += p.first + "=" + p.second + ";";
  17607. res.set_content(r + " body:" + req.body, "text/plain");
  17608. });
  17609. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17610. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17611. });
  17612. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17613. res.set_content("PUT:" + req.body, "text/plain");
  17614. });
  17615. svr_.Patch("/echo",
  17616. [](const httplib::Request &req, httplib::Response &res) {
  17617. res.set_content("PATCH:" + req.body, "text/plain");
  17618. });
  17619. svr_.Delete(
  17620. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17621. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17622. "text/plain");
  17623. });
  17624. svr_.Get("/head-test",
  17625. [](const httplib::Request &, httplib::Response &res) {
  17626. res.set_content("body for HEAD", "text/plain");
  17627. });
  17628. svr_.Options("/options",
  17629. [](const httplib::Request &, httplib::Response &res) {
  17630. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17631. });
  17632. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17633. svr_.wait_until_ready();
  17634. }
  17635. void TearDown() override {
  17636. svr_.stop();
  17637. if (thread_.joinable()) thread_.join();
  17638. }
  17639. httplib::Server svr_;
  17640. std::thread thread_;
  17641. };
  17642. // stream::Get tests
  17643. TEST_F(StreamApiTest, GetBasic) {
  17644. httplib::Client cli(HOST, PORT);
  17645. auto result = httplib::stream::Get(cli, "/hello");
  17646. ASSERT_TRUE(result.is_valid());
  17647. EXPECT_EQ(200, result.status());
  17648. EXPECT_EQ("Hello World!", read_body(result));
  17649. }
  17650. TEST_F(StreamApiTest, GetWithParams) {
  17651. httplib::Client cli(HOST, PORT);
  17652. httplib::Params params{{"foo", "bar"}};
  17653. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17654. ASSERT_TRUE(result.is_valid());
  17655. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17656. }
  17657. TEST_F(StreamApiTest, GetConnectionError) {
  17658. httplib::Client cli(HOST, 9999);
  17659. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17660. }
  17661. TEST_F(StreamApiTest, Get404) {
  17662. httplib::Client cli(HOST, PORT);
  17663. auto result = httplib::stream::Get(cli, "/nonexistent");
  17664. EXPECT_TRUE(result.is_valid());
  17665. EXPECT_EQ(404, result.status());
  17666. }
  17667. // stream::Post tests
  17668. TEST_F(StreamApiTest, PostBasic) {
  17669. httplib::Client cli(HOST, PORT);
  17670. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17671. "application/json");
  17672. ASSERT_TRUE(result.is_valid());
  17673. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17674. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17675. }
  17676. TEST_F(StreamApiTest, PostWithHeaders) {
  17677. httplib::Client cli(HOST, PORT);
  17678. httplib::Headers headers{{"X-Custom", "value"}};
  17679. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17680. "text/plain");
  17681. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17682. }
  17683. TEST_F(StreamApiTest, PostWithParams) {
  17684. httplib::Client cli(HOST, PORT);
  17685. httplib::Params params{{"k", "v"}};
  17686. auto result =
  17687. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17688. auto body = read_body(result);
  17689. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17690. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17691. }
  17692. TEST_F(StreamApiTest, PostLarge) {
  17693. httplib::Client cli(HOST, PORT);
  17694. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17695. size_t total = 0;
  17696. while (result.next()) {
  17697. total += result.size();
  17698. }
  17699. EXPECT_EQ(100u * 1024u, total);
  17700. }
  17701. // stream::Put/Patch tests
  17702. TEST_F(StreamApiTest, PutAndPatch) {
  17703. httplib::Client cli(HOST, PORT);
  17704. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17705. EXPECT_EQ("PUT:test", read_body(put));
  17706. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17707. EXPECT_EQ("PATCH:test", read_body(patch));
  17708. }
  17709. // stream::Delete tests
  17710. TEST_F(StreamApiTest, Delete) {
  17711. httplib::Client cli(HOST, PORT);
  17712. auto del1 = httplib::stream::Delete(cli, "/resource");
  17713. EXPECT_EQ("Deleted", read_body(del1));
  17714. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17715. EXPECT_EQ("Deleted:data", read_body(del2));
  17716. }
  17717. // stream::Head/Options tests
  17718. TEST_F(StreamApiTest, HeadAndOptions) {
  17719. httplib::Client cli(HOST, PORT);
  17720. auto head = httplib::stream::Head(cli, "/head-test");
  17721. EXPECT_TRUE(head.is_valid());
  17722. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17723. auto opts = httplib::stream::Options(cli, "/options");
  17724. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17725. }
  17726. // SSL stream::* tests
  17727. #ifdef CPPHTTPLIB_SSL_ENABLED
  17728. class SSLStreamApiTest : public ::testing::Test {
  17729. protected:
  17730. void SetUp() override {
  17731. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17732. res.set_content("Hello SSL!", "text/plain");
  17733. });
  17734. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17735. res.set_content(req.body, "text/plain");
  17736. });
  17737. port_ = svr_.bind_to_any_port("127.0.0.1");
  17738. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17739. svr_.wait_until_ready();
  17740. }
  17741. void TearDown() override {
  17742. svr_.stop();
  17743. if (thread_.joinable()) thread_.join();
  17744. }
  17745. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17746. std::thread thread_;
  17747. int port_ = 0;
  17748. };
  17749. TEST_F(SSLStreamApiTest, GetAndPost) {
  17750. httplib::SSLClient cli("127.0.0.1", port_);
  17751. cli.enable_server_certificate_verification(false);
  17752. auto get = httplib::stream::Get(cli, "/hello");
  17753. EXPECT_EQ("Hello SSL!", read_body(get));
  17754. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17755. EXPECT_EQ("test", read_body(post));
  17756. }
  17757. #endif
  17758. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17759. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17760. // BodyReader
  17761. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17762. // Test that read timeout during streaming is detected
  17763. // Use a large content-length response where server delays mid-stream
  17764. Server svr;
  17765. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17766. // Send a large response with delay in the middle
  17767. res.set_content_provider(
  17768. 1000, // content_length
  17769. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17770. if (offset < 100) {
  17771. // Send first 100 bytes immediately
  17772. std::string data(100, 'A');
  17773. sink.write(data.c_str(), data.size());
  17774. return true;
  17775. }
  17776. // Then delay longer than client timeout
  17777. std::this_thread::sleep_for(std::chrono::seconds(3));
  17778. std::string data(900, 'B');
  17779. sink.write(data.c_str(), data.size());
  17780. return true;
  17781. });
  17782. });
  17783. auto port = 8091;
  17784. std::thread t([&]() { svr.listen("localhost", port); });
  17785. svr.wait_until_ready();
  17786. Client cli("localhost", port);
  17787. cli.set_read_timeout(1, 0); // 1 second timeout
  17788. auto handle = cli.open_stream("GET", "/slow-stream");
  17789. ASSERT_TRUE(handle.is_valid());
  17790. char buf[256];
  17791. ssize_t total = 0;
  17792. ssize_t n;
  17793. bool got_error = false;
  17794. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17795. total += n;
  17796. }
  17797. if (n < 0) {
  17798. got_error = true;
  17799. // Should be timeout or read error
  17800. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17801. handle.get_read_error() == Error::Read)
  17802. << "Actual error: " << to_string(handle.get_read_error());
  17803. }
  17804. // Either we got an error, or we got less data than expected
  17805. EXPECT_TRUE(got_error || total < 1000)
  17806. << "Expected timeout but got all " << total << " bytes";
  17807. svr.stop();
  17808. t.join();
  17809. }
  17810. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17811. // Test connection closed detection via BodyReader
  17812. Server svr;
  17813. std::atomic<bool> close_now{false};
  17814. svr.Get("/will-close", [&](const Request &, Response &res) {
  17815. res.set_content_provider(
  17816. 10000, // Large content_length that we won't fully send
  17817. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17818. if (offset < 100) {
  17819. std::string data(100, 'X');
  17820. sink.write(data.c_str(), data.size());
  17821. return true;
  17822. }
  17823. // Wait for signal then abort
  17824. while (!close_now) {
  17825. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17826. }
  17827. return false; // Abort - server will close connection
  17828. });
  17829. });
  17830. auto port = 8092;
  17831. std::thread t([&]() { svr.listen("localhost", port); });
  17832. svr.wait_until_ready();
  17833. Client cli("localhost", port);
  17834. auto handle = cli.open_stream("GET", "/will-close");
  17835. ASSERT_TRUE(handle.is_valid());
  17836. char buf[256];
  17837. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17838. EXPECT_GT(n, 0) << "First read should succeed";
  17839. // Signal server to close
  17840. close_now = true;
  17841. // Keep reading until error or EOF
  17842. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17843. // Keep reading
  17844. }
  17845. // Should get an error since content_length wasn't satisfied
  17846. if (n < 0) {
  17847. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17848. handle.get_read_error() == Error::Read)
  17849. << "Actual error: " << to_string(handle.get_read_error());
  17850. }
  17851. svr.stop();
  17852. t.join();
  17853. }
  17854. #ifdef CPPHTTPLIB_SSL_ENABLED
  17855. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17856. // Test that read timeout during SSL streaming is detected
  17857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17858. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17859. res.set_content_provider(
  17860. 1000, "text/plain",
  17861. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17862. if (offset < 100) {
  17863. std::string data(100, 'A');
  17864. sink.write(data.c_str(), data.size());
  17865. return true;
  17866. }
  17867. std::this_thread::sleep_for(std::chrono::seconds(3));
  17868. std::string data(900, 'B');
  17869. sink.write(data.c_str(), data.size());
  17870. return true;
  17871. });
  17872. });
  17873. auto port = 8093;
  17874. std::thread t([&]() { svr.listen("localhost", port); });
  17875. svr.wait_until_ready();
  17876. SSLClient cli("localhost", port);
  17877. cli.enable_server_certificate_verification(false);
  17878. cli.set_read_timeout(1, 0); // 1 second timeout
  17879. auto handle = cli.open_stream("GET", "/slow-stream");
  17880. ASSERT_TRUE(handle.is_valid());
  17881. char buf[256];
  17882. ssize_t total = 0;
  17883. ssize_t n;
  17884. bool got_error = false;
  17885. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17886. total += n;
  17887. }
  17888. if (n < 0) {
  17889. got_error = true;
  17890. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17891. handle.get_read_error() == Error::Read)
  17892. << "Actual error: " << to_string(handle.get_read_error());
  17893. }
  17894. EXPECT_TRUE(got_error || total < 1000)
  17895. << "Expected timeout but got all " << total << " bytes";
  17896. svr.stop();
  17897. t.join();
  17898. }
  17899. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17900. // Test SSL connection closed detection
  17901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17902. std::atomic<bool> close_now{false};
  17903. svr.Get("/will-close", [&](const Request &, Response &res) {
  17904. res.set_content_provider(
  17905. 10000, "text/plain",
  17906. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17907. if (offset < 100) {
  17908. std::string data(100, 'X');
  17909. sink.write(data.c_str(), data.size());
  17910. return true;
  17911. }
  17912. while (!close_now) {
  17913. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17914. }
  17915. return false;
  17916. });
  17917. });
  17918. auto port = 8094;
  17919. std::thread t([&]() { svr.listen("localhost", port); });
  17920. svr.wait_until_ready();
  17921. SSLClient cli("localhost", port);
  17922. cli.enable_server_certificate_verification(false);
  17923. auto handle = cli.open_stream("GET", "/will-close");
  17924. ASSERT_TRUE(handle.is_valid());
  17925. char buf[256];
  17926. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17927. EXPECT_GT(n, 0);
  17928. // Signal server to close
  17929. close_now = true;
  17930. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17931. // Keep reading
  17932. }
  17933. if (n < 0) {
  17934. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17935. handle.get_read_error() == Error::Read)
  17936. << "Actual error: " << to_string(handle.get_read_error());
  17937. }
  17938. svr.stop();
  17939. t.join();
  17940. }
  17941. #endif
  17942. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17943. using namespace httplib;
  17944. // Create a test file
  17945. const char *fname = "etag_testfile.txt";
  17946. const char *content = "etag-content";
  17947. {
  17948. std::ofstream ofs(fname);
  17949. ofs << content;
  17950. ASSERT_TRUE(ofs.good());
  17951. }
  17952. Server svr;
  17953. svr.set_mount_point("/static", ".");
  17954. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17955. svr.wait_until_ready();
  17956. Client cli(HOST, PORT);
  17957. // First request: should get 200 with ETag header
  17958. auto res1 = cli.Get("/static/etag_testfile.txt");
  17959. ASSERT_TRUE(res1);
  17960. ASSERT_EQ(200, res1->status);
  17961. ASSERT_TRUE(res1->has_header("ETag"));
  17962. std::string etag = res1->get_header_value("ETag");
  17963. EXPECT_FALSE(etag.empty());
  17964. // Verify ETag format: W/"hex-hex"
  17965. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17966. EXPECT_EQ('W', etag[0]);
  17967. EXPECT_EQ('/', etag[1]);
  17968. EXPECT_EQ('"', etag[2]);
  17969. EXPECT_EQ('"', etag.back());
  17970. // Exact match: expect 304 Not Modified
  17971. Headers h2 = {{"If-None-Match", etag}};
  17972. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17973. ASSERT_TRUE(res2);
  17974. EXPECT_EQ(304, res2->status);
  17975. // Wildcard match: expect 304 Not Modified
  17976. Headers h3 = {{"If-None-Match", "*"}};
  17977. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17978. ASSERT_TRUE(res3);
  17979. EXPECT_EQ(304, res3->status);
  17980. // Non-matching ETag: expect 200
  17981. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17982. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17983. ASSERT_TRUE(res4);
  17984. EXPECT_EQ(200, res4->status);
  17985. // Multiple ETags with one matching: expect 304
  17986. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17987. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17988. ASSERT_TRUE(res5);
  17989. EXPECT_EQ(304, res5->status);
  17990. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17991. // that equivalent to the single comma-separated list above, so the match on
  17992. // the second line must still be found.
  17993. Headers h6;
  17994. h6.emplace("If-None-Match", "W/\"other\"");
  17995. h6.emplace("If-None-Match", etag);
  17996. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17997. ASSERT_TRUE(res6);
  17998. EXPECT_EQ(304, res6->status);
  17999. svr.stop();
  18000. t.join();
  18001. std::remove(fname);
  18002. }
  18003. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18004. using namespace httplib;
  18005. Server svr;
  18006. svr.set_mount_point("/static", ".");
  18007. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18008. svr.wait_until_ready();
  18009. Client cli(HOST, PORT);
  18010. // Send If-None-Match: * to a non-existent file
  18011. Headers h = {{"If-None-Match", "*"}};
  18012. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18014. EXPECT_EQ(404, res->status);
  18015. svr.stop();
  18016. t.join();
  18017. }
  18018. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18019. using namespace httplib;
  18020. // Create a test file
  18021. const char *fname = "etag_boundary_testfile.txt";
  18022. const char *content = "boundary-test";
  18023. {
  18024. std::ofstream ofs(fname);
  18025. ofs << content;
  18026. ASSERT_TRUE(ofs.good());
  18027. }
  18028. Server svr;
  18029. svr.set_mount_point("/static", ".");
  18030. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18031. svr.wait_until_ready();
  18032. Client cli(HOST, PORT);
  18033. // Get the actual ETag
  18034. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18035. ASSERT_TRUE(res1);
  18036. ASSERT_EQ(200, res1->status);
  18037. ASSERT_TRUE(res1->has_header("ETag"));
  18038. std::string etag = res1->get_header_value("ETag");
  18039. // Test 1: Very long ETag value (longer than actual ETag)
  18040. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18041. Headers h1 = {{"If-None-Match", "W/"
  18042. "\"very-long-etag-value-that-is-much-longer-"
  18043. "than-the-actual-etag-value\""}};
  18044. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18045. ASSERT_TRUE(res2);
  18046. EXPECT_EQ(200, res2->status); // Should not match
  18047. // Test 2: Long string followed by wildcard
  18048. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18049. // string)
  18050. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18051. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18052. ASSERT_TRUE(res3);
  18053. EXPECT_EQ(304, res3->status); // Should match on "*"
  18054. // Test 3: Wildcard followed by long string
  18055. // Should match on "*" immediately and return 304
  18056. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18057. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18058. ASSERT_TRUE(res4);
  18059. EXPECT_EQ(304, res4->status); // Should match on "*"
  18060. // Test 4: Multiple long non-matching values
  18061. // Should NOT match and return 200 (test that all comparisons are safe)
  18062. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18063. "W/\"second-long-non-matching-value\", "
  18064. "W/\"third-long-non-matching-value\""}};
  18065. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18066. ASSERT_TRUE(res5);
  18067. EXPECT_EQ(200, res5->status); // Should not match
  18068. // Test 5: Single character that is not "*" (edge case)
  18069. Headers h5 = {{"If-None-Match", "X"}};
  18070. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18071. ASSERT_TRUE(res6);
  18072. EXPECT_EQ(200, res6->status); // Should not match
  18073. svr.stop();
  18074. t.join();
  18075. std::remove(fname);
  18076. }
  18077. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18078. using namespace httplib;
  18079. // Create a test file
  18080. const char *fname = "ims_testfile.txt";
  18081. const char *content = "if-modified-since-test";
  18082. {
  18083. std::ofstream ofs(fname);
  18084. ofs << content;
  18085. ASSERT_TRUE(ofs.good());
  18086. }
  18087. Server svr;
  18088. svr.set_mount_point("/static", ".");
  18089. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18090. svr.wait_until_ready();
  18091. Client cli(HOST, PORT);
  18092. // First request: should get 200 with Last-Modified header
  18093. auto res1 = cli.Get("/static/ims_testfile.txt");
  18094. ASSERT_TRUE(res1);
  18095. ASSERT_EQ(200, res1->status);
  18096. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18097. std::string last_modified = res1->get_header_value("Last-Modified");
  18098. EXPECT_FALSE(last_modified.empty());
  18099. // If-Modified-Since with same time: expect 304
  18100. Headers h2 = {{"If-Modified-Since", last_modified}};
  18101. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18102. ASSERT_TRUE(res2);
  18103. EXPECT_EQ(304, res2->status);
  18104. // If-Modified-Since with future time: expect 304
  18105. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18106. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18107. ASSERT_TRUE(res3);
  18108. EXPECT_EQ(304, res3->status);
  18109. // If-Modified-Since with past time: expect 200
  18110. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18111. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18112. ASSERT_TRUE(res4);
  18113. EXPECT_EQ(200, res4->status);
  18114. // If-None-Match takes precedence over If-Modified-Since
  18115. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18116. ASSERT_TRUE(res1->has_header("ETag"));
  18117. std::string etag = res1->get_header_value("ETag");
  18118. Headers h5 = {{"If-None-Match", etag},
  18119. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18120. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18121. ASSERT_TRUE(res5);
  18122. EXPECT_EQ(304, res5->status);
  18123. svr.stop();
  18124. t.join();
  18125. std::remove(fname);
  18126. }
  18127. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18128. using namespace httplib;
  18129. Server svr;
  18130. // Endpoint that returns compressible content
  18131. svr.Get("/compressible", [](const Request &, Response &res) {
  18132. // Return a large enough body to trigger compression
  18133. std::string body(1000, 'a');
  18134. res.set_content(body, "text/plain");
  18135. });
  18136. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18137. svr.wait_until_ready();
  18138. Client cli(HOST, PORT);
  18139. // Request with gzip support: should get Vary header when compressed
  18140. cli.set_compress(true);
  18141. auto res1 = cli.Get("/compressible");
  18142. ASSERT_TRUE(res1);
  18143. EXPECT_EQ(200, res1->status);
  18144. // If Content-Encoding is set, Vary should also be set
  18145. if (res1->has_header("Content-Encoding")) {
  18146. EXPECT_TRUE(res1->has_header("Vary"));
  18147. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18148. }
  18149. // Request without Accept-Encoding header: should not have compression
  18150. Headers h_no_compress;
  18151. auto res2 = cli.Get("/compressible", h_no_compress);
  18152. ASSERT_TRUE(res2);
  18153. EXPECT_EQ(200, res2->status);
  18154. // Verify Vary header is present when compression is applied
  18155. // (the exact behavior depends on server configuration)
  18156. svr.stop();
  18157. t.join();
  18158. }
  18159. TEST(ETagTest, IfRangeWithETag) {
  18160. using namespace httplib;
  18161. // Create a test file with known content
  18162. const char *fname = "if_range_testfile.txt";
  18163. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18164. {
  18165. std::ofstream ofs(fname);
  18166. ofs << content;
  18167. ASSERT_TRUE(ofs.good());
  18168. }
  18169. Server svr;
  18170. svr.set_mount_point("/static", ".");
  18171. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18172. svr.wait_until_ready();
  18173. Client cli(HOST, PORT);
  18174. // First request: get ETag
  18175. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18176. ASSERT_TRUE(res1);
  18177. ASSERT_EQ(200, res1->status);
  18178. ASSERT_TRUE(res1->has_header("ETag"));
  18179. std::string etag = res1->get_header_value("ETag");
  18180. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18181. // Since our server generates weak ETags (W/"..."), If-Range with our
  18182. // ETag should NOT result in partial content - it should return full content.
  18183. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18184. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18185. ASSERT_TRUE(res2);
  18186. // Weak ETag in If-Range -> full content (200), not partial (206)
  18187. EXPECT_EQ(200, res2->status);
  18188. EXPECT_EQ(content, res2->body);
  18189. EXPECT_FALSE(res2->has_header("Content-Range"));
  18190. // Range request with non-matching If-Range (ETag): should get 200 (full
  18191. // content)
  18192. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18193. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18194. ASSERT_TRUE(res3);
  18195. EXPECT_EQ(200, res3->status);
  18196. EXPECT_EQ(content, res3->body);
  18197. EXPECT_FALSE(res3->has_header("Content-Range"));
  18198. // Range request with strong ETag (hypothetical - our server doesn't generate
  18199. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18200. // should return full content)
  18201. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18202. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18203. ASSERT_TRUE(res4);
  18204. EXPECT_EQ(200, res4->status);
  18205. EXPECT_EQ(content, res4->body);
  18206. EXPECT_FALSE(res4->has_header("Content-Range"));
  18207. svr.stop();
  18208. t.join();
  18209. std::remove(fname);
  18210. }
  18211. TEST(ETagTest, IfRangeWithDate) {
  18212. using namespace httplib;
  18213. // Create a test file
  18214. const char *fname = "if_range_date_testfile.txt";
  18215. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18216. {
  18217. std::ofstream ofs(fname);
  18218. ofs << content;
  18219. ASSERT_TRUE(ofs.good());
  18220. }
  18221. Server svr;
  18222. svr.set_mount_point("/static", ".");
  18223. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18224. svr.wait_until_ready();
  18225. Client cli(HOST, PORT);
  18226. // First request: get Last-Modified
  18227. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18228. ASSERT_TRUE(res1);
  18229. ASSERT_EQ(200, res1->status);
  18230. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18231. std::string last_modified = res1->get_header_value("Last-Modified");
  18232. // Range request with matching If-Range (date): should get 206
  18233. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18234. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18235. ASSERT_TRUE(res2);
  18236. EXPECT_EQ(206, res2->status);
  18237. EXPECT_EQ("FGHIJ", res2->body);
  18238. // Range request with old If-Range date: should get 200 (full content)
  18239. Headers h3 = {{"Range", "bytes=5-9"},
  18240. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18241. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18242. ASSERT_TRUE(res3);
  18243. EXPECT_EQ(200, res3->status);
  18244. EXPECT_EQ(content, res3->body);
  18245. // Range request with future If-Range date: should get 206
  18246. Headers h4 = {{"Range", "bytes=0-4"},
  18247. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18248. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18249. ASSERT_TRUE(res4);
  18250. EXPECT_EQ(206, res4->status);
  18251. EXPECT_EQ("ABCDE", res4->body);
  18252. svr.stop();
  18253. t.join();
  18254. std::remove(fname);
  18255. }
  18256. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18257. using namespace httplib;
  18258. const char *fname = "etag_malformed.txt";
  18259. const char *content = "malformed-etag";
  18260. {
  18261. std::ofstream ofs(fname);
  18262. ofs << content;
  18263. ASSERT_TRUE(ofs.good());
  18264. }
  18265. Server svr;
  18266. svr.set_mount_point("/static", ".");
  18267. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18268. svr.wait_until_ready();
  18269. Client cli(HOST, PORT);
  18270. // baseline: should get 200 and an ETag
  18271. auto res1 = cli.Get("/static/etag_malformed.txt");
  18272. ASSERT_TRUE(res1);
  18273. ASSERT_EQ(200, res1->status);
  18274. ASSERT_TRUE(res1->has_header("ETag"));
  18275. // Malformed ETag value (missing quotes) should be treated as non-matching
  18276. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18277. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18278. ASSERT_TRUE(res_bad);
  18279. EXPECT_EQ(200, res_bad->status);
  18280. // Whitespace-only header value should be considered invalid / non-matching
  18281. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18282. "Host: localhost\r\n"
  18283. "If-None-Match: \r\n"
  18284. "Connection: close\r\n"
  18285. "\r\n";
  18286. std::string out;
  18287. ASSERT_TRUE(send_request(5, raw_req, &out));
  18288. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18289. svr.stop();
  18290. t.join();
  18291. std::remove(fname);
  18292. }
  18293. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18294. using namespace httplib;
  18295. const char *fname = "ims_invalid_format.txt";
  18296. const char *content = "ims-bad-format";
  18297. {
  18298. std::ofstream ofs(fname);
  18299. ofs << content;
  18300. ASSERT_TRUE(ofs.good());
  18301. }
  18302. Server svr;
  18303. svr.set_mount_point("/static", ".");
  18304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18305. svr.wait_until_ready();
  18306. Client cli(HOST, PORT);
  18307. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18308. ASSERT_TRUE(res1);
  18309. ASSERT_EQ(200, res1->status);
  18310. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18311. // If-Modified-Since with invalid format should not result in 304
  18312. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18313. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18314. ASSERT_TRUE(res_bad);
  18315. EXPECT_EQ(200, res_bad->status);
  18316. // If-Range with invalid date format should be treated as mismatch -> full
  18317. // content (200)
  18318. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18319. {"If-Range", "invalid-date"}};
  18320. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18321. ASSERT_TRUE(res_ifrange);
  18322. EXPECT_EQ(200, res_ifrange->status);
  18323. svr.stop();
  18324. t.join();
  18325. std::remove(fname);
  18326. }
  18327. TEST(ETagTest, IfRangeWithMalformedETag) {
  18328. using namespace httplib;
  18329. const char *fname = "ifrange_malformed.txt";
  18330. const std::string content = "0123456789";
  18331. {
  18332. std::ofstream ofs(fname);
  18333. ofs << content;
  18334. ASSERT_TRUE(ofs.good());
  18335. }
  18336. Server svr;
  18337. svr.set_mount_point("/static", ".");
  18338. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18339. svr.wait_until_ready();
  18340. Client cli(HOST, PORT);
  18341. // First request: get ETag
  18342. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18343. ASSERT_TRUE(res1);
  18344. ASSERT_EQ(200, res1->status);
  18345. ASSERT_TRUE(res1->has_header("ETag"));
  18346. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18347. // full content (200)
  18348. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18349. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18350. ASSERT_TRUE(res2);
  18351. EXPECT_EQ(200, res2->status);
  18352. EXPECT_EQ(content, res2->body);
  18353. svr.stop();
  18354. t.join();
  18355. std::remove(fname);
  18356. }
  18357. TEST(ETagTest, ExtremeLargeDateValues) {
  18358. using namespace httplib;
  18359. const char *fname = "ims_extreme_date.txt";
  18360. const char *content = "ims-extreme-date";
  18361. {
  18362. std::ofstream ofs(fname);
  18363. ofs << content;
  18364. ASSERT_TRUE(ofs.good());
  18365. }
  18366. Server svr;
  18367. svr.set_mount_point("/static", ".");
  18368. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18369. svr.wait_until_ready();
  18370. Client cli(HOST, PORT);
  18371. auto res1 = cli.Get(std::string("/static/") + fname);
  18372. ASSERT_TRUE(res1);
  18373. ASSERT_EQ(200, res1->status);
  18374. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18375. // Extremely large year that may overflow date parsing routines.
  18376. Headers h_large_date = {
  18377. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18378. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18379. ASSERT_TRUE(res_bad);
  18380. // Expect server to treat this as invalid/mismatch and return full content
  18381. EXPECT_EQ(200, res_bad->status);
  18382. // If-Range with extremely large date should be treated as mismatch -> full
  18383. // content (200)
  18384. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18385. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18386. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18387. ASSERT_TRUE(res_ifrange);
  18388. EXPECT_EQ(200, res_ifrange->status);
  18389. svr.stop();
  18390. t.join();
  18391. std::remove(fname);
  18392. }
  18393. TEST(ETagTest, NegativeFileModificationTime) {
  18394. using namespace httplib;
  18395. const char *fname = "ims_negative_mtime.txt";
  18396. const std::string content = "negative-mtime";
  18397. {
  18398. std::ofstream ofs(fname);
  18399. ofs << content;
  18400. ASSERT_TRUE(ofs.good());
  18401. }
  18402. // Try to set file mtime to a negative value. This may fail on some
  18403. // platforms/filesystems; if it fails, the test will still verify server
  18404. // behaves safely by performing a regular conditional request.
  18405. #if defined(__APPLE__) || defined(__linux__)
  18406. bool set_negative = false;
  18407. do {
  18408. struct timeval times[2];
  18409. // access time: now
  18410. times[0].tv_sec = time(nullptr);
  18411. times[0].tv_usec = 0;
  18412. // modification time: negative (e.g., -1)
  18413. times[1].tv_sec = -1;
  18414. times[1].tv_usec = 0;
  18415. if (utimes(fname, times) == 0) { set_negative = true; }
  18416. } while (0);
  18417. #else
  18418. bool set_negative = false;
  18419. #endif
  18420. Server svr;
  18421. svr.set_mount_point("/static", ".");
  18422. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18423. svr.wait_until_ready();
  18424. Client cli(HOST, PORT);
  18425. auto res1 = cli.Get(std::string("/static/") + fname);
  18426. ASSERT_TRUE(res1);
  18427. ASSERT_EQ(200, res1->status);
  18428. bool has_last_modified = res1->has_header("Last-Modified");
  18429. std::string last_modified;
  18430. if (has_last_modified) {
  18431. last_modified = res1->get_header_value("Last-Modified");
  18432. }
  18433. if (set_negative) {
  18434. // If we successfully set a negative mtime, ensure server returns a
  18435. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18436. // with an old date and ensure server handles it without crash.
  18437. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18438. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18439. ASSERT_TRUE(res2);
  18440. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18441. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18442. } else {
  18443. // Could not set negative mtime on this platform; fall back to verifying
  18444. // that normal invalid/malformed dates are treated safely (non-304).
  18445. Headers h_bad_date = {
  18446. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18447. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18448. ASSERT_TRUE(res_bad);
  18449. EXPECT_EQ(200, res_bad->status);
  18450. }
  18451. svr.stop();
  18452. t.join();
  18453. std::remove(fname);
  18454. }
  18455. //==============================================================================
  18456. // SSE Parsing Tests
  18457. //==============================================================================
  18458. class SSEParsingTest : public ::testing::Test {
  18459. protected:
  18460. // Test helper that mimics SSE parsing behavior
  18461. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18462. int &retry_ms) {
  18463. // Blank line signals end of event
  18464. if (line.empty() || line == "\r") { return true; }
  18465. // Lines starting with ':' are comments (ignored)
  18466. if (!line.empty() && line[0] == ':') { return false; }
  18467. // Find the colon separator
  18468. auto colon_pos = line.find(':');
  18469. if (colon_pos == std::string::npos) {
  18470. // Line with no colon is treated as field name with empty value
  18471. return false;
  18472. }
  18473. std::string field = line.substr(0, colon_pos);
  18474. std::string value;
  18475. // Value starts after colon, skip optional single space
  18476. if (colon_pos + 1 < line.size()) {
  18477. size_t value_start = colon_pos + 1;
  18478. if (line[value_start] == ' ') { value_start++; }
  18479. value = line.substr(value_start);
  18480. // Remove trailing \r if present
  18481. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18482. }
  18483. // Handle known fields
  18484. if (field == "event") {
  18485. msg.event = value;
  18486. } else if (field == "data") {
  18487. // Multiple data lines are concatenated with newlines
  18488. if (!msg.data.empty()) { msg.data += "\n"; }
  18489. msg.data += value;
  18490. } else if (field == "id") {
  18491. // Empty id is valid (clears the last event ID)
  18492. msg.id = value;
  18493. } else if (field == "retry") {
  18494. // Parse retry interval in milliseconds
  18495. {
  18496. int v = 0;
  18497. auto res =
  18498. detail::from_chars(value.data(), value.data() + value.size(), v);
  18499. if (res.ec == std::errc{}) { retry_ms = v; }
  18500. }
  18501. }
  18502. // Unknown fields are ignored per SSE spec
  18503. return false;
  18504. }
  18505. };
  18506. // Test: Single-line data
  18507. TEST_F(SSEParsingTest, SingleLineData) {
  18508. sse::SSEMessage msg;
  18509. int retry_ms = 3000;
  18510. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18511. EXPECT_EQ(msg.data, "hello");
  18512. EXPECT_EQ(msg.event, "message");
  18513. // Blank line ends event
  18514. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18515. }
  18516. // Test: Multi-line data
  18517. TEST_F(SSEParsingTest, MultiLineData) {
  18518. sse::SSEMessage msg;
  18519. int retry_ms = 3000;
  18520. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18521. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18522. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18523. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18524. }
  18525. // Test: Custom event types
  18526. TEST_F(SSEParsingTest, CustomEventType) {
  18527. sse::SSEMessage msg;
  18528. int retry_ms = 3000;
  18529. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18530. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18531. EXPECT_EQ(msg.event, "update");
  18532. EXPECT_EQ(msg.data, "payload");
  18533. }
  18534. // Test: Event ID handling
  18535. TEST_F(SSEParsingTest, EventIdHandling) {
  18536. sse::SSEMessage msg;
  18537. int retry_ms = 3000;
  18538. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18539. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18540. EXPECT_EQ(msg.id, "12345");
  18541. }
  18542. // Test: Empty event ID (clears last event ID)
  18543. TEST_F(SSEParsingTest, EmptyEventId) {
  18544. sse::SSEMessage msg;
  18545. msg.id = "previous";
  18546. int retry_ms = 3000;
  18547. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18548. EXPECT_EQ(msg.id, "");
  18549. }
  18550. // Test: Retry field parsing
  18551. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18552. sse::SSEMessage msg;
  18553. int retry_ms = 3000;
  18554. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18555. EXPECT_EQ(retry_ms, 5000);
  18556. }
  18557. // Test: Invalid retry value
  18558. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18559. sse::SSEMessage msg;
  18560. int retry_ms = 3000;
  18561. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18562. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18563. }
  18564. // Test: Comments (lines starting with :)
  18565. TEST_F(SSEParsingTest, CommentsIgnored) {
  18566. sse::SSEMessage msg;
  18567. int retry_ms = 3000;
  18568. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18569. EXPECT_EQ(msg.data, "");
  18570. EXPECT_EQ(msg.event, "message");
  18571. }
  18572. // Test: Colon in value
  18573. TEST_F(SSEParsingTest, ColonInValue) {
  18574. sse::SSEMessage msg;
  18575. int retry_ms = 3000;
  18576. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18577. EXPECT_EQ(msg.data, "hello:world:test");
  18578. }
  18579. // Test: Line with no colon (field name only)
  18580. TEST_F(SSEParsingTest, FieldNameOnly) {
  18581. sse::SSEMessage msg;
  18582. int retry_ms = 3000;
  18583. // According to SSE spec, this is treated as field name with empty value
  18584. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18585. // Since we don't recognize "data" without colon, data should be empty
  18586. EXPECT_EQ(msg.data, "");
  18587. }
  18588. // Test: Trailing \r handling
  18589. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18590. sse::SSEMessage msg;
  18591. int retry_ms = 3000;
  18592. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18593. EXPECT_EQ(msg.data, "hello");
  18594. }
  18595. // Test: Unknown fields ignored
  18596. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18597. sse::SSEMessage msg;
  18598. int retry_ms = 3000;
  18599. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18600. EXPECT_EQ(msg.data, "");
  18601. EXPECT_EQ(msg.event, "message");
  18602. }
  18603. // Test: Space after colon is optional
  18604. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18605. sse::SSEMessage msg1, msg2;
  18606. int retry_ms = 3000;
  18607. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18608. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18609. EXPECT_EQ(msg1.data, "hello");
  18610. EXPECT_EQ(msg2.data, "hello");
  18611. }
  18612. // Test: SSEMessage clear
  18613. TEST_F(SSEParsingTest, MessageClear) {
  18614. sse::SSEMessage msg;
  18615. msg.event = "custom";
  18616. msg.data = "some data";
  18617. msg.id = "123";
  18618. msg.clear();
  18619. EXPECT_EQ(msg.event, "message");
  18620. EXPECT_EQ(msg.data, "");
  18621. EXPECT_EQ(msg.id, "");
  18622. }
  18623. // Test: Complete event parsing
  18624. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18625. sse::SSEMessage msg;
  18626. int retry_ms = 3000;
  18627. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18628. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18629. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18630. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18631. // Blank line ends event
  18632. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18633. EXPECT_EQ(msg.event, "notification");
  18634. EXPECT_EQ(msg.id, "evt-42");
  18635. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18636. EXPECT_EQ(retry_ms, 1000);
  18637. }
  18638. //==============================================================================
  18639. // Integration Tests with Server
  18640. //==============================================================================
  18641. class SSEIntegrationTest : public ::testing::Test {
  18642. protected:
  18643. void SetUp() override {
  18644. stop_server_.store(false);
  18645. events_.clear();
  18646. server_ = httplib::detail::make_unique<Server>();
  18647. setup_server();
  18648. start_server();
  18649. }
  18650. void TearDown() override {
  18651. stop_server_.store(true);
  18652. event_cv_.notify_all();
  18653. server_->stop();
  18654. if (server_thread_.joinable()) { server_thread_.join(); }
  18655. }
  18656. void setup_server() {
  18657. // Simple SSE endpoint
  18658. server_->Get("/events", [this](const Request &req, Response &res) {
  18659. auto last_id = req.get_header_value("Last-Event-ID");
  18660. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18661. res.set_chunked_content_provider(
  18662. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18663. std::unique_lock<std::mutex> lock(event_mutex_);
  18664. if (event_cv_.wait_for(
  18665. lock, std::chrono::milliseconds(200), [this] {
  18666. return !events_.empty() || stop_server_.load();
  18667. })) {
  18668. if (stop_server_.load()) { return false; }
  18669. if (!events_.empty()) {
  18670. std::string event = events_.front();
  18671. events_.erase(events_.begin());
  18672. sink.write(event.data(), event.size());
  18673. return true;
  18674. }
  18675. }
  18676. return !stop_server_.load();
  18677. });
  18678. });
  18679. // Endpoint that returns error
  18680. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18681. res.status = 500;
  18682. res.set_content("Internal Server Error", "text/plain");
  18683. });
  18684. // Endpoint for custom event types
  18685. server_->Get("/custom-events", [](const Request &, Response &res) {
  18686. res.set_chunked_content_provider(
  18687. "text/event-stream", [](size_t offset, DataSink &sink) {
  18688. if (offset == 0) {
  18689. std::string event = "event: update\ndata: updated\n\n"
  18690. "event: delete\ndata: deleted\n\n";
  18691. sink.write(event.data(), event.size());
  18692. }
  18693. return false; // End stream after sending
  18694. });
  18695. });
  18696. }
  18697. void start_server() {
  18698. port_ = server_->bind_to_any_port(HOST);
  18699. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18700. // Wait for server to start
  18701. while (!server_->is_running()) {
  18702. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18703. }
  18704. }
  18705. int get_port() const { return port_; }
  18706. void send_event(const std::string &event) {
  18707. std::lock_guard<std::mutex> lock(event_mutex_);
  18708. events_.push_back(event);
  18709. event_cv_.notify_all();
  18710. }
  18711. std::unique_ptr<Server> server_;
  18712. std::thread server_thread_;
  18713. std::mutex event_mutex_;
  18714. std::condition_variable event_cv_;
  18715. std::vector<std::string> events_;
  18716. std::atomic<bool> stop_server_{false};
  18717. std::string last_received_event_id_;
  18718. int port_ = 0;
  18719. };
  18720. // Test: Successful connection and on_open callback
  18721. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18722. // Add a simple endpoint that sends one event and closes
  18723. server_->Get("/simple-event", [](const Request &, Response &res) {
  18724. res.set_chunked_content_provider(
  18725. "text/event-stream", [](size_t offset, DataSink &sink) {
  18726. if (offset == 0) {
  18727. std::string event = "data: hello\n\n";
  18728. sink.write(event.data(), event.size());
  18729. }
  18730. return false; // Close stream after sending
  18731. });
  18732. });
  18733. Client client("localhost", get_port());
  18734. sse::SSEClient sse(client, "/simple-event");
  18735. std::atomic<bool> open_called{false};
  18736. std::atomic<bool> message_received{false};
  18737. sse.on_open([&open_called]() { open_called.store(true); });
  18738. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18739. if (msg.data == "hello") { message_received.store(true); }
  18740. });
  18741. sse.set_reconnect_interval(100);
  18742. sse.set_max_reconnect_attempts(1);
  18743. // Start async
  18744. sse.start_async();
  18745. // Wait for message to be processed
  18746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18747. sse.stop();
  18748. EXPECT_TRUE(open_called.load());
  18749. EXPECT_TRUE(message_received.load());
  18750. }
  18751. // Test: on_message callback
  18752. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18753. // Endpoint that sends multiple events then closes
  18754. server_->Get("/multi-event", [](const Request &, Response &res) {
  18755. res.set_chunked_content_provider(
  18756. "text/event-stream", [](size_t offset, DataSink &sink) {
  18757. if (offset == 0) {
  18758. std::string events = "data: message1\n\ndata: message2\n\n";
  18759. sink.write(events.data(), events.size());
  18760. }
  18761. return false;
  18762. });
  18763. });
  18764. Client client("localhost", get_port());
  18765. sse::SSEClient sse(client, "/multi-event");
  18766. std::vector<std::string> received_messages;
  18767. std::mutex messages_mutex;
  18768. sse.on_message([&](const sse::SSEMessage &msg) {
  18769. std::lock_guard<std::mutex> lock(messages_mutex);
  18770. received_messages.push_back(msg.data);
  18771. });
  18772. sse.set_reconnect_interval(100);
  18773. sse.set_max_reconnect_attempts(1);
  18774. sse.start_async();
  18775. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18776. sse.stop();
  18777. std::lock_guard<std::mutex> lock(messages_mutex);
  18778. EXPECT_GE(received_messages.size(), 2u);
  18779. if (received_messages.size() >= 2) {
  18780. EXPECT_EQ(received_messages[0], "message1");
  18781. EXPECT_EQ(received_messages[1], "message2");
  18782. }
  18783. }
  18784. // Test: on_event for specific types
  18785. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18786. Client client("localhost", get_port());
  18787. sse::SSEClient sse(client, "/custom-events");
  18788. std::atomic<bool> update_received{false};
  18789. std::atomic<bool> delete_received{false};
  18790. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18791. if (msg.data == "updated") { update_received.store(true); }
  18792. });
  18793. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18794. if (msg.data == "deleted") { delete_received.store(true); }
  18795. });
  18796. sse.set_max_reconnect_attempts(1);
  18797. sse.start_async();
  18798. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18799. sse.stop();
  18800. EXPECT_TRUE(update_received.load());
  18801. EXPECT_TRUE(delete_received.load());
  18802. }
  18803. // Test: on_error callback on connection failure
  18804. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18805. // Connect to a non-existent port
  18806. Client client("localhost", 59999);
  18807. sse::SSEClient sse(client, "/events");
  18808. std::atomic<bool> error_called{false};
  18809. Error received_error = Error::Success;
  18810. sse.on_error([&](Error err) {
  18811. error_called.store(true);
  18812. received_error = err;
  18813. });
  18814. sse.set_reconnect_interval(50);
  18815. sse.set_max_reconnect_attempts(1);
  18816. sse.start_async();
  18817. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18818. sse.stop();
  18819. EXPECT_TRUE(error_called.load());
  18820. EXPECT_NE(received_error, Error::Success);
  18821. }
  18822. // Test: Last-Event-ID header sent on reconnect
  18823. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18824. // Endpoint that sends event with ID
  18825. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18826. res.set_chunked_content_provider(
  18827. "text/event-stream", [](size_t offset, DataSink &sink) {
  18828. if (offset == 0) {
  18829. std::string event = "id: evt-123\ndata: test\n\n";
  18830. sink.write(event.data(), event.size());
  18831. }
  18832. return false;
  18833. });
  18834. });
  18835. Client client("localhost", get_port());
  18836. sse::SSEClient sse(client, "/event-with-id");
  18837. std::atomic<bool> id_received{false};
  18838. sse.on_message([&](const sse::SSEMessage &msg) {
  18839. if (!msg.id.empty()) { id_received.store(true); }
  18840. });
  18841. sse.set_reconnect_interval(100);
  18842. sse.set_max_reconnect_attempts(1);
  18843. sse.start_async();
  18844. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18845. sse.stop();
  18846. EXPECT_TRUE(id_received.load());
  18847. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18848. }
  18849. // Test: Manual stop
  18850. TEST_F(SSEIntegrationTest, ManualStop) {
  18851. // Endpoint that sends one event and stays open briefly
  18852. std::atomic<bool> handler_running{true};
  18853. server_->Get("/stay-open", [&handler_running](const Request &,
  18854. Response &res) {
  18855. res.set_chunked_content_provider(
  18856. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18857. if (offset == 0) {
  18858. std::string event = "data: connected\n\n";
  18859. sink.write(event.data(), event.size());
  18860. }
  18861. // Keep connection open while handler_running is true
  18862. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18863. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18864. }
  18865. return false;
  18866. });
  18867. });
  18868. Client client("localhost", get_port());
  18869. sse::SSEClient sse(client, "/stay-open");
  18870. std::atomic<bool> connected{false};
  18871. sse.on_open([&connected]() { connected.store(true); });
  18872. sse.set_reconnect_interval(100);
  18873. sse.set_max_reconnect_attempts(1);
  18874. sse.start_async();
  18875. // Wait for connection to establish
  18876. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18877. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18878. }
  18879. EXPECT_TRUE(connected.load());
  18880. EXPECT_TRUE(sse.is_connected());
  18881. // Signal handler to stop
  18882. handler_running.store(false);
  18883. // Stop SSE client
  18884. sse.stop();
  18885. EXPECT_FALSE(sse.is_connected());
  18886. }
  18887. // Test: SSEClient with custom headers
  18888. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18889. // Setup a server endpoint that checks for custom header
  18890. std::atomic<bool> header_received{false};
  18891. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18892. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18893. header_received.store(true);
  18894. }
  18895. res.set_chunked_content_provider("text/event-stream",
  18896. [](size_t, DataSink &) { return false; });
  18897. });
  18898. Client client("localhost", get_port());
  18899. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18900. sse::SSEClient sse(client, "/header-check", headers);
  18901. sse.set_max_reconnect_attempts(1);
  18902. sse.start_async();
  18903. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18904. sse.stop();
  18905. EXPECT_TRUE(header_received.load());
  18906. }
  18907. // Test: Reconnect interval configuration
  18908. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18909. Client client("localhost", get_port());
  18910. sse::SSEClient sse(client, "/events");
  18911. auto &result = sse.set_reconnect_interval(500);
  18912. // Builder pattern should return reference to self
  18913. EXPECT_EQ(&result, &sse);
  18914. }
  18915. // Test: Max reconnect attempts
  18916. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18917. // Connect to non-existent port to force reconnects
  18918. Client client("localhost", 59998);
  18919. sse::SSEClient sse(client, "/events");
  18920. std::atomic<int> error_count{0};
  18921. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18922. sse.set_reconnect_interval(50);
  18923. sse.set_max_reconnect_attempts(2);
  18924. auto start = std::chrono::steady_clock::now();
  18925. sse.start(); // Blocking call
  18926. auto end = std::chrono::steady_clock::now();
  18927. // Should have stopped after 2 failed attempts
  18928. EXPECT_GE(error_count.load(), 2);
  18929. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18930. auto duration =
  18931. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18932. #ifdef _WIN32
  18933. // Windows is much slower for socket connection failures
  18934. EXPECT_LT(duration.count(), 7000);
  18935. #else
  18936. EXPECT_LT(duration.count(), 1000);
  18937. #endif
  18938. }
  18939. // Test: Multi-line data in integration
  18940. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18941. // Endpoint with multi-line data
  18942. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18943. res.set_chunked_content_provider(
  18944. "text/event-stream", [](size_t offset, DataSink &sink) {
  18945. if (offset == 0) {
  18946. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18947. sink.write(event.data(), event.size());
  18948. }
  18949. return false;
  18950. });
  18951. });
  18952. Client client("localhost", get_port());
  18953. sse::SSEClient sse(client, "/multiline-data");
  18954. std::string received_data;
  18955. std::mutex data_mutex;
  18956. sse.on_message([&](const sse::SSEMessage &msg) {
  18957. std::lock_guard<std::mutex> lock(data_mutex);
  18958. received_data = msg.data;
  18959. });
  18960. sse.set_reconnect_interval(100);
  18961. sse.set_max_reconnect_attempts(1);
  18962. sse.start_async();
  18963. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18964. sse.stop();
  18965. std::lock_guard<std::mutex> lock(data_mutex);
  18966. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18967. }
  18968. // Test: Auto-reconnect after server disconnection
  18969. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18970. std::atomic<int> connection_count{0};
  18971. std::atomic<int> message_count{0};
  18972. // Endpoint that sends one event and closes, forcing reconnect
  18973. server_->Get("/reconnect-test",
  18974. [&connection_count](const Request &, Response &res) {
  18975. connection_count.fetch_add(1);
  18976. res.set_chunked_content_provider(
  18977. "text/event-stream", [](size_t offset, DataSink &sink) {
  18978. if (offset == 0) {
  18979. std::string event = "data: hello\n\n";
  18980. sink.write(event.data(), event.size());
  18981. }
  18982. return false; // Close connection after sending
  18983. });
  18984. });
  18985. Client client("localhost", get_port());
  18986. sse::SSEClient sse(client, "/reconnect-test");
  18987. sse.on_message([&message_count](const sse::SSEMessage &) {
  18988. message_count.fetch_add(1);
  18989. });
  18990. sse.set_reconnect_interval(100);
  18991. sse.set_max_reconnect_attempts(3);
  18992. sse.start_async();
  18993. // Wait long enough for multiple reconnects
  18994. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18995. sse.stop();
  18996. // Should have connected multiple times (initial + reconnects)
  18997. EXPECT_GE(connection_count.load(), 2);
  18998. // Should have received messages from multiple connections
  18999. EXPECT_GE(message_count.load(), 2);
  19000. }
  19001. // Test: A retry field that is not all ASCII digits is ignored
  19002. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19003. std::atomic<int> connection_count{0};
  19004. server_->Get("/bad-retry",
  19005. [&connection_count](const Request &, Response &res) {
  19006. connection_count.fetch_add(1);
  19007. res.set_chunked_content_provider(
  19008. "text/event-stream", [](size_t offset, DataSink &sink) {
  19009. if (offset == 0) {
  19010. std::string event = "retry: -1\ndata: hello\n\n";
  19011. sink.write(event.data(), event.size());
  19012. }
  19013. return false;
  19014. });
  19015. });
  19016. Client client("localhost", get_port());
  19017. sse::SSEClient sse(client, "/bad-retry");
  19018. sse.set_reconnect_interval(10000);
  19019. sse.start_async();
  19020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19021. sse.stop();
  19022. EXPECT_EQ(connection_count.load(), 1);
  19023. }
  19024. // Test: A retry field of all ASCII digits sets the reconnection time
  19025. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19026. std::atomic<int> connection_count{0};
  19027. server_->Get("/zero-retry",
  19028. [&connection_count](const Request &, Response &res) {
  19029. connection_count.fetch_add(1);
  19030. res.set_chunked_content_provider(
  19031. "text/event-stream", [](size_t offset, DataSink &sink) {
  19032. if (offset == 0) {
  19033. std::string event = "retry: 0\ndata: hello\n\n";
  19034. sink.write(event.data(), event.size());
  19035. }
  19036. return false;
  19037. });
  19038. });
  19039. Client client("localhost", get_port());
  19040. sse::SSEClient sse(client, "/zero-retry");
  19041. sse.set_reconnect_interval(10000);
  19042. sse.start_async();
  19043. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19044. sse.stop();
  19045. // The server-supplied interval is applied, but never below 100ms, so
  19046. // "retry: 0" does not cause a busy reconnect loop
  19047. EXPECT_GE(connection_count.load(), 2);
  19048. EXPECT_LE(connection_count.load(), 10);
  19049. }
  19050. // Test: Last-Event-ID sent on reconnect
  19051. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19052. std::atomic<int> connection_count{0};
  19053. std::vector<std::string> received_last_event_ids;
  19054. std::mutex id_mutex;
  19055. // Endpoint that checks Last-Event-ID header and sends event with ID
  19056. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19057. int conn = connection_count.fetch_add(1);
  19058. // Capture the Last-Event-ID header from each connection
  19059. {
  19060. std::lock_guard<std::mutex> lock(id_mutex);
  19061. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19062. }
  19063. res.set_chunked_content_provider(
  19064. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19065. if (offset == 0) {
  19066. std::string event =
  19067. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19068. sink.write(event.data(), event.size());
  19069. }
  19070. return false;
  19071. });
  19072. });
  19073. Client client("localhost", get_port());
  19074. sse::SSEClient sse(client, "/reconnect-with-id");
  19075. sse.set_reconnect_interval(100);
  19076. sse.set_max_reconnect_attempts(3);
  19077. sse.start_async();
  19078. // Wait for at least 2 connections
  19079. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19080. sse.stop();
  19081. // Verify behavior
  19082. std::lock_guard<std::mutex> lock(id_mutex);
  19083. EXPECT_GE(received_last_event_ids.size(), 2u);
  19084. // First connection should have no Last-Event-ID
  19085. if (!received_last_event_ids.empty()) {
  19086. EXPECT_EQ(received_last_event_ids[0], "");
  19087. }
  19088. // Second connection should have Last-Event-ID from first connection
  19089. if (received_last_event_ids.size() >= 2) {
  19090. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19091. }
  19092. }
  19093. // Test: set_headers updates headers used on reconnect
  19094. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19095. std::vector<std::string> received_tokens;
  19096. std::mutex token_mutex;
  19097. // Endpoint that captures Authorization header
  19098. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19099. {
  19100. std::lock_guard<std::mutex> lock(token_mutex);
  19101. received_tokens.push_back(req.get_header_value("Authorization"));
  19102. }
  19103. res.set_chunked_content_provider(
  19104. "text/event-stream", [](size_t offset, DataSink &sink) {
  19105. if (offset == 0) {
  19106. std::string event = "data: hello\n\n";
  19107. sink.write(event.data(), event.size());
  19108. }
  19109. return false; // Close connection to trigger reconnect
  19110. });
  19111. });
  19112. Client client("localhost", get_port());
  19113. Headers headers = {{"Authorization", "Bearer old-token"}};
  19114. sse::SSEClient sse(client, "/auth-check", headers);
  19115. // Update headers on each successful connection
  19116. sse.on_open(
  19117. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19118. sse.set_reconnect_interval(100);
  19119. sse.set_max_reconnect_attempts(3);
  19120. sse.start_async();
  19121. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19122. sse.stop();
  19123. std::lock_guard<std::mutex> lock(token_mutex);
  19124. ASSERT_GE(received_tokens.size(), 2u);
  19125. // First connection uses original header
  19126. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19127. // Second connection uses updated header from set_headers
  19128. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19129. }
  19130. // Test: 401 allows reconnection (so on_error can refresh headers)
  19131. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19132. std::atomic<int> connection_count{0};
  19133. // Endpoint: returns 401 on first attempt, 200 on second
  19134. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19135. int conn = connection_count.fetch_add(1);
  19136. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19137. res.status = StatusCode::Unauthorized_401;
  19138. res.set_content("Unauthorized", "text/plain");
  19139. return;
  19140. }
  19141. res.set_chunked_content_provider(
  19142. "text/event-stream", [](size_t offset, DataSink &sink) {
  19143. if (offset == 0) {
  19144. std::string event = "data: authenticated\n\n";
  19145. sink.write(event.data(), event.size());
  19146. }
  19147. return false;
  19148. });
  19149. });
  19150. Client client("localhost", get_port());
  19151. Headers headers = {{"Authorization", "Bearer expired"}};
  19152. sse::SSEClient sse(client, "/auth-retry", headers);
  19153. std::atomic<bool> message_received{false};
  19154. // Refresh token on error
  19155. sse.on_error(
  19156. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19157. sse.on_message([&](const sse::SSEMessage &msg) {
  19158. if (msg.data == "authenticated") { message_received.store(true); }
  19159. });
  19160. sse.set_reconnect_interval(100);
  19161. sse.set_max_reconnect_attempts(3);
  19162. sse.start_async();
  19163. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19164. sse.stop();
  19165. // Should have reconnected after 401 and succeeded with new token
  19166. EXPECT_GE(connection_count.load(), 2);
  19167. EXPECT_TRUE(message_received.load());
  19168. }
  19169. TEST(Issue2318Test, EmptyHostString) {
  19170. {
  19171. httplib::Client cli_empty("", PORT);
  19172. auto res = cli_empty.Get("/");
  19173. ASSERT_FALSE(res);
  19174. EXPECT_EQ(httplib::Error::Connection, res.error());
  19175. }
  19176. {
  19177. httplib::Client cli(" ", PORT);
  19178. auto res = cli.Get("/");
  19179. ASSERT_FALSE(res);
  19180. EXPECT_EQ(httplib::Error::Connection, res.error());
  19181. }
  19182. }
  19183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19184. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19185. Server svr;
  19186. // Set a small payload limit (1KB)
  19187. svr.set_payload_max_length(1024);
  19188. svr.Post("/test", [&](const Request &req, Response &res) {
  19189. res.set_content("Body size: " + std::to_string(req.body.size()),
  19190. "text/plain");
  19191. });
  19192. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19193. auto se = detail::scope_exit([&] {
  19194. svr.stop();
  19195. listen_thread.join();
  19196. });
  19197. svr.wait_until_ready();
  19198. // Create data that compresses well but exceeds limit when decompressed
  19199. // 8KB of repeated null bytes compresses to a very small size
  19200. std::string original_data(8 * 1024, '\0');
  19201. // Compress the data using gzip
  19202. std::string compressed_data;
  19203. detail::gzip_compressor compressor;
  19204. compressor.compress(original_data.data(), original_data.size(), true,
  19205. [&](const char *data, size_t size) {
  19206. compressed_data.append(data, size);
  19207. return true;
  19208. });
  19209. // Verify compression worked (compressed should be much smaller)
  19210. ASSERT_LT(compressed_data.size(), original_data.size());
  19211. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19212. // Send compressed data with Content-Encoding: gzip
  19213. Client cli(HOST, PORT);
  19214. Headers headers = {{"Content-Encoding", "gzip"}};
  19215. auto res =
  19216. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19217. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19219. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19220. }
  19221. #endif
  19222. // ============================================================================
  19223. // OpenSSL-Specific Tests
  19224. // ============================================================================
  19225. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19226. X509 *readCertificate(const std::string &strFileName) {
  19227. std::ifstream inStream(strFileName);
  19228. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19229. std::istreambuf_iterator<char>());
  19230. if (strCertPEM.empty()) return (nullptr);
  19231. BIO *pbCert = BIO_new(BIO_s_mem());
  19232. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19233. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19234. BIO_free(pbCert);
  19235. return (pCert);
  19236. }
  19237. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19238. std::ifstream inStream(strFileName);
  19239. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19240. std::istreambuf_iterator<char>());
  19241. if (strPrivateKeyPEM.empty()) return (nullptr);
  19242. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19243. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19244. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19245. BIO_free(pbPrivKey);
  19246. return (pPrivateKey);
  19247. }
  19248. TEST(BindServerTest, UpdateCerts) {
  19249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19250. int port = svr.bind_to_any_port("0.0.0.0");
  19251. ASSERT_TRUE(svr.is_valid());
  19252. ASSERT_TRUE(port > 0);
  19253. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19254. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19255. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19256. ASSERT_TRUE(cert != nullptr);
  19257. ASSERT_TRUE(ca_cert != nullptr);
  19258. ASSERT_TRUE(key != nullptr);
  19259. X509_STORE *cert_store = X509_STORE_new();
  19260. X509_STORE_add_cert(cert_store, ca_cert);
  19261. // svr.update_certs(cert, key, cert_store); // deprecated
  19262. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19263. CLIENT_CA_CERT_FILE);
  19264. ASSERT_TRUE(svr.is_valid());
  19265. svr.stop();
  19266. X509_STORE_free(cert_store);
  19267. X509_free(cert);
  19268. X509_free(ca_cert);
  19269. EVP_PKEY_free(key);
  19270. }
  19271. // Test that update_certs() updates client CA list correctly
  19272. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19273. // Start with file-based constructor
  19274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19275. ASSERT_TRUE(svr.is_valid());
  19276. // Initially no client CA list should be set
  19277. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19278. ASSERT_TRUE(ssl_ctx != nullptr);
  19279. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19280. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19281. EXPECT_EQ(0, count_before);
  19282. // Now update with client CA (PEM string)
  19283. std::string cert_pem, key_pem, ca_pem;
  19284. read_file(SERVER_CERT_FILE, cert_pem);
  19285. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19286. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19287. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19288. ASSERT_TRUE(svr.is_valid());
  19289. // Now client CA list should be set
  19290. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19291. ASSERT_TRUE(ca_list_after != nullptr);
  19292. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19293. }
  19294. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19295. // Test that the file-path SSLServer constructor properly sets the client CA
  19296. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19297. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19298. ASSERT_TRUE(svr.is_valid());
  19299. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19300. ASSERT_TRUE(ssl_ctx != nullptr);
  19301. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19302. ASSERT_TRUE(ca_list != nullptr);
  19303. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19304. }
  19305. #endif
  19306. // ============================================================================
  19307. // MbedTLS-Specific Tests
  19308. // ============================================================================
  19309. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19310. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19311. using namespace httplib::tls;
  19312. // Track if callback was invoked
  19313. bool callback_invoked = false;
  19314. // The callback receives void* ctx which is actually MbedTlsContext*
  19315. // We can access the mbedtls_ssl_config via the context
  19316. auto setup_callback = [&callback_invoked](void *ctx) {
  19317. callback_invoked = true;
  19318. // Cast to MbedTlsContext* to access the ssl config
  19319. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19320. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19321. // Use static variables to hold certificate data (simplified for test)
  19322. static mbedtls_x509_crt own_cert;
  19323. static mbedtls_pk_context own_key;
  19324. static mbedtls_x509_crt ca_chain;
  19325. static bool initialized = false;
  19326. if (!initialized) {
  19327. mbedtls_x509_crt_init(&own_cert);
  19328. mbedtls_pk_init(&own_key);
  19329. mbedtls_x509_crt_init(&ca_chain);
  19330. // Load server certificate
  19331. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19332. return false;
  19333. }
  19334. // Load server private key.
  19335. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19336. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19337. #if MBEDTLS_VERSION_MAJOR == 3
  19338. ,
  19339. mbedtls_ctr_drbg_random, nullptr
  19340. #endif
  19341. ) != 0) {
  19342. return false;
  19343. }
  19344. // Load CA chain for client verification
  19345. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19346. return false;
  19347. }
  19348. initialized = true;
  19349. }
  19350. // Configure the SSL config
  19351. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19352. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19353. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19354. // Set minimum TLS version using mbedTLS native API
  19355. #if MBEDTLS_VERSION_MAJOR >= 3
  19356. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19357. #else
  19358. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19359. MBEDTLS_SSL_MINOR_VERSION_3);
  19360. #endif
  19361. return true;
  19362. };
  19363. SSLServer svr(setup_callback);
  19364. ASSERT_TRUE(svr.is_valid());
  19365. ASSERT_TRUE(callback_invoked);
  19366. svr.Get("/test", [&](const Request &req, Response &res) {
  19367. res.set_content("test", "text/plain");
  19368. auto cert = req.peer_cert();
  19369. ASSERT_TRUE(static_cast<bool>(cert));
  19370. auto common_name = cert.subject_cn();
  19371. EXPECT_EQ("Common Name", common_name);
  19372. });
  19373. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19374. auto se = detail::scope_exit([&] {
  19375. svr.stop();
  19376. t.join();
  19377. ASSERT_FALSE(svr.is_running());
  19378. });
  19379. svr.wait_until_ready();
  19380. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19381. cli.enable_server_certificate_verification(false);
  19382. cli.set_connection_timeout(30);
  19383. auto res = cli.Get("/test");
  19384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19385. ASSERT_EQ(StatusCode::OK_200, res->status);
  19386. }
  19387. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19388. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19389. // keep-alive SSL session, which reads through that config in
  19390. // mbedtls_ssl_close_notify.
  19391. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19393. ASSERT_TRUE(svr.is_valid());
  19394. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19395. res.set_content("test", "text/plain");
  19396. });
  19397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19398. auto se = detail::scope_exit([&] {
  19399. svr.stop();
  19400. t.join();
  19401. ASSERT_FALSE(svr.is_running());
  19402. });
  19403. svr.wait_until_ready();
  19404. {
  19405. SSLClient cli(HOST, PORT);
  19406. cli.enable_server_certificate_verification(false);
  19407. cli.set_keep_alive(true);
  19408. auto res = cli.Get("/test");
  19409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19410. ASSERT_EQ(StatusCode::OK_200, res->status);
  19411. // cli is destructed here with the keep-alive SSL session still open.
  19412. }
  19413. }
  19414. #endif
  19415. // WebSocket Tests
  19416. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19417. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19418. // defining the meaning of these bits has been negotiated.
  19419. auto make_frame = [](uint8_t first_byte) {
  19420. std::string frame;
  19421. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19422. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19423. frame += "Hello";
  19424. return frame;
  19425. };
  19426. // RSV1 set (0x40)
  19427. {
  19428. detail::BufferStream strm;
  19429. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19430. ws::Opcode opcode;
  19431. std::string payload;
  19432. bool fin;
  19433. EXPECT_EQ(
  19434. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19435. ws::impl::FrameRead::Fail);
  19436. }
  19437. // RSV2 set (0x20)
  19438. {
  19439. detail::BufferStream strm;
  19440. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19441. ws::Opcode opcode;
  19442. std::string payload;
  19443. bool fin;
  19444. EXPECT_EQ(
  19445. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19446. ws::impl::FrameRead::Fail);
  19447. }
  19448. // RSV3 set (0x10)
  19449. {
  19450. detail::BufferStream strm;
  19451. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19452. ws::Opcode opcode;
  19453. std::string payload;
  19454. bool fin;
  19455. EXPECT_EQ(
  19456. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19457. ws::impl::FrameRead::Fail);
  19458. }
  19459. // No RSV bits set - should succeed
  19460. {
  19461. detail::BufferStream strm;
  19462. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19463. ws::Opcode opcode;
  19464. std::string payload;
  19465. bool fin;
  19466. EXPECT_EQ(
  19467. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19468. ws::impl::FrameRead::Ok);
  19469. EXPECT_EQ(ws::Opcode::Text, opcode);
  19470. EXPECT_EQ("Hello", payload);
  19471. EXPECT_TRUE(fin);
  19472. }
  19473. }
  19474. TEST(WebSocketTest, ControlFrameValidation) {
  19475. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19476. // payload length <= 125.
  19477. // Ping with FIN=0 - must be rejected
  19478. {
  19479. detail::BufferStream strm;
  19480. std::string frame;
  19481. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19482. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19483. strm.write(frame.data(), frame.size());
  19484. ws::Opcode opcode;
  19485. std::string payload;
  19486. bool fin;
  19487. EXPECT_EQ(
  19488. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19489. ws::impl::FrameRead::Fail);
  19490. }
  19491. // Close with FIN=0 - must be rejected
  19492. {
  19493. detail::BufferStream strm;
  19494. std::string frame;
  19495. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19496. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19497. strm.write(frame.data(), frame.size());
  19498. ws::Opcode opcode;
  19499. std::string payload;
  19500. bool fin;
  19501. EXPECT_EQ(
  19502. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19503. ws::impl::FrameRead::Fail);
  19504. }
  19505. // Ping with payload_len=126 (extended length) - must be rejected
  19506. {
  19507. detail::BufferStream strm;
  19508. std::string frame;
  19509. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19510. frame += static_cast<char>(126); // payload_len=126 (>125)
  19511. frame += static_cast<char>(0x00); // extended length high byte
  19512. frame += static_cast<char>(126); // extended length low byte
  19513. frame += std::string(126, 'x');
  19514. strm.write(frame.data(), frame.size());
  19515. ws::Opcode opcode;
  19516. std::string payload;
  19517. bool fin;
  19518. EXPECT_EQ(
  19519. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19520. ws::impl::FrameRead::Fail);
  19521. }
  19522. // Ping with FIN=1 and payload_len=125 - should succeed
  19523. {
  19524. detail::BufferStream strm;
  19525. std::string frame;
  19526. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19527. frame += static_cast<char>(125); // payload_len=125
  19528. frame += std::string(125, 'x');
  19529. strm.write(frame.data(), frame.size());
  19530. ws::Opcode opcode;
  19531. std::string payload;
  19532. bool fin;
  19533. EXPECT_EQ(
  19534. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19535. ws::impl::FrameRead::Ok);
  19536. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19537. EXPECT_EQ(125u, payload.size());
  19538. EXPECT_TRUE(fin);
  19539. }
  19540. }
  19541. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19542. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19543. // length MUST be 0.
  19544. // MSB set - must be rejected
  19545. {
  19546. detail::BufferStream strm;
  19547. std::string frame;
  19548. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19549. frame += static_cast<char>(127); // 64-bit extended length
  19550. frame += static_cast<char>(0x80); // MSB set (invalid)
  19551. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19552. strm.write(frame.data(), frame.size());
  19553. ws::Opcode opcode;
  19554. std::string payload;
  19555. bool fin;
  19556. EXPECT_EQ(
  19557. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19558. ws::impl::FrameRead::Fail);
  19559. }
  19560. // MSB clear - should pass length parsing (will be rejected by max_len,
  19561. // but that's a different check; use a small length to verify)
  19562. {
  19563. detail::BufferStream strm;
  19564. std::string frame;
  19565. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19566. frame += static_cast<char>(127); // 64-bit extended length
  19567. frame += std::string(7, '\0'); // high bytes = 0
  19568. frame += static_cast<char>(0x03); // length = 3
  19569. frame += "abc";
  19570. strm.write(frame.data(), frame.size());
  19571. ws::Opcode opcode;
  19572. std::string payload;
  19573. bool fin;
  19574. EXPECT_EQ(
  19575. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19576. ws::impl::FrameRead::Ok);
  19577. EXPECT_EQ(ws::Opcode::Text, opcode);
  19578. EXPECT_EQ("abc", payload);
  19579. }
  19580. }
  19581. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19582. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19583. // Valid UTF-8
  19584. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19585. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19586. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19587. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19588. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19589. // Invalid UTF-8
  19590. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19591. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19592. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19593. EXPECT_FALSE(
  19594. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19595. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19596. }
  19597. TEST(WebSocketTest, ConnectAndDisconnect) {
  19598. Server svr;
  19599. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19600. std::string msg;
  19601. while (ws.read(msg)) {}
  19602. });
  19603. auto port = svr.bind_to_any_port(HOST);
  19604. std::thread t([&]() { svr.listen_after_bind(); });
  19605. svr.wait_until_ready();
  19606. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19607. auto res = client.connect();
  19608. ASSERT_TRUE(res);
  19609. EXPECT_EQ(Error::Success, res.error());
  19610. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19611. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19612. EXPECT_TRUE(client.is_open());
  19613. client.close();
  19614. EXPECT_FALSE(client.is_open());
  19615. svr.stop();
  19616. t.join();
  19617. }
  19618. TEST(WebSocketTest, ValidURL) {
  19619. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19620. EXPECT_TRUE(ws1.is_valid());
  19621. ws::WebSocketClient ws2("ws://example.com/path");
  19622. EXPECT_TRUE(ws2.is_valid());
  19623. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19624. EXPECT_TRUE(ws3.is_valid());
  19625. #ifdef CPPHTTPLIB_SSL_ENABLED
  19626. ws::WebSocketClient wss1("wss://example.com/path");
  19627. EXPECT_TRUE(wss1.is_valid());
  19628. ws::WebSocketClient wss2("wss://example.com:443/path");
  19629. EXPECT_TRUE(wss2.is_valid());
  19630. #endif
  19631. }
  19632. TEST(WebSocketTest, InvalidURL) {
  19633. // No scheme
  19634. ws::WebSocketClient ws1("localhost:8080/path");
  19635. EXPECT_FALSE(ws1.is_valid());
  19636. // No path
  19637. ws::WebSocketClient ws2("ws://localhost:8080");
  19638. EXPECT_FALSE(ws2.is_valid());
  19639. // Empty string
  19640. ws::WebSocketClient ws3("");
  19641. EXPECT_FALSE(ws3.is_valid());
  19642. // Missing host
  19643. ws::WebSocketClient ws4("ws://:8080/path");
  19644. EXPECT_FALSE(ws4.is_valid());
  19645. // Port number overflow — should not crash
  19646. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19647. EXPECT_FALSE(ws5.is_valid());
  19648. // Port out of range
  19649. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19650. EXPECT_FALSE(ws6.is_valid());
  19651. }
  19652. TEST(WebSocketTest, UnsupportedScheme) {
  19653. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19654. ws::WebSocketClient ws1("http://localhost:8080/path");
  19655. EXPECT_FALSE(ws1.is_valid());
  19656. ws::WebSocketClient ws2("https://localhost:8080/path");
  19657. EXPECT_FALSE(ws2.is_valid());
  19658. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19659. EXPECT_FALSE(ws3.is_valid());
  19660. #else
  19661. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19662. std::invalid_argument);
  19663. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19664. std::invalid_argument);
  19665. #endif
  19666. }
  19667. TEST(WebSocketTest, ConnectWhenInvalid) {
  19668. ws::WebSocketClient ws("not a valid url");
  19669. EXPECT_FALSE(ws.is_valid());
  19670. auto res = ws.connect();
  19671. EXPECT_FALSE(res);
  19672. EXPECT_EQ(Error::Connection, res.error());
  19673. EXPECT_EQ(-1, res.status());
  19674. }
  19675. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19676. // Grab a port that is free, then close it again so nothing listens there
  19677. Server svr;
  19678. auto port = svr.bind_to_any_port(HOST);
  19679. svr.stop();
  19680. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19681. auto res = client.connect();
  19682. ASSERT_FALSE(res);
  19683. EXPECT_EQ(Error::Connection, res.error());
  19684. EXPECT_EQ(-1, res.status());
  19685. }
  19686. TEST(WebSocketTest, DefaultPort) {
  19687. ws::WebSocketClient ws1("ws://example.com/path");
  19688. EXPECT_TRUE(ws1.is_valid());
  19689. // ws:// defaults to port 80 (verified by successful parse)
  19690. #ifdef CPPHTTPLIB_SSL_ENABLED
  19691. ws::WebSocketClient ws2("wss://example.com/path");
  19692. EXPECT_TRUE(ws2.is_valid());
  19693. // wss:// defaults to port 443 (verified by successful parse)
  19694. #endif
  19695. }
  19696. TEST(WebSocketTest, IPv6LiteralAddress) {
  19697. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19698. EXPECT_TRUE(ws1.is_valid());
  19699. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19700. EXPECT_TRUE(ws2.is_valid());
  19701. }
  19702. TEST(WebSocketTest, ComplexPath) {
  19703. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19704. EXPECT_TRUE(ws1.is_valid());
  19705. ws::WebSocketClient ws2("ws://localhost:8080/");
  19706. EXPECT_TRUE(ws2.is_valid());
  19707. }
  19708. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19709. Server svr;
  19710. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19711. std::string msg;
  19712. while (ws.read(msg)) {}
  19713. });
  19714. auto port = svr.bind_to_any_port(HOST);
  19715. std::thread t([&]() { svr.listen_after_bind(); });
  19716. svr.wait_until_ready();
  19717. auto another_host = "example.com";
  19718. auto wrong_ip = "192.0.2.1";
  19719. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19720. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19721. ASSERT_TRUE(client.connect());
  19722. EXPECT_TRUE(client.is_open());
  19723. client.close();
  19724. svr.stop();
  19725. t.join();
  19726. }
  19727. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19728. Server svr;
  19729. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19730. std::string msg;
  19731. while (ws.read(msg)) {}
  19732. });
  19733. auto port = svr.bind_to_any_port(HOST);
  19734. std::thread t([&]() { svr.listen_after_bind(); });
  19735. svr.wait_until_ready();
  19736. auto wrong_ip = "192.0.2.1";
  19737. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19738. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19739. client.set_connection_timeout(1);
  19740. client.set_read_timeout(1);
  19741. client.set_write_timeout(1);
  19742. EXPECT_FALSE(client.connect());
  19743. EXPECT_FALSE(client.is_open());
  19744. svr.stop();
  19745. t.join();
  19746. }
  19747. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19748. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19749. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19750. // (RFC 6761) is only a map key and the Host header value.
  19751. auto host = "target.invalid";
  19752. Server svr;
  19753. std::string received_host;
  19754. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19755. received_host = req.get_header_value("Host");
  19756. std::string msg;
  19757. while (ws.read(msg)) {}
  19758. });
  19759. auto port = svr.bind_to_any_port(HOST);
  19760. std::thread t([&]() { svr.listen_after_bind(); });
  19761. // ASSERT_* below returns from the test body, which would leave t joinable
  19762. // and make ~thread call std::terminate.
  19763. auto se = detail::scope_exit([&] {
  19764. svr.stop();
  19765. if (t.joinable()) { t.join(); }
  19766. });
  19767. svr.wait_until_ready();
  19768. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19769. std::to_string(port) + "/ws");
  19770. client.set_hostname_addr_map({{host, HOST}});
  19771. ASSERT_TRUE(client.connect());
  19772. EXPECT_TRUE(client.is_open());
  19773. client.close();
  19774. svr.stop();
  19775. t.join();
  19776. // The mapping only redirects the connection; the identity stays host_.
  19777. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19778. }
  19779. class WebSocketIntegrationTest : public ::testing::Test {
  19780. protected:
  19781. void SetUp() override {
  19782. server_ = httplib::detail::make_unique<Server>();
  19783. setup_server();
  19784. start_server();
  19785. }
  19786. void TearDown() override {
  19787. server_->stop();
  19788. if (server_thread_.joinable()) { server_thread_.join(); }
  19789. }
  19790. void setup_server() {
  19791. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19792. std::string msg;
  19793. ws::ReadResult ret;
  19794. while ((ret = ws.read(msg))) {
  19795. if (ret == ws::Binary) {
  19796. ws.send(msg.data(), msg.size());
  19797. } else {
  19798. ws.send(msg);
  19799. }
  19800. }
  19801. });
  19802. server_->WebSocket("/ws-echo-string",
  19803. [](const Request &, ws::WebSocket &ws) {
  19804. std::string msg;
  19805. while (ws.read(msg)) {
  19806. ws.send("echo: " + msg);
  19807. }
  19808. });
  19809. server_->WebSocket(
  19810. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19811. // Echo back request metadata
  19812. ws.send("path:" + req.path);
  19813. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19814. std::string msg;
  19815. while (ws.read(msg)) {}
  19816. });
  19817. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19818. std::string msg;
  19819. ws.read(msg); // wait for a message
  19820. ws.close();
  19821. });
  19822. server_->WebSocket("/ws-close-status",
  19823. [](const Request &, ws::WebSocket &ws) {
  19824. std::string msg;
  19825. ws.read(msg); // wait for a message
  19826. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19827. });
  19828. server_->WebSocket(
  19829. "/ws-subprotocol",
  19830. [](const Request &, ws::WebSocket &ws) {
  19831. std::string msg;
  19832. while (ws.read(msg)) {
  19833. ws.send(msg);
  19834. }
  19835. },
  19836. [](const std::vector<std::string> &protocols) -> std::string {
  19837. for (const auto &p : protocols) {
  19838. if (p == "graphql-ws") { return p; }
  19839. }
  19840. return "";
  19841. });
  19842. }
  19843. void start_server() {
  19844. port_ = server_->bind_to_any_port(HOST);
  19845. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19846. server_->wait_until_ready();
  19847. }
  19848. std::unique_ptr<Server> server_;
  19849. std::thread server_thread_;
  19850. int port_ = 0;
  19851. };
  19852. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19854. "/ws-echo");
  19855. ASSERT_TRUE(client.connect());
  19856. ASSERT_TRUE(client.is_open());
  19857. ASSERT_TRUE(client.send("Hello WebSocket"));
  19858. std::string msg;
  19859. EXPECT_EQ(ws::Text, client.read(msg));
  19860. EXPECT_EQ("Hello WebSocket", msg);
  19861. client.close();
  19862. }
  19863. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19864. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19865. "/ws-echo");
  19866. ASSERT_TRUE(client.connect());
  19867. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19868. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19869. std::string msg;
  19870. EXPECT_EQ(ws::Binary, client.read(msg));
  19871. EXPECT_EQ(binary_data, msg);
  19872. client.close();
  19873. }
  19874. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19876. "/ws-echo");
  19877. ASSERT_TRUE(client.connect());
  19878. for (int i = 0; i < 10; i++) {
  19879. auto text = "message " + std::to_string(i);
  19880. ASSERT_TRUE(client.send(text));
  19881. std::string msg;
  19882. ASSERT_TRUE(client.read(msg));
  19883. EXPECT_EQ(text, msg);
  19884. }
  19885. client.close();
  19886. }
  19887. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19889. "/ws-close");
  19890. ASSERT_TRUE(client.connect());
  19891. // Send a message to trigger the server to close
  19892. ASSERT_TRUE(client.send("trigger close"));
  19893. // The server will close, so read should return false
  19894. std::string msg;
  19895. EXPECT_FALSE(client.read(msg));
  19896. EXPECT_FALSE(client.is_open());
  19897. }
  19898. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19900. "/ws-echo");
  19901. ASSERT_TRUE(client.connect());
  19902. // 128KB message
  19903. std::string large_data(128 * 1024, 'X');
  19904. ASSERT_TRUE(client.send(large_data));
  19905. std::string msg;
  19906. ASSERT_TRUE(client.read(msg));
  19907. EXPECT_EQ(large_data, msg);
  19908. client.close();
  19909. }
  19910. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19911. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19912. "/ws-echo");
  19913. ASSERT_TRUE(client.connect());
  19914. const int num_threads = 4;
  19915. std::vector<std::thread> threads;
  19916. std::atomic<int> send_count{0};
  19917. for (int t = 0; t < num_threads; t++) {
  19918. threads.emplace_back([&client, &send_count, t]() {
  19919. for (int i = 0; i < 5; i++) {
  19920. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19921. if (client.send(text)) { send_count++; }
  19922. }
  19923. });
  19924. }
  19925. for (auto &th : threads) {
  19926. th.join();
  19927. }
  19928. int received = 0;
  19929. std::string msg;
  19930. while (received < send_count.load()) {
  19931. if (!client.read(msg)) { break; }
  19932. received++;
  19933. }
  19934. EXPECT_EQ(send_count.load(), received);
  19935. client.close();
  19936. }
  19937. TEST_F(WebSocketIntegrationTest, ReadString) {
  19938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19939. "/ws-echo-string");
  19940. ASSERT_TRUE(client.connect());
  19941. ASSERT_TRUE(client.send("hello"));
  19942. std::string msg;
  19943. ASSERT_TRUE(client.read(msg));
  19944. EXPECT_EQ("echo: hello", msg);
  19945. ASSERT_TRUE(client.send("world"));
  19946. ASSERT_TRUE(client.read(msg));
  19947. EXPECT_EQ("echo: world", msg);
  19948. client.close();
  19949. }
  19950. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19951. Headers headers = {{"X-Test-Header", "test-value"}};
  19952. ws::WebSocketClient client(
  19953. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19954. ASSERT_TRUE(client.connect());
  19955. std::string msg;
  19956. ASSERT_TRUE(client.read(msg));
  19957. EXPECT_EQ("path:/ws-request-info", msg);
  19958. ASSERT_TRUE(client.read(msg));
  19959. EXPECT_EQ("header:test-value", msg);
  19960. client.close();
  19961. }
  19962. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19963. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19964. "/ws-echo");
  19965. client.set_read_timeout(1, 0); // 1 second
  19966. ASSERT_TRUE(client.connect());
  19967. // Don't send anything — server echo handler waits for a message, so read()
  19968. // should time out. The connection survives it: nothing was consumed.
  19969. std::string msg;
  19970. EXPECT_EQ(client.read(msg), ws::Timeout);
  19971. EXPECT_TRUE(client.is_open());
  19972. // And it is still usable afterwards.
  19973. EXPECT_TRUE(client.send("after timeout"));
  19974. EXPECT_EQ(client.read(msg), ws::Text);
  19975. EXPECT_EQ(msg, "after timeout");
  19976. }
  19977. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19979. "/ws-echo");
  19980. client.set_read_timeout(1, 0);
  19981. ASSERT_TRUE(client.connect());
  19982. ASSERT_TRUE(client.send("first"));
  19983. std::string msg;
  19984. ASSERT_EQ(client.read(msg), ws::Text);
  19985. ASSERT_EQ(msg, "first");
  19986. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19987. // not be used with a read timeout: it would reprocess the previous message.
  19988. EXPECT_EQ(client.read(msg), ws::Timeout);
  19989. EXPECT_EQ(msg, "first");
  19990. }
  19991. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19992. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19993. "/ws-echo");
  19994. ASSERT_TRUE(client.connect());
  19995. // Setting it once the connection is open reaches the live stream, not just
  19996. // the seed for the next connect().
  19997. client.set_read_timeout(1, 0);
  19998. std::string msg;
  19999. EXPECT_EQ(client.read(msg), ws::Timeout);
  20000. EXPECT_TRUE(client.is_open());
  20001. }
  20002. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20004. "/ws-echo");
  20005. client.set_read_timeout(5, 0);
  20006. ASSERT_TRUE(client.connect());
  20007. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20008. // The server should reject it and close the connection.
  20009. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20010. client.send(oversized);
  20011. // The server's read() should have failed due to payload limit,
  20012. // so our read() should return false (connection closed).
  20013. std::string msg;
  20014. EXPECT_FALSE(client.read(msg));
  20015. }
  20016. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20018. "/ws-echo");
  20019. client.set_read_timeout(10, 0);
  20020. ASSERT_TRUE(client.connect());
  20021. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20022. // This should succeed.
  20023. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20024. ASSERT_TRUE(client.send(at_limit));
  20025. std::string msg;
  20026. ASSERT_TRUE(client.read(msg));
  20027. EXPECT_EQ(at_limit.size(), msg.size());
  20028. client.close();
  20029. }
  20030. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20031. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20032. "/nonexistent");
  20033. auto res = client.connect();
  20034. EXPECT_FALSE(res);
  20035. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20036. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20037. EXPECT_FALSE(client.is_open());
  20038. }
  20039. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20041. "/ws-echo");
  20042. ASSERT_TRUE(client.connect());
  20043. ASSERT_TRUE(client.send(""));
  20044. std::string msg;
  20045. EXPECT_EQ(ws::Text, client.read(msg));
  20046. EXPECT_EQ("", msg);
  20047. client.close();
  20048. }
  20049. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20051. "/ws-echo");
  20052. // First connection
  20053. ASSERT_TRUE(client.connect());
  20054. ASSERT_TRUE(client.send("first"));
  20055. std::string msg;
  20056. ASSERT_TRUE(client.read(msg));
  20057. EXPECT_EQ("first", msg);
  20058. client.close();
  20059. EXPECT_FALSE(client.is_open());
  20060. // Reconnect using the same client object
  20061. ASSERT_TRUE(client.connect());
  20062. ASSERT_TRUE(client.is_open());
  20063. ASSERT_TRUE(client.send("second"));
  20064. ASSERT_TRUE(client.read(msg));
  20065. EXPECT_EQ("second", msg);
  20066. client.close();
  20067. }
  20068. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20069. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20070. "/ws-close-status");
  20071. ASSERT_TRUE(client.connect());
  20072. // Trigger the server to close with GoingAway status
  20073. ASSERT_TRUE(client.send("trigger"));
  20074. // read() should return false after receiving the close frame
  20075. std::string msg;
  20076. EXPECT_FALSE(client.read(msg));
  20077. EXPECT_FALSE(client.is_open());
  20078. }
  20079. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20080. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20081. "/ws-echo");
  20082. ASSERT_TRUE(client.connect());
  20083. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20084. EXPECT_FALSE(client.is_open());
  20085. }
  20086. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20087. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20088. ws::WebSocketClient client(
  20089. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20090. ASSERT_TRUE(client.connect());
  20091. // Server should have selected graphql-ws
  20092. EXPECT_EQ("graphql-ws", client.subprotocol());
  20093. client.close();
  20094. }
  20095. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20096. Headers headers;
  20097. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20098. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20099. ws::WebSocketClient client(
  20100. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20101. ASSERT_TRUE(client.connect());
  20102. // The offer on the second field line counts too, so graphql-ws is selected
  20103. EXPECT_EQ("graphql-ws", client.subprotocol());
  20104. client.close();
  20105. }
  20106. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20107. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20108. ws::WebSocketClient client(
  20109. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20110. ASSERT_TRUE(client.connect());
  20111. // Server should not have selected any subprotocol
  20112. EXPECT_TRUE(client.subprotocol().empty());
  20113. client.close();
  20114. }
  20115. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20116. // Connect without requesting any subprotocol
  20117. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20118. "/ws-subprotocol");
  20119. ASSERT_TRUE(client.connect());
  20120. EXPECT_TRUE(client.subprotocol().empty());
  20121. client.close();
  20122. }
  20123. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20125. "/ws-echo");
  20126. client.set_tcp_nodelay(true);
  20127. client.set_connection_timeout(3, 0);
  20128. bool socket_options_called = false;
  20129. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20130. ASSERT_TRUE(client.connect());
  20131. ASSERT_TRUE(client.is_open());
  20132. EXPECT_TRUE(socket_options_called);
  20133. ASSERT_TRUE(client.send("hello"));
  20134. std::string msg;
  20135. auto result = client.read(msg);
  20136. EXPECT_EQ(result, ws::ReadResult::Text);
  20137. EXPECT_EQ(msg, "hello");
  20138. client.close();
  20139. }
  20140. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20141. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20142. "/ws-echo");
  20143. client.set_connection_timeout(std::chrono::seconds(3));
  20144. client.set_write_timeout(std::chrono::seconds(3));
  20145. // A sub-second remainder exercises the seconds/microseconds split.
  20146. client.set_read_timeout(std::chrono::milliseconds(1500));
  20147. ASSERT_TRUE(client.connect());
  20148. auto start = std::chrono::steady_clock::now();
  20149. std::string msg;
  20150. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20151. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20152. std::chrono::steady_clock::now() - start)
  20153. .count();
  20154. // Above 1s so that dropping the microseconds half of the split fails here.
  20155. // Ignoring the setter altogether would not reach this line at all: a client
  20156. // waits forever by default.
  20157. EXPECT_GE(elapsed, 1400);
  20158. EXPECT_LT(elapsed, 30000);
  20159. }
  20160. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20161. Server svr;
  20162. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20163. if (!req.has_header("Authorization")) {
  20164. res.status = StatusCode::Unauthorized_401;
  20165. res.set_content("Unauthorized", "text/plain");
  20166. return Server::HandlerResponse::Handled;
  20167. }
  20168. return Server::HandlerResponse::Unhandled;
  20169. });
  20170. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20171. std::string msg;
  20172. while (ws.read(msg)) {
  20173. ws.send(msg);
  20174. }
  20175. });
  20176. auto port = svr.bind_to_any_port("localhost");
  20177. std::thread t([&]() { svr.listen_after_bind(); });
  20178. svr.wait_until_ready();
  20179. // Without Authorization header - should be rejected before upgrade
  20180. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20181. EXPECT_FALSE(client1.connect());
  20182. // The rejection is framed like any other HTTP response
  20183. {
  20184. Client cli("localhost", port);
  20185. Headers headers = {{"Upgrade", "websocket"},
  20186. {"Connection", "Upgrade"},
  20187. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20188. {"Sec-WebSocket-Version", "13"}};
  20189. auto res = cli.Get("/ws", headers);
  20190. ASSERT_TRUE(res);
  20191. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20192. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20193. EXPECT_EQ("Unauthorized", res->body);
  20194. }
  20195. // With Authorization header - should succeed
  20196. Headers headers = {{"Authorization", "Bearer token123"}};
  20197. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20198. headers);
  20199. ASSERT_TRUE(client2.connect());
  20200. ASSERT_TRUE(client2.send("hello"));
  20201. std::string msg;
  20202. ASSERT_TRUE(client2.read(msg));
  20203. EXPECT_EQ("hello", msg);
  20204. client2.close();
  20205. svr.stop();
  20206. t.join();
  20207. }
  20208. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20209. Server svr;
  20210. std::atomic<int> pre_request_calls{0};
  20211. std::atomic<bool> route_matched{false};
  20212. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20213. pre_request_calls++;
  20214. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20215. if (req.get_header_value("Authorization") != "Bearer token123") {
  20216. res.status = StatusCode::Unauthorized_401;
  20217. res.set_content("Unauthorized", "text/plain");
  20218. return Server::HandlerResponse::Handled;
  20219. }
  20220. return Server::HandlerResponse::Unhandled;
  20221. });
  20222. std::atomic<bool> handler_called{false};
  20223. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20224. handler_called = true;
  20225. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20226. });
  20227. auto port = svr.bind_to_any_port("localhost");
  20228. std::thread t([&]() { svr.listen_after_bind(); });
  20229. svr.wait_until_ready();
  20230. // Without Authorization header - should be rejected before upgrade
  20231. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20232. "/ws/1");
  20233. EXPECT_FALSE(client1.connect());
  20234. EXPECT_FALSE(handler_called);
  20235. EXPECT_EQ(1, pre_request_calls);
  20236. EXPECT_TRUE(route_matched);
  20237. // The rejection is an ordinary HTTP response, not a protocol switch
  20238. {
  20239. Client cli("localhost", port);
  20240. Headers headers = {{"Upgrade", "websocket"},
  20241. {"Connection", "Upgrade"},
  20242. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20243. {"Sec-WebSocket-Version", "13"}};
  20244. auto res = cli.Get("/ws/1", headers);
  20245. ASSERT_TRUE(res);
  20246. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20247. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20248. EXPECT_EQ("Unauthorized", res->body);
  20249. }
  20250. EXPECT_FALSE(handler_called);
  20251. // With Authorization header - should succeed
  20252. Headers headers = {{"Authorization", "Bearer token123"}};
  20253. ws::WebSocketClient client2(
  20254. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20255. ASSERT_TRUE(client2.connect());
  20256. std::string msg;
  20257. ASSERT_TRUE(client2.read(msg));
  20258. EXPECT_EQ("/ws/:id 2", msg);
  20259. EXPECT_TRUE(handler_called);
  20260. client2.close();
  20261. svr.stop();
  20262. t.join();
  20263. }
  20264. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20265. Server svr;
  20266. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20267. // A read timeout is how a handler gets control back. Without it, a handler
  20268. // parked in read() can never write on the connection it is reading.
  20269. ws.set_read_timeout(std::chrono::milliseconds(100));
  20270. std::string msg;
  20271. while (ws.is_open()) {
  20272. auto r = ws.read(msg);
  20273. if (r == httplib::ws::Timeout) {
  20274. ws.send("tick");
  20275. continue;
  20276. }
  20277. if (r == httplib::ws::Fail) { break; }
  20278. ws.send(msg);
  20279. }
  20280. });
  20281. auto port = svr.bind_to_any_port("localhost");
  20282. std::thread t([&]() { svr.listen_after_bind(); });
  20283. svr.wait_until_ready();
  20284. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20285. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20286. ASSERT_TRUE(client.connect());
  20287. // The client sends nothing, so anything it receives came out of the
  20288. // handler's timeout path.
  20289. std::string msg;
  20290. ASSERT_EQ(client.read(msg), ws::Text);
  20291. EXPECT_EQ("tick", msg);
  20292. client.close();
  20293. svr.stop();
  20294. t.join();
  20295. }
  20296. // Stream::read may return fewer bytes than asked for. This is that contract at
  20297. // its worst -- one byte per call -- which is what a frame header straddling a
  20298. // read buffer's boundary looks like to the frame parser.
  20299. class WsByteAtATimeStream : public Stream {
  20300. public:
  20301. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20302. bool is_readable() const override { return true; }
  20303. bool wait_readable() const override { return true; }
  20304. bool wait_writable() const override { return true; }
  20305. ssize_t read(char *ptr, size_t size) override {
  20306. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20307. *ptr = data_[pos_++];
  20308. return 1;
  20309. }
  20310. ssize_t write(const char *, size_t size) override {
  20311. return static_cast<ssize_t>(size);
  20312. }
  20313. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20314. ip = "127.0.0.1";
  20315. port = 0;
  20316. }
  20317. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20318. ip = "127.0.0.1";
  20319. port = 0;
  20320. }
  20321. socket_t socket() const override { return INVALID_SOCKET; }
  20322. time_t duration() const override { return 0; }
  20323. private:
  20324. std::string data_;
  20325. size_t pos_ = 0;
  20326. };
  20327. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20328. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20329. // length and the mask key are all multi-byte fields here. Each used to be
  20330. // read with a single read() call, which fails as soon as one is split.
  20331. std::string body(200, 'x');
  20332. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20333. std::string frame;
  20334. frame += static_cast<char>(0x81); // FIN + Text
  20335. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20336. frame += static_cast<char>(body.size() >> 8);
  20337. frame += static_cast<char>(body.size() & 0xff);
  20338. for (size_t i = 0; i < 4; i++) {
  20339. frame += static_cast<char>(mask[i]);
  20340. }
  20341. for (size_t i = 0; i < body.size(); i++) {
  20342. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20343. }
  20344. WsByteAtATimeStream strm(frame);
  20345. ws::Opcode opcode;
  20346. std::string payload;
  20347. bool fin = false;
  20348. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20349. /*expect_masked=*/true, 1024),
  20350. ws::impl::FrameRead::Ok);
  20351. EXPECT_TRUE(fin);
  20352. EXPECT_EQ(opcode, ws::Opcode::Text);
  20353. EXPECT_EQ(payload, body);
  20354. }
  20355. TEST(WebSocketTest, QueryStringInHandshake) {
  20356. Server svr;
  20357. std::mutex mtx;
  20358. std::string received_target;
  20359. std::string received_token;
  20360. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20361. {
  20362. std::lock_guard<std::mutex> lock(mtx);
  20363. received_target = req.target;
  20364. if (req.has_param("token")) {
  20365. received_token = req.get_param_value("token");
  20366. }
  20367. }
  20368. std::string msg;
  20369. while (ws.read(msg)) {
  20370. ws.send(msg);
  20371. }
  20372. });
  20373. auto port = svr.bind_to_any_port("localhost");
  20374. std::thread t([&]() { svr.listen_after_bind(); });
  20375. svr.wait_until_ready();
  20376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20377. "/ws?token=ABC&session=123");
  20378. ASSERT_TRUE(client.connect());
  20379. // Round-trip ensures the handler has run and captured the request.
  20380. ASSERT_TRUE(client.send("hello"));
  20381. std::string msg;
  20382. ASSERT_TRUE(client.read(msg));
  20383. EXPECT_EQ("hello", msg);
  20384. client.close();
  20385. {
  20386. std::lock_guard<std::mutex> lock(mtx);
  20387. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20388. EXPECT_EQ("ABC", received_token);
  20389. }
  20390. svr.stop();
  20391. t.join();
  20392. }
  20393. // Run a handshake against a throwaway server and hand the request the server
  20394. // received back to the caller, so tests can assert on the headers the client
  20395. // actually put on the wire.
  20396. static void capture_websocket_handshake_request(
  20397. const Headers &client_headers,
  20398. std::function<void(const Request &, int port)> verify) {
  20399. Server svr;
  20400. std::mutex mtx;
  20401. Request received;
  20402. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20403. {
  20404. std::lock_guard<std::mutex> lock(mtx);
  20405. received = req;
  20406. }
  20407. std::string msg;
  20408. while (ws.read(msg)) {
  20409. ws.send(msg);
  20410. }
  20411. });
  20412. auto port = svr.bind_to_any_port("localhost");
  20413. std::thread t([&]() { svr.listen_after_bind(); });
  20414. auto se = detail::scope_exit([&] {
  20415. svr.stop();
  20416. t.join();
  20417. });
  20418. svr.wait_until_ready();
  20419. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20420. client_headers);
  20421. ASSERT_TRUE(client.connect());
  20422. ASSERT_TRUE(client.send("hello"));
  20423. std::string msg;
  20424. ASSERT_TRUE(client.read(msg));
  20425. client.close();
  20426. {
  20427. std::lock_guard<std::mutex> lock(mtx);
  20428. verify(received, port);
  20429. }
  20430. }
  20431. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20432. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20433. // Non-default port must be present in the Host header. Default ports
  20434. // (80/443) are omitted; that logic is covered by
  20435. // MakeHostAndPortStringTest.
  20436. EXPECT_EQ("localhost:" + std::to_string(port),
  20437. req.get_header_value("Host"));
  20438. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20439. req.get_header_value("User-Agent"));
  20440. EXPECT_FALSE(req.has_header("Accept"));
  20441. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20442. EXPECT_FALSE(req.has_header("Content-Length"));
  20443. });
  20444. }
  20445. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20446. capture_websocket_handshake_request(
  20447. {{"Host", "example.com"},
  20448. {"User-Agent", "custom-agent"},
  20449. {"X-Custom", "value"}},
  20450. [](const Request &req, int) {
  20451. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20452. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20453. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20454. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20455. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20456. });
  20457. }
  20458. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20459. capture_websocket_handshake_request(
  20460. {{"Upgrade", "bogus"},
  20461. {"Connection", "close"},
  20462. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20463. {"Sec-WebSocket-Version", "8"}},
  20464. [](const Request &req, int) {
  20465. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20466. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20467. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20468. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20469. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20470. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20471. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20472. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20473. req.get_header_value("Sec-WebSocket-Key"));
  20474. });
  20475. }
  20476. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20477. // A header the client refuses to send must abort the handshake before any
  20478. // part of it reaches the wire; a lone request line would otherwise sit in
  20479. // the peer's buffer as a truncated request.
  20480. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20481. ASSERT_NE(INVALID_SOCKET, srv);
  20482. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20483. sockaddr_in addr{};
  20484. addr.sin_family = AF_INET;
  20485. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20487. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20488. ASSERT_EQ(0, ::listen(srv, 1));
  20489. sockaddr_in bound{};
  20490. socklen_t bound_len = sizeof(bound);
  20491. ASSERT_EQ(
  20492. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20493. auto port = ntohs(bound.sin_port);
  20494. ssize_t received = -1;
  20495. std::thread t([&] {
  20496. // Bound every blocking call so a regression fails the test with a bad
  20497. // value instead of hanging the suite.
  20498. fd_set rfds;
  20499. FD_ZERO(&rfds);
  20500. FD_SET(srv, &rfds);
  20501. timeval tv{5, 0};
  20502. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20503. 0) {
  20504. return;
  20505. }
  20506. sockaddr_in cli_addr{};
  20507. socklen_t cli_len = sizeof(cli_addr);
  20508. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20509. if (cli == INVALID_SOCKET) { return; }
  20510. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20511. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20512. char buf[4096];
  20513. received = ::recv(cli, buf, sizeof(buf), 0);
  20514. });
  20515. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20516. // connect() has already shut the socket down by the time it returns false,
  20517. // so the peer sees EOF without waiting for the client to be destroyed.
  20518. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20519. {{"X-Bad", "a\r\nInjected: 1"}});
  20520. EXPECT_FALSE(client.connect());
  20521. t.join();
  20522. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20523. EXPECT_EQ(0, received);
  20524. }
  20525. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20526. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20527. // contains "upgrade" as a substring is a different token and must not
  20528. // start a WebSocket handshake.
  20529. auto make_request = [](const std::vector<std::string> &connection_values) {
  20530. Request req;
  20531. req.method = "GET";
  20532. req.headers.emplace("Upgrade", "websocket");
  20533. for (const auto &value : connection_values) {
  20534. req.headers.emplace("Connection", value);
  20535. }
  20536. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20537. req.headers.emplace("Sec-WebSocket-Version", "13");
  20538. return req;
  20539. };
  20540. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20541. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20542. EXPECT_TRUE(
  20543. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20544. EXPECT_TRUE(
  20545. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20546. EXPECT_TRUE(
  20547. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20548. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20549. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20550. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20551. EXPECT_FALSE(
  20552. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20553. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20554. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20555. }
  20556. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20557. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20558. // asks recipients to match each protocol-name case-insensitively, and RFC
  20559. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20560. // client naming websocket alongside another protocol, or on a second field
  20561. // line, is offering websocket; a value that merely contains "websocket" as a
  20562. // substring is a different protocol name and is not.
  20563. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20564. Request req;
  20565. req.method = "GET";
  20566. for (const auto &value : upgrade_values) {
  20567. req.headers.emplace("Upgrade", value);
  20568. }
  20569. req.headers.emplace("Connection", "Upgrade");
  20570. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20571. req.headers.emplace("Sec-WebSocket-Version", "13");
  20572. return req;
  20573. };
  20574. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20575. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20576. EXPECT_TRUE(
  20577. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20578. EXPECT_TRUE(
  20579. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20580. EXPECT_TRUE(
  20581. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20582. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20583. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20584. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20585. EXPECT_FALSE(
  20586. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20587. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20588. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20589. }
  20590. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20591. Server svr;
  20592. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20593. auto port = svr.bind_to_any_port("localhost");
  20594. std::thread t([&]() { svr.listen_after_bind(); });
  20595. auto se = detail::scope_exit([&] {
  20596. svr.stop();
  20597. t.join();
  20598. });
  20599. svr.wait_until_ready();
  20600. Headers headers = {{"Upgrade", "websocket"},
  20601. {"Connection", "notupgrade"},
  20602. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20603. {"Sec-WebSocket-Version", "13"}};
  20604. Client cli("localhost", port);
  20605. auto res = cli.Get("/ws", headers);
  20606. // The route exists only as a WebSocket route, so a request that fails the
  20607. // handshake check falls through to ordinary routing.
  20608. ASSERT_TRUE(res);
  20609. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20610. }
  20611. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20612. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20613. // Connection value is the only thing left for the client to reject.
  20614. Server svr;
  20615. svr.Get("/ws", [](const Request &req, Response &res) {
  20616. res.status = StatusCode::SwitchingProtocol_101;
  20617. res.set_header("Upgrade", "websocket");
  20618. res.set_header("Connection", "notupgrade");
  20619. res.set_header("Sec-WebSocket-Accept",
  20620. detail::websocket_accept_key(
  20621. req.get_header_value("Sec-WebSocket-Key")));
  20622. });
  20623. auto port = svr.bind_to_any_port("localhost");
  20624. std::thread t([&]() { svr.listen_after_bind(); });
  20625. auto se = detail::scope_exit([&] {
  20626. svr.stop();
  20627. t.join();
  20628. });
  20629. svr.wait_until_ready();
  20630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20631. auto res = client.connect();
  20632. EXPECT_FALSE(res);
  20633. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20634. EXPECT_FALSE(client.is_open());
  20635. }
  20636. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20637. // The socket path doubles as the URL host, so it must not contain '/'.
  20638. const char *shard = getenv("GTEST_SHARD_INDEX");
  20639. const std::string sock_path =
  20640. shard ? std::string("httplib-ws-") + shard + ".sock"
  20641. : std::string("httplib-ws.sock");
  20642. std::remove(sock_path.c_str());
  20643. Server svr;
  20644. std::mutex mtx;
  20645. std::string received_host;
  20646. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20647. {
  20648. std::lock_guard<std::mutex> lock(mtx);
  20649. received_host = req.get_header_value("Host");
  20650. }
  20651. std::string msg;
  20652. while (ws.read(msg)) {
  20653. ws.send(msg);
  20654. }
  20655. });
  20656. svr.set_address_family(AF_UNIX);
  20657. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20658. auto se = detail::scope_exit([&] {
  20659. svr.stop();
  20660. t.join();
  20661. std::remove(sock_path.c_str());
  20662. });
  20663. svr.wait_until_ready();
  20664. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20665. client.set_address_family(AF_UNIX);
  20666. ASSERT_TRUE(client.connect());
  20667. ASSERT_TRUE(client.send("hello"));
  20668. std::string msg;
  20669. ASSERT_TRUE(client.read(msg));
  20670. client.close();
  20671. {
  20672. std::lock_guard<std::mutex> lock(mtx);
  20673. // There is no host:port for a Unix socket, so the same "localhost"
  20674. // placeholder the HTTP client uses is expected.
  20675. EXPECT_EQ("localhost", received_host);
  20676. }
  20677. }
  20678. // Two threads must never parse WebSocket frames from the same stream.
  20679. // close() used to read the peer's Close reply with its own frame read, so it
  20680. // raced a reader thread that was in the middle of a payload: the payload loop
  20681. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20682. // so bytes taken by close() were replaced with bytes from further along the
  20683. // stream. The message kept its length and silently changed content.
  20684. //
  20685. // The raw peer below sends a frame header plus part of the payload, waits for
  20686. // the handler to call close(), and only then sends the rest. Whichever thread
  20687. // would win the race for those bytes, the message must arrive intact, because
  20688. // close() must not touch the stream while read() owns it.
  20689. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20690. #ifndef _WIN32
  20691. signal(SIGPIPE, SIG_IGN);
  20692. #endif
  20693. const size_t payload_len = 120; // fits the 7-bit length field
  20694. const size_t prefix_len = 8;
  20695. const int attempts = 8;
  20696. std::string expected(payload_len, '\0');
  20697. for (size_t i = 0; i < payload_len; i++) {
  20698. expected[i] = static_cast<char>('a' + i % 26);
  20699. }
  20700. std::atomic<bool> peer_stalled{false};
  20701. std::atomic<bool> handler_done{false};
  20702. std::mutex received_mutex;
  20703. std::vector<std::string> received;
  20704. // Bound every wait, so a regression fails the test instead of hanging the
  20705. // suite.
  20706. auto wait_for = [](const std::atomic<bool> &flag) {
  20707. for (int i = 0; i < 500 && !flag; i++) {
  20708. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20709. }
  20710. };
  20711. Server svr;
  20712. svr.set_websocket_ping_interval(0);
  20713. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20714. std::thread reader([&]() {
  20715. std::string msg;
  20716. while (ws.read(msg)) {
  20717. std::lock_guard<std::mutex> guard(received_mutex);
  20718. received.push_back(msg);
  20719. }
  20720. });
  20721. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20722. // inside read_websocket_frame() when close() runs.
  20723. wait_for(peer_stalled);
  20724. ws.close();
  20725. reader.join();
  20726. handler_done = true;
  20727. });
  20728. auto port = svr.bind_to_any_port("127.0.0.1");
  20729. std::thread t([&]() { svr.listen_after_bind(); });
  20730. auto se = detail::scope_exit([&] {
  20731. svr.stop();
  20732. t.join();
  20733. });
  20734. svr.wait_until_ready();
  20735. auto send_bytes = [](socket_t s, const std::string &data) {
  20736. #ifdef _WIN32
  20737. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20738. #else
  20739. auto n = ::send(s, data.data(), data.size(), 0);
  20740. #endif
  20741. return n == static_cast<decltype(n)>(data.size());
  20742. };
  20743. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20744. // Every length used here fits the 7-bit length field.
  20745. auto masked_header = [](uint8_t first_byte, size_t len) {
  20746. std::string h;
  20747. h += static_cast<char>(first_byte);
  20748. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20749. h.append(4, '\0'); // mask key
  20750. return h;
  20751. };
  20752. for (int attempt = 0; attempt < attempts; attempt++) {
  20753. peer_stalled = false;
  20754. handler_done = false;
  20755. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20756. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20757. auto se_sock = detail::scope_exit([&] {
  20758. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20759. });
  20760. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20761. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20762. sockaddr_in addr{};
  20763. addr.sin_family = AF_INET;
  20764. addr.sin_port = htons(static_cast<uint16_t>(port));
  20765. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20766. ASSERT_EQ(
  20767. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20768. << "attempt " << attempt;
  20769. ASSERT_TRUE(send_bytes(sock,
  20770. "GET /ws HTTP/1.1\r\n"
  20771. "Host: 127.0.0.1\r\n"
  20772. "Upgrade: websocket\r\n"
  20773. "Connection: Upgrade\r\n"
  20774. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20775. "Sec-WebSocket-Version: 13\r\n"
  20776. "\r\n"))
  20777. << "attempt " << attempt;
  20778. std::string response;
  20779. while (response.find("\r\n\r\n") == std::string::npos) {
  20780. char buf[512];
  20781. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20782. if (n <= 0) { break; }
  20783. response.append(buf, static_cast<size_t>(n));
  20784. }
  20785. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20786. << "attempt " << attempt;
  20787. // Send the header of a Binary message but only the first prefix_len bytes
  20788. // of its payload, leaving the reader thread stalled inside the payload.
  20789. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20790. expected.substr(0, prefix_len)))
  20791. << "attempt " << attempt;
  20792. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20793. peer_stalled = true;
  20794. // Let close() send its Close frame and park in its own read before the
  20795. // rest of the payload arrives, so both threads are waiting for it.
  20796. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20797. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20798. close_frame += static_cast<char>(0x03); // status 1000
  20799. close_frame += static_cast<char>(0xE8);
  20800. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20801. << "attempt " << attempt;
  20802. // Closing the peer releases the reader thread even on the buggy path,
  20803. // where it waits for bytes another thread already consumed.
  20804. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20805. detail::close_socket(sock);
  20806. sock = INVALID_SOCKET;
  20807. wait_for(handler_done);
  20808. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20809. }
  20810. std::lock_guard<std::mutex> guard(received_mutex);
  20811. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20812. << "a message in flight when close() ran was dropped";
  20813. for (size_t i = 0; i < received.size(); i++) {
  20814. EXPECT_EQ(expected, received[i]) << "message " << i;
  20815. }
  20816. }
  20817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20818. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20819. protected:
  20820. void SetUp() override {
  20821. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20822. SERVER_PRIVATE_KEY_FILE);
  20823. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20824. std::string msg;
  20825. ws::ReadResult ret;
  20826. while ((ret = ws.read(msg))) {
  20827. if (ret == ws::Binary) {
  20828. ws.send(msg.data(), msg.size());
  20829. } else {
  20830. ws.send(msg);
  20831. }
  20832. }
  20833. });
  20834. port_ = server_->bind_to_any_port(HOST);
  20835. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20836. server_->wait_until_ready();
  20837. }
  20838. void TearDown() override {
  20839. server_->stop();
  20840. if (server_thread_.joinable()) { server_thread_.join(); }
  20841. }
  20842. std::unique_ptr<SSLServer> server_;
  20843. std::thread server_thread_;
  20844. int port_ = 0;
  20845. };
  20846. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20847. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20848. "/ws-echo");
  20849. client.enable_server_certificate_verification(false);
  20850. ASSERT_TRUE(client.connect());
  20851. ASSERT_TRUE(client.is_open());
  20852. ASSERT_TRUE(client.send("Hello WSS"));
  20853. std::string msg;
  20854. EXPECT_EQ(ws::Text, client.read(msg));
  20855. EXPECT_EQ("Hello WSS", msg);
  20856. client.close();
  20857. }
  20858. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20859. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20860. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20861. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20862. // client (without calling close() first) is the only path that runs
  20863. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20864. // bug exactly.
  20865. //
  20866. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20867. // when linked against an instrumented libssl; run under Valgrind to catch it
  20868. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20869. // suite (the freed session otherwise stalls on the close handshake) — this test
  20870. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20871. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20872. {
  20873. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20874. "/ws-echo");
  20875. client.enable_server_certificate_verification(false);
  20876. client.set_read_timeout(2, 0);
  20877. client.set_write_timeout(2, 0);
  20878. ASSERT_TRUE(client.connect());
  20879. ASSERT_TRUE(client.is_open());
  20880. ASSERT_TRUE(client.send("still open"));
  20881. // Intentionally do NOT call client.close(): leaving scope runs
  20882. // shutdown_and_close() with the WebSocket still open, which must send the
  20883. // close frame while the TLS session is still alive.
  20884. }
  20885. }
  20886. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20887. // shutdown_and_close() at the start of connect(), reproducing the same
  20888. // use-after-free within the test body rather than at scope exit. The second
  20889. // connect must succeed and echo, proving the close handshake ran over a live
  20890. // session. See the note above about memory-tool requirements.
  20891. TEST_F(WebSocketSSLIntegrationTest,
  20892. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20893. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20894. "/ws-echo");
  20895. client.enable_server_certificate_verification(false);
  20896. client.set_read_timeout(2, 0);
  20897. client.set_write_timeout(2, 0);
  20898. ASSERT_TRUE(client.connect());
  20899. ASSERT_TRUE(client.is_open());
  20900. ASSERT_TRUE(client.send("still open"));
  20901. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20902. // the still-open connection, which must not touch a freed TLS session.
  20903. ASSERT_TRUE(client.connect());
  20904. ASSERT_TRUE(client.is_open());
  20905. ASSERT_TRUE(client.send("after reconnect"));
  20906. std::string msg;
  20907. EXPECT_EQ(ws::Text, client.read(msg));
  20908. EXPECT_EQ("after reconnect", msg);
  20909. client.close();
  20910. }
  20911. #endif
  20912. #ifdef CPPHTTPLIB_SSL_ENABLED
  20913. class WebSocketSSLCATest : public ::testing::Test {
  20914. protected:
  20915. void SetUp() override {
  20916. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20917. SERVER_PRIVATE_KEY_FILE);
  20918. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20919. std::string msg;
  20920. while (ws.read(msg)) {
  20921. ws.send(msg);
  20922. }
  20923. });
  20924. port_ = server_->bind_to_any_port("127.0.0.1");
  20925. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20926. server_->wait_until_ready();
  20927. }
  20928. void TearDown() override {
  20929. server_->stop();
  20930. if (server_thread_.joinable()) { server_thread_.join(); }
  20931. }
  20932. std::string url() const {
  20933. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20934. }
  20935. std::unique_ptr<SSLServer> server_;
  20936. std::thread server_thread_;
  20937. int port_ = 0;
  20938. };
  20939. // A custom CA loaded as PEM verifies the server with full certificate
  20940. // verification enabled
  20941. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20942. ws::WebSocketClient client(url());
  20943. std::string cert;
  20944. read_file(SERVER_CERT2_FILE, cert);
  20945. client.load_ca_cert_store(cert.c_str(), cert.size());
  20946. ASSERT_TRUE(client.connect());
  20947. ASSERT_TRUE(client.send("hello"));
  20948. std::string msg;
  20949. EXPECT_EQ(ws::Text, client.read(msg));
  20950. EXPECT_EQ("hello", msg);
  20951. client.close();
  20952. }
  20953. // A custom CA that does not cover the server must fail verification (the
  20954. // custom CA is exclusive; system certs are not loaded alongside it)
  20955. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20956. ws::WebSocketClient client(url());
  20957. std::string cert;
  20958. read_file(CLIENT_CA_CERT_FILE, cert);
  20959. client.load_ca_cert_store(cert.c_str(), cert.size());
  20960. auto res = client.connect();
  20961. ASSERT_FALSE(res);
  20962. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20963. EXPECT_EQ(-1, res.status());
  20964. EXPECT_NE(0u, res.ssl_backend_error());
  20965. }
  20966. // The same CA as a file path rather than PEM in memory
  20967. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20968. ws::WebSocketClient client(url());
  20969. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20970. ASSERT_TRUE(client.connect());
  20971. ASSERT_TRUE(client.send("hello"));
  20972. std::string msg;
  20973. EXPECT_EQ(ws::Text, client.read(msg));
  20974. EXPECT_EQ("hello", msg);
  20975. client.close();
  20976. }
  20977. // ...and a CA file that does not cover the server still fails, so it is the
  20978. // path above that decides the outcome
  20979. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20980. ws::WebSocketClient client(url());
  20981. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20982. ASSERT_FALSE(client.connect());
  20983. }
  20984. // Regression test: reconnecting with a native custom CA store used to reuse
  20985. // a store handle the previous TLS context had already freed (use-after-free
  20986. // under the OpenSSL backend). The context now lives as long as the client.
  20987. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20988. ws::WebSocketClient client(url());
  20989. std::string cert;
  20990. read_file(SERVER_CERT2_FILE, cert);
  20991. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20992. ASSERT_TRUE(client.connect());
  20993. client.close();
  20994. ASSERT_TRUE(client.connect());
  20995. ASSERT_TRUE(client.send("again"));
  20996. std::string msg;
  20997. EXPECT_EQ(ws::Text, client.read(msg));
  20998. EXPECT_EQ("again", msg);
  20999. client.close();
  21000. }
  21001. // Regression test: a certificate with a trusted chain but no identity match
  21002. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21003. // verification entirely for IP hosts, so this connection succeeded there.
  21004. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21005. // chain verification while the identity check must still fail.
  21006. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21008. ASSERT_TRUE(svr.is_valid());
  21009. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21010. std::string msg;
  21011. while (ws.read(msg)) {
  21012. ws.send(msg);
  21013. }
  21014. });
  21015. auto port = svr.bind_to_any_port("127.0.0.1");
  21016. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21017. auto se = detail::scope_exit([&] {
  21018. svr.stop();
  21019. t.join();
  21020. });
  21021. svr.wait_until_ready();
  21022. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21023. "/echo");
  21024. std::string cert;
  21025. read_file(SERVER_CERT_FILE, cert);
  21026. client.load_ca_cert_store(cert.c_str(), cert.size());
  21027. ASSERT_FALSE(client.connect());
  21028. }
  21029. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21030. // SNI, so nothing binds the host name to the TLS session. These bind the
  21031. // server to "localhost" instead, the only shape that exercises the SNI and
  21032. // hostname-verification path with certificate verification left enabled.
  21033. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21034. protected:
  21035. void Start(const char *cert_file) {
  21036. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21037. SERVER_PRIVATE_KEY_FILE);
  21038. ASSERT_TRUE(server_->is_valid());
  21039. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21040. std::string msg;
  21041. while (ws.read(msg)) {
  21042. ws.send(msg);
  21043. }
  21044. });
  21045. port_ = server_->bind_to_any_port("localhost");
  21046. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21047. server_->wait_until_ready();
  21048. }
  21049. void TearDown() override {
  21050. if (server_) { server_->stop(); }
  21051. if (server_thread_.joinable()) { server_thread_.join(); }
  21052. }
  21053. std::string url() const {
  21054. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21055. }
  21056. std::unique_ptr<SSLServer> server_;
  21057. std::thread server_thread_;
  21058. int port_ = 0;
  21059. };
  21060. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21061. // out and the connection is usable
  21062. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21063. Start(SERVER_CERT2_FILE);
  21064. ws::WebSocketClient client(url());
  21065. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21066. ASSERT_TRUE(client.connect());
  21067. ASSERT_TRUE(client.send("hello"));
  21068. std::string msg;
  21069. EXPECT_EQ(ws::Text, client.read(msg));
  21070. EXPECT_EQ("hello", msg);
  21071. client.close();
  21072. }
  21073. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21074. // while the identity check must still reject "localhost"
  21075. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21076. Start(SERVER_CERT_FILE);
  21077. ws::WebSocketClient client(url());
  21078. client.set_ca_cert_path(SERVER_CERT_FILE);
  21079. auto res = client.connect();
  21080. ASSERT_FALSE(res);
  21081. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21082. EXPECT_EQ(-1, res.status());
  21083. }
  21084. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21085. // disabled: the chain is still checked, only the identity check is skipped
  21086. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21087. Start(SERVER_CERT_FILE);
  21088. ws::WebSocketClient client(url());
  21089. client.set_ca_cert_path(SERVER_CERT_FILE);
  21090. client.enable_server_hostname_verification(false);
  21091. ASSERT_TRUE(client.connect());
  21092. ASSERT_TRUE(client.send("hello"));
  21093. std::string msg;
  21094. EXPECT_EQ(ws::Text, client.read(msg));
  21095. EXPECT_EQ("hello", msg);
  21096. client.close();
  21097. }
  21098. // A CA that did not sign the server certificate fails the chain, even though
  21099. // the name would match
  21100. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21101. Start(SERVER_CERT2_FILE);
  21102. ws::WebSocketClient client(url());
  21103. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21104. ASSERT_FALSE(client.connect());
  21105. }
  21106. // With verification disabled, neither the chain nor the name is checked
  21107. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21108. Start(SERVER_CERT_FILE);
  21109. ws::WebSocketClient client(url());
  21110. client.enable_server_certificate_verification(false);
  21111. ASSERT_TRUE(client.connect());
  21112. ASSERT_TRUE(client.send("hello"));
  21113. std::string msg;
  21114. EXPECT_EQ(ws::Text, client.read(msg));
  21115. EXPECT_EQ("hello", msg);
  21116. client.close();
  21117. }
  21118. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21119. protected:
  21120. void SetUp() override {
  21121. server_ = httplib::detail::make_unique<SSLServer>(
  21122. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21123. ASSERT_TRUE(server_->is_valid());
  21124. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21125. std::string msg;
  21126. while (ws.read(msg)) {
  21127. ws.send(msg);
  21128. }
  21129. });
  21130. port_ = server_->bind_to_any_port("localhost");
  21131. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21132. server_->wait_until_ready();
  21133. }
  21134. void TearDown() override {
  21135. server_->stop();
  21136. if (server_thread_.joinable()) { server_thread_.join(); }
  21137. }
  21138. std::string url() const {
  21139. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21140. }
  21141. void ConnectWithClientCert(const std::string &client_cert_file,
  21142. const std::string &client_private_key_file,
  21143. const char *private_key_password) {
  21144. std::string cert_pem, key_pem;
  21145. read_file(client_cert_file, cert_pem);
  21146. read_file(client_private_key_file, key_pem);
  21147. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21148. key_pem.c_str(), key_pem.size(),
  21149. private_key_password};
  21150. ws::WebSocketClient client(url(), pem);
  21151. ASSERT_TRUE(client.is_valid());
  21152. client.enable_server_certificate_verification(false);
  21153. ASSERT_TRUE(client.connect());
  21154. ASSERT_TRUE(client.send("hello"));
  21155. std::string msg;
  21156. EXPECT_EQ(ws::Text, client.read(msg));
  21157. EXPECT_EQ("hello", msg);
  21158. client.close();
  21159. }
  21160. std::unique_ptr<SSLServer> server_;
  21161. std::thread server_thread_;
  21162. int port_ = 0;
  21163. };
  21164. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21165. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21166. }
  21167. // Control for the tests above: the fixture's server really does require a
  21168. // client certificate, so it is the PEM the constructor installed that decides
  21169. // the outcome.
  21170. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21171. ws::WebSocketClient client(url());
  21172. ASSERT_TRUE(client.is_valid());
  21173. client.enable_server_certificate_verification(false);
  21174. EXPECT_FALSE(client.connect());
  21175. }
  21176. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21177. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21178. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21179. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21180. }
  21181. #endif
  21182. #if !defined(_WIN32)
  21183. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21184. auto secret_dir = std::string("./symlink_test_secret");
  21185. auto served_dir = std::string("./symlink_test_served");
  21186. auto secret_file = secret_dir + "/secret.txt";
  21187. auto symlink_path = served_dir + "/escape";
  21188. // Setup: create directories and files
  21189. mkdir(secret_dir.c_str(), 0755);
  21190. mkdir(served_dir.c_str(), 0755);
  21191. {
  21192. std::ofstream ofs(secret_file);
  21193. ofs << "SECRET_DATA";
  21194. }
  21195. // Create symlink using absolute path so it resolves correctly
  21196. #ifdef PATH_MAX
  21197. char abs_secret[PATH_MAX];
  21198. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21199. #else
  21200. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21201. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21202. ASSERT_NE(nullptr, abs_secret);
  21203. #endif
  21204. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21205. auto se = detail::scope_exit([&] {
  21206. unlink(symlink_path.c_str());
  21207. unlink(secret_file.c_str());
  21208. rmdir(served_dir.c_str());
  21209. rmdir(secret_dir.c_str());
  21210. });
  21211. Server svr;
  21212. svr.set_mount_point("/", served_dir);
  21213. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21214. auto se2 = detail::scope_exit([&] {
  21215. svr.stop();
  21216. listen_thread.join();
  21217. });
  21218. svr.wait_until_ready();
  21219. Client cli("localhost", PORT);
  21220. // Symlink pointing outside base dir should be blocked
  21221. auto res = cli.Get("/escape/secret.txt");
  21222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21223. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21224. }
  21225. #endif
  21226. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21227. // "GET /smuggled" request), reads the first response, and only then sends the
  21228. // embedded request as the body. Returns how many times /smuggled ran.
  21229. //
  21230. // The body is sent AFTER receiving the first response (as in the original
  21231. // PoC) so that the stream_line_reader cannot buffer it together with the
  21232. // headers of the first request.
  21233. static int count_smuggled_requests(const std::string &outer_head,
  21234. std::string &first_response) {
  21235. Server svr;
  21236. svr.set_mount_point("/", "./www");
  21237. std::atomic<int> smuggled_count(0);
  21238. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21239. smuggled_count++;
  21240. res.set_content("oops", "text/plain");
  21241. });
  21242. svr.Post("/post", [&](const Request &req, Response &res) {
  21243. res.set_content(req.body, "text/plain");
  21244. });
  21245. auto port = svr.bind_to_any_port("localhost");
  21246. thread t = thread([&] { svr.listen_after_bind(); });
  21247. auto se = detail::scope_exit([&] {
  21248. svr.stop();
  21249. t.join();
  21250. });
  21251. svr.wait_until_ready();
  21252. auto error = Error::Success;
  21253. auto sock = detail::create_client_socket(
  21254. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21255. /*connection_timeout_sec=*/2, 0,
  21256. /*read_timeout_sec=*/2, 0,
  21257. /*write_timeout_sec=*/2, 0, std::string(), error);
  21258. EXPECT_NE(INVALID_SOCKET, sock);
  21259. if (sock == INVALID_SOCKET) { return -1; }
  21260. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21261. // The "smuggled" request will be sent as the body of the outer request
  21262. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21263. "Host: localhost\r\n"
  21264. "Connection: close\r\n"
  21265. "\r\n";
  21266. auto head = outer_head;
  21267. auto len = std::to_string(smuggled.size());
  21268. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21269. pos = head.find("{len}", pos + len.size())) {
  21270. head.replace(pos, 5, len);
  21271. }
  21272. // Step 1: Send only the outer request headers (no body yet)
  21273. auto sent = send(sock, head.data(), head.size(), 0);
  21274. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21275. // Step 2: Read the first response
  21276. char buf[4096];
  21277. for (;;) {
  21278. auto n = recv(sock, buf, sizeof(buf), 0);
  21279. if (n <= 0) break;
  21280. first_response.append(buf, static_cast<size_t>(n));
  21281. // Stop once we have a complete response (headers + body)
  21282. auto hdr_end = first_response.find("\r\n\r\n");
  21283. if (hdr_end != std::string::npos) {
  21284. // Check for Content-Length to know when the body is complete
  21285. auto cl_pos = first_response.find("Content-Length:");
  21286. if (cl_pos != std::string::npos) {
  21287. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21288. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21289. auto cl = std::stoul(
  21290. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21291. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21292. } else {
  21293. break; // No Content-Length, assume headers-only response
  21294. }
  21295. }
  21296. }
  21297. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21298. // vulnerable server the keep-alive loop reads this as a second request. The
  21299. // server may already have closed the connection, so the result is ignored.
  21300. send(sock, smuggled.data(), smuggled.size(), 0);
  21301. // Half-close so that a server which drained the body sees EOF and closes,
  21302. // instead of the read below waiting for the read timeout.
  21303. #ifdef _WIN32
  21304. ::shutdown(sock, SD_SEND);
  21305. #else
  21306. ::shutdown(sock, SHUT_WR);
  21307. #endif
  21308. // Step 4: Read until the server closes the connection
  21309. for (;;) {
  21310. auto n = recv(sock, buf, sizeof(buf), 0);
  21311. if (n <= 0) break;
  21312. }
  21313. return smuggled_count.load();
  21314. }
  21315. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21316. // A GET request with Content-Length to a static file handler must have its
  21317. // body drained before the keep-alive connection is reused. Otherwise the
  21318. // unread body bytes are interpreted as the next HTTP request.
  21319. std::string first_response;
  21320. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21321. "Host: localhost\r\n"
  21322. "Content-Length: {len}\r\n"
  21323. "\r\n",
  21324. first_response));
  21325. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21326. }
  21327. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21328. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21329. // be answered with 400 and the connection closed. Treating it as "no body"
  21330. // leaves the body to be parsed as the next request.
  21331. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21332. const char *targets[] = {
  21333. "GET /file", // handler that never reads the body
  21334. "GET /not-found", // no handler matches (404)
  21335. "POST /post", // handler that reads the body
  21336. };
  21337. for (auto target : targets) {
  21338. for (auto value : values) {
  21339. std::string first_response;
  21340. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21341. " HTTP/1.1\r\n"
  21342. "Host: localhost\r\n"
  21343. "Content-Length: " +
  21344. value + "\r\n\r\n",
  21345. first_response))
  21346. << target << " with Content-Length: " << value;
  21347. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21348. << target << " with Content-Length: " << value;
  21349. }
  21350. }
  21351. }
  21352. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21353. // A 400 for an unparseable request line leaves the rest of the message
  21354. // unread, so the connection must be closed rather than reused.
  21355. std::string first_response;
  21356. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21357. "Host: localhost\r\n"
  21358. "Content-Length: {len}\r\n"
  21359. "\r\n",
  21360. first_response));
  21361. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21362. }
  21363. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21364. // Same as above for a header block that fails to parse.
  21365. std::string first_response;
  21366. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21367. "Host: localhost\r\n"
  21368. "Bad Header\r\n"
  21369. "Content-Length: {len}\r\n"
  21370. "\r\n",
  21371. first_response));
  21372. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21373. }
  21374. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21375. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21376. // server must not read another request on that connection, even when the
  21377. // request had no body to drain.
  21378. std::string first_response;
  21379. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21380. "Host: localhost\r\n"
  21381. "\r\n",
  21382. first_response));
  21383. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21384. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21385. }
  21386. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21387. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21388. // must be rejected with 400 Bad Request.
  21389. Server svr;
  21390. svr.Post("/test", [&](const Request &, Response &res) {
  21391. res.set_content("ok", "text/plain");
  21392. });
  21393. thread t = thread([&] { svr.listen(HOST, PORT); });
  21394. auto se = detail::scope_exit([&] {
  21395. svr.stop();
  21396. t.join();
  21397. ASSERT_FALSE(svr.is_running());
  21398. });
  21399. svr.wait_until_ready();
  21400. // Exact "chunked"
  21401. {
  21402. auto req = "POST /test HTTP/1.1\r\n"
  21403. "Host: localhost\r\n"
  21404. "Content-Length: 5\r\n"
  21405. "Transfer-Encoding: chunked\r\n"
  21406. "Connection: close\r\n"
  21407. "\r\n"
  21408. "hello";
  21409. std::string response;
  21410. ASSERT_TRUE(send_request(1, req, &response));
  21411. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21412. response.substr(0, response.find("\r\n")));
  21413. }
  21414. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21415. {
  21416. auto req = "POST /test HTTP/1.1\r\n"
  21417. "Host: localhost\r\n"
  21418. "Content-Length: 5\r\n"
  21419. "Transfer-Encoding: gzip, chunked\r\n"
  21420. "Connection: close\r\n"
  21421. "\r\n"
  21422. "hello";
  21423. std::string response;
  21424. ASSERT_TRUE(send_request(1, req, &response));
  21425. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21426. response.substr(0, response.find("\r\n")));
  21427. }
  21428. }
  21429. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21430. Server svr;
  21431. svr.Post("/test", [&](const Request &, Response &res) {
  21432. res.set_content("ok", "text/plain");
  21433. });
  21434. thread t = thread([&] { svr.listen(HOST, PORT); });
  21435. auto se = detail::scope_exit([&] {
  21436. svr.stop();
  21437. t.join();
  21438. ASSERT_FALSE(svr.is_running());
  21439. });
  21440. svr.wait_until_ready();
  21441. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21442. // length cannot be determined, so the server must answer 400 and close
  21443. // rather than treat the request as bodyless and leave the body in the
  21444. // socket for the next request to pick up.
  21445. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21446. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21447. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21448. std::string response;
  21449. ASSERT_TRUE(send_request(1, req, &response));
  21450. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21451. response.substr(0, response.find("\r\n")))
  21452. << transfer_encoding;
  21453. }
  21454. // RFC 9110 5.3: the codings may also be split across several
  21455. // Transfer-Encoding lines, which combine in the order they were received.
  21456. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21457. // just like the single-line "chunked, gzip" above.
  21458. {
  21459. auto req = "POST /test HTTP/1.1\r\n"
  21460. "Host: localhost\r\n"
  21461. "Transfer-Encoding: chunked\r\n"
  21462. "Transfer-Encoding: gzip\r\n"
  21463. "\r\n"
  21464. "0\r\n\r\n";
  21465. std::string response;
  21466. ASSERT_TRUE(send_request(1, req, &response));
  21467. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21468. response.substr(0, response.find("\r\n")));
  21469. }
  21470. // A sequence ending in chunked stays valid.
  21471. auto req = "POST /test HTTP/1.1\r\n"
  21472. "Host: localhost\r\n"
  21473. "Transfer-Encoding: gzip, chunked\r\n"
  21474. "Connection: close\r\n"
  21475. "\r\n"
  21476. "0\r\n\r\n";
  21477. std::string response;
  21478. ASSERT_TRUE(send_request(1, req, &response));
  21479. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21480. // ...including when it is spread over several lines.
  21481. auto split_req = "POST /test HTTP/1.1\r\n"
  21482. "Host: localhost\r\n"
  21483. "Transfer-Encoding: gzip\r\n"
  21484. "Transfer-Encoding: chunked\r\n"
  21485. "Connection: close\r\n"
  21486. "\r\n"
  21487. "0\r\n\r\n";
  21488. std::string split_response;
  21489. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21490. EXPECT_EQ("HTTP/1.1 200 OK",
  21491. split_response.substr(0, split_response.find("\r\n")));
  21492. }
  21493. // Regression for issue #2450: a DELETE without Content-Length on a
  21494. // keep-alive connection must not let the post-response drain consume the
  21495. // next request's bytes.
  21496. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21497. Server svr;
  21498. std::atomic<int> delete_count(0);
  21499. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21500. delete_count++;
  21501. res.status = StatusCode::NoContent_204;
  21502. });
  21503. auto port = svr.bind_to_any_port(HOST);
  21504. thread t = thread([&] { svr.listen_after_bind(); });
  21505. auto se = detail::scope_exit([&] {
  21506. svr.stop();
  21507. t.join();
  21508. });
  21509. svr.wait_until_ready();
  21510. auto error = Error::Success;
  21511. auto sock = detail::create_client_socket(
  21512. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21513. /*connection_timeout_sec=*/2, 0,
  21514. /*read_timeout_sec=*/2, 0,
  21515. /*write_timeout_sec=*/2, 0, std::string(), error);
  21516. ASSERT_NE(INVALID_SOCKET, sock);
  21517. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21518. auto send_request_and_read_response = [&](const std::string &req,
  21519. std::string &out) -> bool {
  21520. auto sent = send(sock, req.data(), req.size(), 0);
  21521. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21522. char buf[4096];
  21523. for (;;) {
  21524. auto n = recv(sock, buf, sizeof(buf), 0);
  21525. if (n <= 0) { return !out.empty(); }
  21526. out.append(buf, static_cast<size_t>(n));
  21527. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21528. }
  21529. };
  21530. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21531. "Host: localhost\r\n"
  21532. "\r\n";
  21533. std::string resp1;
  21534. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21535. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21536. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21537. "Host: localhost\r\n"
  21538. "Connection: close\r\n"
  21539. "\r\n";
  21540. std::string resp2;
  21541. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21542. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21543. EXPECT_EQ(2, delete_count.load());
  21544. }
  21545. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21546. Server svr;
  21547. svr.Post("/ingest", [&](const Request &, Response &res,
  21548. const ContentReader &content_reader) {
  21549. auto consumed = content_reader([](const char *, size_t) { return false; });
  21550. EXPECT_FALSE(consumed);
  21551. res.status = StatusCode::Conflict_409;
  21552. res.set_header("Connection", "close");
  21553. });
  21554. auto port = svr.bind_to_any_port(HOST);
  21555. thread t = thread([&] { svr.listen_after_bind(); });
  21556. auto se = detail::scope_exit([&] {
  21557. svr.stop();
  21558. t.join();
  21559. });
  21560. svr.wait_until_ready();
  21561. auto error = Error::Success;
  21562. auto sock = detail::create_client_socket(
  21563. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21564. /*connection_timeout_sec=*/2, 0,
  21565. /*read_timeout_sec=*/1, 0,
  21566. /*write_timeout_sec=*/2, 0, std::string(), error);
  21567. ASSERT_NE(INVALID_SOCKET, sock);
  21568. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21569. std::string request = "POST /ingest HTTP/1.1\r\n"
  21570. "Host: localhost\r\n"
  21571. "Transfer-Encoding: chunked\r\n"
  21572. "\r\n"
  21573. "4\r\n"
  21574. "data\r\n";
  21575. auto sent = send(sock, request.data(), request.size(), 0);
  21576. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21577. std::string response;
  21578. ssize_t received = 0;
  21579. do {
  21580. char buf[4096];
  21581. received = recv(sock, buf, sizeof(buf), 0);
  21582. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21583. } while (received > 0);
  21584. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21585. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21586. EXPECT_EQ(0, received);
  21587. }
  21588. namespace no_proxy_test {
  21589. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21590. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21591. // calling listen().
  21592. class ScopedServer {
  21593. public:
  21594. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21595. ~ScopedServer() {
  21596. svr_.stop();
  21597. if (th_.joinable()) { th_.join(); }
  21598. }
  21599. Server &svr() { return svr_; }
  21600. int port() const { return port_; }
  21601. void listen() {
  21602. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21603. svr_.wait_until_ready();
  21604. }
  21605. private:
  21606. Server svr_;
  21607. std::thread th_;
  21608. int port_ = 0;
  21609. };
  21610. class ProxyAndTargetServers {
  21611. public:
  21612. ProxyAndTargetServers() {
  21613. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21614. proxy_hits_++;
  21615. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21616. res.set_content("via-proxy", "text/plain");
  21617. });
  21618. target_.Get(".*", [this](const Request &req, Response &res) {
  21619. target_hits_++;
  21620. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21621. res.set_content("direct", "text/plain");
  21622. });
  21623. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21624. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21625. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21626. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21627. proxy_mock_.wait_until_ready();
  21628. target_.wait_until_ready();
  21629. }
  21630. ~ProxyAndTargetServers() {
  21631. proxy_mock_.stop();
  21632. target_.stop();
  21633. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21634. if (target_thread_.joinable()) { target_thread_.join(); }
  21635. }
  21636. Server &proxy_mock() { return proxy_mock_; }
  21637. Server &target() { return target_; }
  21638. int proxy_port() const { return proxy_port_; }
  21639. int target_port() const { return target_port_; }
  21640. int proxy_hits() const { return proxy_hits_.load(); }
  21641. int target_hits() const { return target_hits_.load(); }
  21642. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21643. void reset_counters() {
  21644. proxy_hits_ = 0;
  21645. target_hits_ = 0;
  21646. last_had_proxy_authz_ = false;
  21647. }
  21648. private:
  21649. Server proxy_mock_;
  21650. Server target_;
  21651. std::thread proxy_thread_;
  21652. std::thread target_thread_;
  21653. int proxy_port_ = 0;
  21654. int target_port_ = 0;
  21655. std::atomic<int> proxy_hits_{0};
  21656. std::atomic<int> target_hits_{0};
  21657. std::atomic<bool> last_had_proxy_authz_{false};
  21658. };
  21659. inline std::unique_ptr<Client> make_client(const std::string &host,
  21660. ProxyAndTargetServers &s) {
  21661. auto cli = detail::make_unique<Client>(host, s.target_port());
  21662. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21663. cli->set_proxy("127.0.0.1", s.proxy_port());
  21664. return cli;
  21665. }
  21666. } // namespace no_proxy_test
  21667. using no_proxy_test::make_client;
  21668. using no_proxy_test::ProxyAndTargetServers;
  21669. TEST(NoProxyTest, ExactHostnameBypasses) {
  21670. ProxyAndTargetServers s;
  21671. auto cli = make_client("example.com", s);
  21672. cli->set_no_proxy({"example.com"});
  21673. auto res = cli->Get("/");
  21674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21675. EXPECT_EQ(0, s.proxy_hits());
  21676. EXPECT_EQ(1, s.target_hits());
  21677. }
  21678. TEST(NoProxyTest, SubdomainBypasses) {
  21679. ProxyAndTargetServers s;
  21680. auto cli = make_client("foo.example.com", s);
  21681. cli->set_no_proxy({"example.com"});
  21682. auto res = cli->Get("/");
  21683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21684. EXPECT_EQ(0, s.proxy_hits());
  21685. EXPECT_EQ(1, s.target_hits());
  21686. }
  21687. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21688. // Regression guard: "evilexample.com" must not be considered a subdomain
  21689. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21690. // check would let traffic bypass the proxy and leak credentials direct
  21691. // to the attacker host.
  21692. ProxyAndTargetServers s;
  21693. auto cli = make_client("evilexample.com", s);
  21694. cli->set_no_proxy({"example.com"});
  21695. auto res = cli->Get("/");
  21696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21697. EXPECT_GE(s.proxy_hits(), 1);
  21698. EXPECT_EQ(0, s.target_hits());
  21699. }
  21700. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21701. ProxyAndTargetServers s;
  21702. auto cli = make_client("example.com.evil.com", s);
  21703. cli->set_no_proxy({"example.com"});
  21704. auto res = cli->Get("/");
  21705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21706. EXPECT_GE(s.proxy_hits(), 1);
  21707. EXPECT_EQ(0, s.target_hits());
  21708. }
  21709. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21710. ProxyAndTargetServers s;
  21711. auto cli = make_client("example.com", s);
  21712. cli->set_no_proxy({".example.com"});
  21713. auto res = cli->Get("/");
  21714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21715. EXPECT_EQ(0, s.proxy_hits());
  21716. EXPECT_EQ(1, s.target_hits());
  21717. }
  21718. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21719. ProxyAndTargetServers s;
  21720. auto cli = make_client("Example.COM", s);
  21721. cli->set_no_proxy({"EXAMPLE.com"});
  21722. auto res = cli->Get("/");
  21723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21724. EXPECT_EQ(0, s.proxy_hits());
  21725. EXPECT_EQ(1, s.target_hits());
  21726. }
  21727. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21728. ProxyAndTargetServers s;
  21729. auto cli = make_client("example.com.", s);
  21730. cli->set_no_proxy({"example.com"});
  21731. auto res = cli->Get("/");
  21732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21733. EXPECT_EQ(0, s.proxy_hits());
  21734. EXPECT_EQ(1, s.target_hits());
  21735. }
  21736. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21737. // Trailing dots must be normalized on BOTH sides — host and entry.
  21738. // An implementation that only strips the host-side trailing dot would
  21739. // fail to match host "example.com" against entry "example.com." because
  21740. // a literal substring search would compare 11 chars against 12.
  21741. ProxyAndTargetServers s;
  21742. auto cli = make_client("example.com", s);
  21743. cli->set_no_proxy({"example.com."});
  21744. auto res = cli->Get("/");
  21745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21746. EXPECT_EQ(0, s.proxy_hits());
  21747. EXPECT_EQ(1, s.target_hits());
  21748. }
  21749. TEST(NoProxyTest, WildcardBypassesEverything) {
  21750. ProxyAndTargetServers s;
  21751. auto cli = make_client("anything.invalid.test", s);
  21752. cli->set_no_proxy({"*"});
  21753. auto res = cli->Get("/");
  21754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21755. EXPECT_EQ(0, s.proxy_hits());
  21756. EXPECT_EQ(1, s.target_hits());
  21757. }
  21758. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21759. ProxyAndTargetServers s;
  21760. Client cli("127.0.0.1", s.target_port());
  21761. cli.set_proxy("127.0.0.1", s.proxy_port());
  21762. cli.set_no_proxy({"127.0.0.1"});
  21763. auto res = cli.Get("/");
  21764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21765. EXPECT_EQ(0, s.proxy_hits());
  21766. EXPECT_EQ(1, s.target_hits());
  21767. }
  21768. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21769. ProxyAndTargetServers s;
  21770. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21771. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21772. cli.set_proxy("127.0.0.1", s.proxy_port());
  21773. cli.set_no_proxy({"::1"});
  21774. auto res = cli.Get("/");
  21775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21776. EXPECT_EQ(0, s.proxy_hits());
  21777. EXPECT_EQ(1, s.target_hits());
  21778. }
  21779. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21780. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21781. // must still be recognized as IPv6 for CIDR matching. Implementations
  21782. // that detect IPv6 only when the host begins with '[' would parse the
  21783. // host as a hostname and miss the match.
  21784. ProxyAndTargetServers s;
  21785. Client cli("fe80::1", s.target_port());
  21786. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21787. cli.set_proxy("127.0.0.1", s.proxy_port());
  21788. cli.set_no_proxy({"fe80::/10"});
  21789. auto res = cli.Get("/");
  21790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21791. EXPECT_EQ(0, s.proxy_hits());
  21792. EXPECT_EQ(1, s.target_hits());
  21793. }
  21794. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21795. ProxyAndTargetServers s;
  21796. Client cli("::1", s.target_port());
  21797. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21798. cli.set_proxy("127.0.0.1", s.proxy_port());
  21799. cli.set_no_proxy({"[::1]"});
  21800. auto res = cli.Get("/");
  21801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21802. EXPECT_EQ(0, s.proxy_hits());
  21803. EXPECT_EQ(1, s.target_hits());
  21804. }
  21805. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21806. ProxyAndTargetServers s;
  21807. Client cli("fe80::1", s.target_port());
  21808. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21809. cli.set_proxy("127.0.0.1", s.proxy_port());
  21810. cli.set_no_proxy({"[fe80::]/10"});
  21811. auto res = cli.Get("/");
  21812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21813. EXPECT_EQ(0, s.proxy_hits());
  21814. EXPECT_EQ(1, s.target_hits());
  21815. }
  21816. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21817. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21818. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21819. // tricks via address-family conversion.
  21820. ProxyAndTargetServers s;
  21821. Client cli("::ffff:127.0.0.1", s.target_port());
  21822. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21823. cli.set_proxy("127.0.0.1", s.proxy_port());
  21824. cli.set_no_proxy({"127.0.0.1"});
  21825. auto res = cli.Get("/");
  21826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21827. EXPECT_GE(s.proxy_hits(), 1);
  21828. EXPECT_EQ(0, s.target_hits());
  21829. }
  21830. TEST(NoProxyTest, IPv4CidrMatch) {
  21831. ProxyAndTargetServers s;
  21832. Client cli("127.0.0.1", s.target_port());
  21833. cli.set_proxy("127.0.0.1", s.proxy_port());
  21834. cli.set_no_proxy({"127.0.0.0/8"});
  21835. auto res = cli.Get("/");
  21836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21837. EXPECT_EQ(0, s.proxy_hits());
  21838. EXPECT_EQ(1, s.target_hits());
  21839. }
  21840. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21841. ProxyAndTargetServers s;
  21842. Client cli("127.0.0.1", s.target_port());
  21843. cli.set_proxy("127.0.0.1", s.proxy_port());
  21844. cli.set_no_proxy({"10.0.0.0/8"});
  21845. auto res = cli.Get("/");
  21846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21847. EXPECT_GE(s.proxy_hits(), 1);
  21848. EXPECT_EQ(0, s.target_hits());
  21849. }
  21850. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21851. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21852. // IPv4 target matches.
  21853. ProxyAndTargetServers s;
  21854. Client cli("127.0.0.1", s.target_port());
  21855. cli.set_proxy("127.0.0.1", s.proxy_port());
  21856. cli.set_no_proxy({"0.0.0.0/0"});
  21857. auto res = cli.Get("/");
  21858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21859. EXPECT_EQ(0, s.proxy_hits());
  21860. EXPECT_EQ(1, s.target_hits());
  21861. }
  21862. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21863. ProxyAndTargetServers s;
  21864. Client cli("127.0.0.1", s.target_port());
  21865. cli.set_proxy("127.0.0.1", s.proxy_port());
  21866. cli.set_no_proxy({"127.0.0.1"});
  21867. auto res = cli.Get("/");
  21868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21869. EXPECT_EQ(0, s.proxy_hits());
  21870. EXPECT_EQ(1, s.target_hits());
  21871. }
  21872. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21873. ProxyAndTargetServers s;
  21874. Client cli("127.0.0.1", s.target_port());
  21875. cli.set_proxy("127.0.0.1", s.proxy_port());
  21876. cli.set_no_proxy({"127.0.0.0/33"});
  21877. auto res = cli.Get("/");
  21878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21879. EXPECT_GE(s.proxy_hits(), 1);
  21880. EXPECT_EQ(0, s.target_hits());
  21881. }
  21882. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21883. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21884. ProxyAndTargetServers s;
  21885. Client cli("127.0.0.1", s.target_port());
  21886. cli.set_proxy("127.0.0.1", s.proxy_port());
  21887. cli.set_no_proxy({"127.0.0.1/"});
  21888. auto res = cli.Get("/");
  21889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21890. EXPECT_GE(s.proxy_hits(), 1);
  21891. EXPECT_EQ(0, s.target_hits());
  21892. }
  21893. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21894. ProxyAndTargetServers s;
  21895. auto cli = make_client("internal.corp", s);
  21896. cli->set_proxy_basic_auth("u", "p");
  21897. cli->set_no_proxy({"internal.corp"});
  21898. auto res = cli->Get("/");
  21899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21900. EXPECT_EQ(1, s.target_hits());
  21901. EXPECT_EQ(0, s.proxy_hits());
  21902. EXPECT_FALSE(s.last_had_proxy_authz())
  21903. << "Proxy-Authorization must not be sent direct to the target";
  21904. }
  21905. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21906. ProxyAndTargetServers s;
  21907. auto cli = make_client("public.example", s);
  21908. cli->set_proxy_basic_auth("u", "p");
  21909. cli->set_no_proxy({"internal.corp"}); // does not match
  21910. auto res = cli->Get("/");
  21911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21912. EXPECT_GE(s.proxy_hits(), 1);
  21913. EXPECT_TRUE(s.last_had_proxy_authz());
  21914. }
  21915. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21916. ProxyAndTargetServers s;
  21917. auto cli = make_client("anything.test", s);
  21918. auto res = cli->Get("/");
  21919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21920. EXPECT_GE(s.proxy_hits(), 1);
  21921. EXPECT_EQ(0, s.target_hits());
  21922. }
  21923. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21924. ProxyAndTargetServers s;
  21925. auto cli = make_client("example.com", s);
  21926. cli->set_no_proxy({"example.com:8080"});
  21927. auto res = cli->Get("/");
  21928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21929. EXPECT_GE(s.proxy_hits(), 1);
  21930. EXPECT_EQ(0, s.target_hits());
  21931. }
  21932. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21933. ProxyAndTargetServers s;
  21934. auto cli = make_client("anything.test", s);
  21935. cli->set_no_proxy({"", " ", "\t"});
  21936. auto res = cli->Get("/");
  21937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21938. EXPECT_GE(s.proxy_hits(), 1);
  21939. EXPECT_EQ(0, s.target_hits());
  21940. }
  21941. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21942. // An entry with leading/trailing whitespace must still match — env-style
  21943. // values are commonly pasted with stray spaces and an implementation
  21944. // that feeds the raw token directly to inet_pton would fail to match
  21945. // valid CIDRs because of the spaces.
  21946. ProxyAndTargetServers s;
  21947. Client cli("127.0.0.1", s.target_port());
  21948. cli.set_proxy("127.0.0.1", s.proxy_port());
  21949. cli.set_no_proxy({" 127.0.0.0/8 "});
  21950. auto res = cli.Get("/");
  21951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21952. EXPECT_EQ(0, s.proxy_hits());
  21953. EXPECT_EQ(1, s.target_hits());
  21954. }
  21955. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21956. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21957. // go direct and must NOT carry Proxy-Authorization.
  21958. std::atomic<int> proxy_hits{0};
  21959. std::atomic<int> target_hits{0};
  21960. std::atomic<bool> target_saw_authz{false};
  21961. no_proxy_test::ScopedServer proxy_mock, target;
  21962. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21963. proxy_hits++;
  21964. res.status = 302;
  21965. res.set_header("Location", "http://127.0.0.1:" +
  21966. std::to_string(target.port()) + "/landed");
  21967. });
  21968. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21969. target_hits++;
  21970. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21971. res.set_content("direct", "text/plain");
  21972. });
  21973. proxy_mock.listen();
  21974. target.listen();
  21975. Client cli("public.example", target.port());
  21976. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21977. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21978. cli.set_proxy_basic_auth("u", "p");
  21979. cli.set_no_proxy({"127.0.0.1"});
  21980. cli.set_follow_location(true);
  21981. auto res = cli.Get("/redir");
  21982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21983. EXPECT_GE(proxy_hits.load(), 1);
  21984. EXPECT_GE(target_hits.load(), 1);
  21985. EXPECT_FALSE(target_saw_authz.load());
  21986. }
  21987. #ifdef CPPHTTPLIB_SSL_ENABLED
  21988. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21989. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21990. // proxy creds would be sent to the (possibly hostile) origin.
  21991. std::atomic<int> target_hits{0};
  21992. std::atomic<bool> target_saw_proxy_authz{false};
  21993. no_proxy_test::ScopedServer target;
  21994. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21995. target_hits++;
  21996. if (req.has_header("Proxy-Authorization")) {
  21997. target_saw_proxy_authz = true;
  21998. }
  21999. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22000. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22001. "nonce=\"abc\", algorithm=MD5");
  22002. });
  22003. target.listen();
  22004. // The proxy address is set to the target's port: the bypass MUST kick in;
  22005. // if it doesn't, the test still routes "via proxy" to the same server and
  22006. // the Proxy-Authorization assertion below catches the leak.
  22007. Client cli("evil.example", target.port());
  22008. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22009. cli.set_proxy("127.0.0.1", target.port());
  22010. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22011. cli.set_no_proxy({"evil.example"});
  22012. auto res = cli.Get("/x");
  22013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22014. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22015. EXPECT_EQ(1, target_hits.load());
  22016. EXPECT_FALSE(target_saw_proxy_authz.load());
  22017. }
  22018. #endif
  22019. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22020. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22021. std::atomic<int> proxy_hits{0};
  22022. std::atomic<int> bypass_hits{0};
  22023. std::atomic<bool> proxy_saw_c_url{false};
  22024. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22025. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22026. proxy_hits++;
  22027. if (req.path.find("/start") != std::string::npos) {
  22028. res.status = 302;
  22029. res.set_header("Location", "http://127.0.0.1:" +
  22030. std::to_string(bypass_server.port()) +
  22031. "/middle");
  22032. return;
  22033. }
  22034. if (req.path.find("/end") != std::string::npos) {
  22035. proxy_saw_c_url = true;
  22036. res.set_content("c-via-proxy", "text/plain");
  22037. return;
  22038. }
  22039. res.set_content("unexpected", "text/plain");
  22040. });
  22041. // public.example's "advertised" port is arbitrary (the request never lands
  22042. // there — it goes through the proxy), but use a dynamic value to stay
  22043. // friendly with sharded parallel runs.
  22044. int public_port = bypass_server.port();
  22045. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22046. bypass_hits++;
  22047. res.status = 302;
  22048. res.set_header("Location", "http://public.example:" +
  22049. std::to_string(public_port) + "/end");
  22050. });
  22051. proxy_mock.listen();
  22052. bypass_server.listen();
  22053. Client cli("public.example", public_port);
  22054. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22055. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22056. cli.set_no_proxy({"127.0.0.1"});
  22057. cli.set_follow_location(true);
  22058. auto res = cli.Get("/start");
  22059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22060. EXPECT_EQ(StatusCode::OK_200, res->status);
  22061. EXPECT_EQ("c-via-proxy", res->body);
  22062. EXPECT_GE(proxy_hits.load(), 2);
  22063. EXPECT_GE(bypass_hits.load(), 1);
  22064. EXPECT_TRUE(proxy_saw_c_url.load());
  22065. }
  22066. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22067. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22068. // request reconnects to the correct endpoint.
  22069. std::atomic<int> proxy_hits{0};
  22070. std::atomic<int> target_hits{0};
  22071. no_proxy_test::ScopedServer proxy_mock, target;
  22072. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22073. proxy_hits++;
  22074. res.set_content("via-proxy", "text/plain");
  22075. });
  22076. target.svr().Get(".*", [&](const Request &, Response &res) {
  22077. target_hits++;
  22078. res.set_content("direct", "text/plain");
  22079. });
  22080. proxy_mock.listen();
  22081. target.listen();
  22082. Client cli("public.example", target.port());
  22083. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22084. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22085. cli.set_keep_alive(true);
  22086. auto res1 = cli.Get("/a");
  22087. ASSERT_TRUE(res1);
  22088. EXPECT_EQ("via-proxy", res1->body);
  22089. EXPECT_EQ(1, proxy_hits.load());
  22090. EXPECT_EQ(0, target_hits.load());
  22091. cli.set_no_proxy({"public.example"});
  22092. auto res2 = cli.Get("/b");
  22093. ASSERT_TRUE(res2);
  22094. EXPECT_EQ("direct", res2->body);
  22095. EXPECT_EQ(1, proxy_hits.load());
  22096. EXPECT_EQ(1, target_hits.load());
  22097. }
  22098. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22099. namespace proxy_tunnel_test {
  22100. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22101. class ScopedSSLServer {
  22102. public:
  22103. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22104. port_ = svr_.bind_to_any_port("127.0.0.1");
  22105. }
  22106. ~ScopedSSLServer() {
  22107. svr_.stop();
  22108. if (th_.joinable()) { th_.join(); }
  22109. }
  22110. SSLServer &svr() { return svr_; }
  22111. int port() const { return port_; }
  22112. void listen() {
  22113. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22114. svr_.wait_until_ready();
  22115. }
  22116. private:
  22117. SSLServer svr_;
  22118. std::thread th_;
  22119. int port_ = 0;
  22120. };
  22121. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22122. class ScopedConnectProxy {
  22123. public:
  22124. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22125. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22126. if (listen_fd_ < 0) { return; }
  22127. int yes = 1;
  22128. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22129. sockaddr_in a{};
  22130. a.sin_family = AF_INET;
  22131. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22132. a.sin_port = 0;
  22133. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22134. return;
  22135. }
  22136. socklen_t alen = sizeof(a);
  22137. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22138. 0) {
  22139. return;
  22140. }
  22141. port_ = ntohs(a.sin_port);
  22142. if (::listen(listen_fd_, 1) != 0) { return; }
  22143. th_ = std::thread([this] { run(); });
  22144. }
  22145. ~ScopedConnectProxy() {
  22146. stop_ = true;
  22147. if (listen_fd_ >= 0) {
  22148. ::shutdown(listen_fd_, SHUT_RDWR);
  22149. ::close(listen_fd_);
  22150. }
  22151. if (th_.joinable()) { th_.join(); }
  22152. }
  22153. int port() const { return port_; }
  22154. int connect_hits() const { return connect_hits_.load(); }
  22155. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22156. std::string connect_request() const {
  22157. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22158. return connect_request_;
  22159. }
  22160. private:
  22161. void run() {
  22162. while (!stop_.load()) {
  22163. fd_set rfds;
  22164. FD_ZERO(&rfds);
  22165. FD_SET(listen_fd_, &rfds);
  22166. timeval tv{0, 100 * 1000};
  22167. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22168. if (sel <= 0) { continue; }
  22169. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22170. if (client_fd < 0) { continue; }
  22171. std::string req;
  22172. char buf[2048];
  22173. while (req.find("\r\n\r\n") == std::string::npos) {
  22174. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22175. if (n <= 0) { break; }
  22176. req.append(buf, static_cast<size_t>(n));
  22177. }
  22178. if (req.compare(0, 7, "CONNECT") != 0) {
  22179. ::close(client_fd);
  22180. continue;
  22181. }
  22182. connect_hits_++;
  22183. {
  22184. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22185. connect_request_ = req;
  22186. }
  22187. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22188. ::send(client_fd, ok, std::strlen(ok), 0);
  22189. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22190. sockaddr_in o{};
  22191. o.sin_family = AF_INET;
  22192. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22193. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22194. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22195. 0) {
  22196. ::close(client_fd);
  22197. ::close(origin_fd);
  22198. continue;
  22199. }
  22200. auto forward = [](int from, int to) {
  22201. char b[8192];
  22202. for (;;) {
  22203. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22204. if (n <= 0) { break; }
  22205. ssize_t off = 0;
  22206. while (off < n) {
  22207. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22208. if (s <= 0) {
  22209. off = n;
  22210. break;
  22211. }
  22212. off += s;
  22213. }
  22214. }
  22215. ::shutdown(to, SHUT_WR);
  22216. };
  22217. std::thread t1([&] { forward(client_fd, origin_fd); });
  22218. std::thread t2([&] { forward(origin_fd, client_fd); });
  22219. t1.join();
  22220. t2.join();
  22221. ::close(client_fd);
  22222. ::close(origin_fd);
  22223. }
  22224. }
  22225. int forward_port_ = -1;
  22226. int listen_fd_ = -1;
  22227. int port_ = 0;
  22228. std::thread th_;
  22229. std::atomic<bool> stop_{false};
  22230. std::atomic<int> connect_hits_{0};
  22231. mutable std::mutex connect_request_mutex_;
  22232. std::string connect_request_;
  22233. };
  22234. // Sends one request through the CONNECT proxy to the TLS origin with a
  22235. // credential configured for each hop, and checks that each credential reaches
  22236. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22237. // origin's (every header in origin_headers) on the tunnelled request.
  22238. void CredentialsStayWithTheirHop(
  22239. const std::function<void(SSLClient &)> &set_credentials,
  22240. const std::string &scheme,
  22241. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22242. std::atomic<int> origin_hits{0};
  22243. std::atomic<bool> origin_saw_proxy_authz{false};
  22244. std::atomic<bool> origin_saw_headers{false};
  22245. ScopedSSLServer origin;
  22246. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22247. origin_hits++;
  22248. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22249. origin_saw_headers =
  22250. std::all_of(origin_headers.begin(), origin_headers.end(),
  22251. [&](const std::string &h) { return req.has_header(h); });
  22252. res.set_content("ok", "text/plain");
  22253. });
  22254. origin.listen();
  22255. ScopedConnectProxy proxy(origin.port());
  22256. ASSERT_NE(0, proxy.port());
  22257. // Pinned to 127.0.0.1 for the same reason as the test below.
  22258. SSLClient cli("127.0.0.1", origin.port());
  22259. cli.enable_server_certificate_verification(false);
  22260. cli.set_proxy("127.0.0.1", proxy.port());
  22261. set_credentials(cli);
  22262. auto res = cli.Get("/x");
  22263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22264. EXPECT_EQ(StatusCode::OK_200, res->status);
  22265. EXPECT_EQ(1, origin_hits.load());
  22266. EXPECT_EQ(1, proxy.connect_hits());
  22267. EXPECT_TRUE(origin_saw_headers.load());
  22268. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22269. << "Proxy-Authorization must not be sent inside the tunnel";
  22270. auto connect_req = proxy.connect_request();
  22271. EXPECT_NE(std::string::npos,
  22272. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22273. for (const auto &h : origin_headers) {
  22274. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22275. << h << " must not be sent to the proxy on CONNECT";
  22276. }
  22277. }
  22278. } // namespace proxy_tunnel_test
  22279. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22280. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22281. [](SSLClient &cli) {
  22282. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22283. cli.set_basic_auth("origin-user", "origin-pass");
  22284. },
  22285. "Basic");
  22286. }
  22287. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22288. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22289. [](SSLClient &cli) {
  22290. cli.set_proxy_bearer_token_auth("proxy-token");
  22291. cli.set_bearer_token_auth("origin-token");
  22292. },
  22293. "Bearer");
  22294. }
  22295. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22296. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22297. [](SSLClient &cli) {
  22298. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22299. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22300. {"Cookie", "sid=origin-session"},
  22301. {"X-Api-Key", "origin-key"}});
  22302. },
  22303. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22304. }
  22305. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22306. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22307. // retry; otherwise proxy creds would be sent to the origin.
  22308. std::atomic<int> origin_hits{0};
  22309. std::atomic<bool> origin_saw_proxy_authz{false};
  22310. proxy_tunnel_test::ScopedSSLServer origin;
  22311. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22312. origin_hits++;
  22313. if (req.has_header("Proxy-Authorization")) {
  22314. origin_saw_proxy_authz = true;
  22315. }
  22316. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22317. res.set_header("Proxy-Authenticate",
  22318. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22319. "algorithm=MD5");
  22320. });
  22321. origin.listen();
  22322. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22323. ASSERT_NE(0, proxy.port());
  22324. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22325. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22326. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22327. // and answer with its own status, making this test flaky.
  22328. SSLClient cli("127.0.0.1", origin.port());
  22329. cli.enable_server_certificate_verification(false);
  22330. cli.set_proxy("127.0.0.1", proxy.port());
  22331. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22332. auto res = cli.Get("/x");
  22333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22334. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22335. EXPECT_EQ(1, origin_hits.load());
  22336. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22337. EXPECT_EQ(1, proxy.connect_hits());
  22338. }
  22339. #endif