1
0

test.cc 1022 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457
  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_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(RangeTest, IgnoredForPost) {
  2318. Server svr;
  2319. svr.Post("/", [](const Request &, Response &res) {
  2320. res.set_content("abcdefg", "text/plain");
  2321. });
  2322. auto port = svr.bind_to_any_port(HOST);
  2323. ASSERT_GT(port, 0);
  2324. thread t = thread([&] { svr.listen_after_bind(); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. t.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. Client cli(HOST, port);
  2332. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2333. auto res = cli.Post("/", Headers{{"Range", range}});
  2334. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2336. EXPECT_EQ("abcdefg", res->body) << range;
  2337. }
  2338. }
  2339. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2340. auto host = "unresolvableaddress.local";
  2341. auto path = std::string{"/"};
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(1);
  2350. {
  2351. auto res = cli.Get(path);
  2352. ASSERT_FALSE(res);
  2353. }
  2354. std::this_thread::sleep_for(std::chrono::seconds(8));
  2355. }
  2356. #if defined(__linux__) && defined(__GLIBC__) && \
  2357. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2358. // Forward declaration: in split builds split.py strips `inline` and moves the
  2359. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2360. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2361. // against the symbol in both header-only and split builds.
  2362. namespace httplib {
  2363. namespace detail {
  2364. int getaddrinfo_with_timeout(const char *node, const char *service,
  2365. const struct addrinfo *hints,
  2366. struct addrinfo **res, time_t timeout_sec);
  2367. } // namespace detail
  2368. } // namespace httplib
  2369. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2370. //
  2371. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2372. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2373. // gai_suspend() call hits the connection timeout the function calls
  2374. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2375. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2376. // still alive and still references the now-destroyed stack frame.
  2377. //
  2378. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2379. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2380. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2381. // and runs them in a container.
  2382. namespace {
  2383. bool should_run_issue_2431_tests() {
  2384. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2385. return v && *v && std::string(v) != "0";
  2386. }
  2387. std::string unique_unresolvable_host(int n) {
  2388. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2389. // glibc still asks the configured nameserver — which is exactly the path
  2390. // we want to exercise. A unique label per call avoids the resolver cache.
  2391. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2392. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2393. std::to_string(n) + ".invalid";
  2394. }
  2395. } // namespace
  2396. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. for (int i = 0; i < 8; ++i) {
  2402. struct addrinfo hints;
  2403. memset(&hints, 0, sizeof(hints));
  2404. hints.ai_family = AF_UNSPEC;
  2405. hints.ai_socktype = SOCK_STREAM;
  2406. auto host = unique_unresolvable_host(i);
  2407. struct addrinfo *result = nullptr;
  2408. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2409. &result, /*timeout_sec=*/1);
  2410. if (rc == 0 && result) { freeaddrinfo(result); }
  2411. }
  2412. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2413. // stack region they still believe holds their gaicb.
  2414. std::this_thread::sleep_for(std::chrono::seconds(3));
  2415. }
  2416. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2417. if (!should_run_issue_2431_tests()) {
  2418. GTEST_SKIP()
  2419. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2420. }
  2421. std::atomic<bool> stop{false};
  2422. std::vector<std::thread> threads;
  2423. for (int t = 0; t < 8; ++t) {
  2424. threads.emplace_back([t, &stop] {
  2425. int i = 0;
  2426. while (!stop.load(std::memory_order_relaxed)) {
  2427. struct addrinfo hints;
  2428. memset(&hints, 0, sizeof(hints));
  2429. hints.ai_family = AF_UNSPEC;
  2430. hints.ai_socktype = SOCK_STREAM;
  2431. auto host = unique_unresolvable_host(t * 100000 + i++);
  2432. struct addrinfo *result = nullptr;
  2433. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2434. &result, /*timeout_sec=*/1);
  2435. if (rc == 0 && result) { freeaddrinfo(result); }
  2436. }
  2437. });
  2438. }
  2439. std::this_thread::sleep_for(std::chrono::seconds(8));
  2440. stop.store(true, std::memory_order_relaxed);
  2441. for (auto &th : threads) {
  2442. th.join();
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(3));
  2445. }
  2446. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2447. if (!should_run_issue_2431_tests()) {
  2448. GTEST_SKIP()
  2449. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2450. }
  2451. std::atomic<bool> stop{false};
  2452. std::vector<std::thread> threads;
  2453. for (int t = 0; t < 8; ++t) {
  2454. threads.emplace_back([t, &stop] {
  2455. int i = 0;
  2456. while (!stop.load(std::memory_order_relaxed)) {
  2457. auto host = unique_unresolvable_host(t * 100000 + i++);
  2458. Client cli(host, 80);
  2459. cli.set_connection_timeout(1, 0);
  2460. cli.set_read_timeout(1, 0);
  2461. cli.set_write_timeout(1, 0);
  2462. (void)cli.Get("/");
  2463. }
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(8));
  2467. stop.store(true, std::memory_order_relaxed);
  2468. for (auto &th : threads) {
  2469. th.join();
  2470. }
  2471. std::this_thread::sleep_for(std::chrono::seconds(3));
  2472. }
  2473. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2474. TEST(ConnectionErrorTest, InvalidHost) {
  2475. auto host = "-abcde.com";
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(std::chrono::seconds(2));
  2484. auto res = cli.Get("/");
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Connection, res.error());
  2487. }
  2488. TEST(ConnectionErrorTest, InvalidHost2) {
  2489. auto host = "httpcan.org/";
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. SSLClient cli(host);
  2492. #else
  2493. Client cli(host);
  2494. #endif
  2495. cli.set_connection_timeout(std::chrono::seconds(2));
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::Connection, res.error());
  2499. }
  2500. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2501. auto host = "httpcan.org/";
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. stringstream s;
  2511. s << "error code: " << res.error();
  2512. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2513. }
  2514. TEST(ConnectionErrorTest, InvalidPort) {
  2515. auto host = "localhost";
  2516. auto port = 44380;
  2517. #ifdef CPPHTTPLIB_SSL_ENABLED
  2518. SSLClient cli(host, port);
  2519. #else
  2520. Client cli(host, port);
  2521. #endif
  2522. cli.set_connection_timeout(std::chrono::seconds(2));
  2523. auto res = cli.Get("/");
  2524. ASSERT_TRUE(!res);
  2525. EXPECT_TRUE(Error::Connection == res.error() ||
  2526. Error::ConnectionTimeout == res.error());
  2527. }
  2528. TEST(ConnectionErrorTest, Timeout_Online) {
  2529. auto host = "google.com";
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 44380;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 8080;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(std::chrono::seconds(2));
  2538. // only probe one address type so that the error reason
  2539. // correlates to the timed-out IPv4, not the unsupported
  2540. // IPv6 connection attempt
  2541. cli.set_address_family(AF_INET);
  2542. auto res = cli.Get("/");
  2543. ASSERT_TRUE(!res);
  2544. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2545. }
  2546. TEST(CancelTest, NoCancel_Online) {
  2547. auto host = "httpbingo.org";
  2548. auto path = std::string{"/range/32"};
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(5));
  2557. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. }
  2562. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2563. // Use /bytes with a large payload so that the DownloadProgress callback
  2564. // (which only fires for Content-Length responses) is invoked before the
  2565. // entire body is received, giving cancellation a chance to fire.
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/bytes/524288"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. auto port = 443;
  2570. SSLClient cli(host, port);
  2571. #else
  2572. auto port = 80;
  2573. Client cli(host, port);
  2574. #endif
  2575. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2576. cli.set_connection_timeout(std::chrono::seconds(5));
  2577. ASSERT_TRUE(!res);
  2578. EXPECT_EQ(Error::Canceled, res.error());
  2579. }
  2580. TEST(CancelTest, WithCancelLargePayload_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/bytes/524288"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. cli.set_connection_timeout(std::chrono::seconds(5));
  2591. uint32_t count = 0;
  2592. auto res =
  2593. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2594. ASSERT_TRUE(!res);
  2595. EXPECT_EQ(Error::Canceled, res.error());
  2596. }
  2597. TEST(CancelTest, NoCancelPost) {
  2598. Server svr;
  2599. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2600. res.set_content("Hello World!", "text/plain");
  2601. });
  2602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli(HOST, PORT);
  2610. cli.set_connection_timeout(std::chrono::seconds(5));
  2611. auto res =
  2612. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2613. "application/json", [](uint64_t, uint64_t) { return true; });
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. EXPECT_EQ("Hello World!", res->body);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2619. Server svr;
  2620. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2621. res.set_content("Hello World!", "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, WithCancelLargePayloadPost) {
  2639. Server svr;
  2640. svr.set_payload_max_length(200 * 1024 * 1024);
  2641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content(LARGE_DATA, "text/plain");
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. cli.set_payload_max_length(200 * 1024 * 1024);
  2653. cli.set_connection_timeout(std::chrono::seconds(5));
  2654. auto res =
  2655. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2656. "application/json", [](uint64_t, uint64_t) { return false; });
  2657. ASSERT_TRUE(!res);
  2658. EXPECT_EQ(Error::Canceled, res.error());
  2659. }
  2660. TEST(CancelTest, NoCancelPut) {
  2661. Server svr;
  2662. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. thread.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. Client cli(HOST, PORT);
  2673. cli.set_connection_timeout(std::chrono::seconds(5));
  2674. auto res =
  2675. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2676. "application/json", [](uint64_t, uint64_t) { return true; });
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ("Hello World!", res->body);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. }
  2681. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2682. Server svr;
  2683. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2684. res.set_content("Hello World!", "text/plain");
  2685. });
  2686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. thread.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, PORT);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, WithCancelLargePayloadPut) {
  2702. Server svr;
  2703. svr.set_payload_max_length(200 * 1024 * 1024);
  2704. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2705. res.set_content(LARGE_DATA, "text/plain");
  2706. });
  2707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. thread.join();
  2711. ASSERT_FALSE(svr.is_running());
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, PORT);
  2715. cli.set_payload_max_length(200 * 1024 * 1024);
  2716. cli.set_connection_timeout(std::chrono::seconds(5));
  2717. auto res =
  2718. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2719. "application/json", [](uint64_t, uint64_t) { return false; });
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::Canceled, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancelPatch) {
  2724. Server svr;
  2725. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!", "text/plain");
  2727. });
  2728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2729. auto se = detail::scope_exit([&] {
  2730. svr.stop();
  2731. thread.join();
  2732. ASSERT_FALSE(svr.is_running());
  2733. });
  2734. svr.wait_until_ready();
  2735. Client cli(HOST, PORT);
  2736. cli.set_connection_timeout(std::chrono::seconds(5));
  2737. auto res =
  2738. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2739. "application/json", [](uint64_t, uint64_t) { return true; });
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ("Hello World!", res->body);
  2742. EXPECT_EQ(StatusCode::OK_200, res->status);
  2743. }
  2744. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2745. Server svr;
  2746. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2747. res.set_content("Hello World!", "text/plain");
  2748. });
  2749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, PORT);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2765. Server svr;
  2766. svr.set_payload_max_length(200 * 1024 * 1024);
  2767. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2768. res.set_content(LARGE_DATA, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. cli.set_payload_max_length(200 * 1024 * 1024);
  2779. cli.set_connection_timeout(std::chrono::seconds(5));
  2780. auto res =
  2781. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2782. "application/json", [](uint64_t, uint64_t) { return false; });
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Canceled, res.error());
  2785. }
  2786. TEST(CancelTest, NoCancelDelete) {
  2787. Server svr;
  2788. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2789. res.set_content("Hello World!", "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. cli.set_connection_timeout(std::chrono::seconds(5));
  2800. auto res =
  2801. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2802. "application/json", [](uint64_t, uint64_t) { return true; });
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ("Hello World!", res->body);
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. }
  2807. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2808. Server svr;
  2809. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2810. res.set_content("Hello World!", "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2828. Server svr;
  2829. svr.set_payload_max_length(200 * 1024 * 1024);
  2830. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2831. res.set_content(LARGE_DATA, "text/plain");
  2832. });
  2833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2834. auto se = detail::scope_exit([&] {
  2835. svr.stop();
  2836. thread.join();
  2837. ASSERT_FALSE(svr.is_running());
  2838. });
  2839. svr.wait_until_ready();
  2840. Client cli(HOST, PORT);
  2841. cli.set_payload_max_length(200 * 1024 * 1024);
  2842. cli.set_connection_timeout(std::chrono::seconds(5));
  2843. auto res =
  2844. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2845. "application/json", [](uint64_t, uint64_t) { return false; });
  2846. ASSERT_TRUE(!res);
  2847. EXPECT_EQ(Error::Canceled, res.error());
  2848. }
  2849. static std::string remove_whitespace(const std::string &input) {
  2850. std::string output;
  2851. output.reserve(input.size());
  2852. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2853. [](unsigned char c) { return !std::isspace(c); });
  2854. return output;
  2855. }
  2856. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2857. auto host = "httpbingo.org";
  2858. auto path = std::string{"/basic-auth/hello/world"};
  2859. #ifdef CPPHTTPLIB_SSL_ENABLED
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. #else
  2863. auto port = 80;
  2864. Client cli(host, port);
  2865. #endif
  2866. {
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. auto res = cli.Get(
  2873. path, Headers{make_basic_authentication_header("hello", "world")});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "world");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. auto body = remove_whitespace(res->body);
  2885. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2886. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. {
  2890. cli.set_basic_auth("hello", "bad");
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("bad", "world");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. }
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2904. auto host = "httpbingo.org";
  2905. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2906. auto paths = std::vector<std::string>{
  2907. "/digest-auth/auth/hello/world/MD5",
  2908. "/digest-auth/auth/hello/world/SHA-256",
  2909. };
  2910. auto port = 443;
  2911. SSLClient cli(host, port);
  2912. {
  2913. auto res = cli.Get(unauth_path);
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2916. }
  2917. {
  2918. cli.set_digest_auth("hello", "world");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. auto body = remove_whitespace(res->body);
  2923. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2924. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. cli.set_digest_auth("hello", "bad");
  2928. for (const auto &path : paths) {
  2929. auto res = cli.Get(path.c_str());
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. }
  2934. }
  2935. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2936. // comma-separated list of challenges, and each challenge may itself carry a
  2937. // comma-separated auth-param list, so a server can legally offer Basic
  2938. // before Digest, either as two field lines or packed into one. Runs one 401
  2939. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2940. // value() joins them in receipt order) and checks that the retry carries a
  2941. // well-formed Digest Authorization header naming expected_realm.
  2942. static void
  2943. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2944. const std::string &expected_realm) {
  2945. std::atomic<int> hits{0};
  2946. Server svr;
  2947. svr.Get("/x", [&](const Request &req, Response &res) {
  2948. if (++hits == 1) {
  2949. res.status = StatusCode::Unauthorized_401;
  2950. for (const auto &challenge : challenges) {
  2951. res.set_header("WWW-Authenticate", challenge);
  2952. }
  2953. } else {
  2954. auto authorization = req.get_header_value("Authorization");
  2955. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2956. EXPECT_NE(std::string::npos,
  2957. authorization.find("realm=\"" + expected_realm + "\""));
  2958. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2959. res.set_content("ok", "text/plain");
  2960. }
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. std::thread t([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. t.join();
  2967. });
  2968. svr.wait_until_ready();
  2969. Client cli(HOST, port);
  2970. cli.set_digest_auth("hello", "world");
  2971. auto res = cli.Get("/x");
  2972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2973. EXPECT_EQ(2, hits.load());
  2974. }
  2975. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2976. static const char *kDigestChallenge =
  2977. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2978. "algorithm=MD5";
  2979. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2980. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2981. "testrealm");
  2982. }
  2983. // Same challenge list with the schemes in the opposite order, to make sure
  2984. // the fix above didn't just special-case "Basic first".
  2985. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2986. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2987. "testrealm");
  2988. }
  2989. // A comma inside a quoted auth-param value must not be mistaken for the
  2990. // separator between two challenges (or two auth-params).
  2991. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2992. run_digest_challenge_list_test(
  2993. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2994. "algorithm=MD5"},
  2995. "test,realm");
  2996. }
  2997. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2998. // the params and leaves out the fragment.
  2999. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3000. Server svr;
  3001. std::string uri, target;
  3002. svr.Get("/a b", [&](const Request &req, Response &res) {
  3003. auto auth = req.get_header_value("Authorization");
  3004. if (auth.empty()) {
  3005. res.status = StatusCode::Unauthorized_401;
  3006. res.set_header("WWW-Authenticate",
  3007. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3008. return;
  3009. }
  3010. auto b = auth.find("uri=\"") + 5;
  3011. uri = auth.substr(b, auth.find('"', b) - b);
  3012. target = req.target;
  3013. });
  3014. auto port = svr.bind_to_any_port(HOST);
  3015. std::thread t([&]() { svr.listen_after_bind(); });
  3016. auto se = detail::scope_exit([&] {
  3017. svr.stop();
  3018. t.join();
  3019. });
  3020. svr.wait_until_ready();
  3021. Client cli(HOST, port);
  3022. cli.set_digest_auth("hello", "world");
  3023. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ("/a%20b?x=1", target);
  3026. EXPECT_EQ(target, uri);
  3027. }
  3028. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3029. // make_digest_authentication_header() dereferences both unconditionally, so
  3030. // a server sending a challenge missing either one must not be treated as
  3031. // usable -- doing so used to crash the client with std::out_of_range.
  3032. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3033. Server svr;
  3034. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3035. res.status = StatusCode::Unauthorized_401;
  3036. res.set_header("WWW-Authenticate", challenge);
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/x");
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3050. }
  3051. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3052. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3053. }
  3054. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3055. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3059. }
  3060. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3061. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3062. // when storing the values, so the header builder has to re-escape them (and
  3063. // keep algorithm a bare token); otherwise the value breaks out of its
  3064. // quoted-string and injects extra auth-params into the client's Authorization.
  3065. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3066. std::atomic<int> hits{0};
  3067. std::string authorization;
  3068. Server svr;
  3069. svr.Get("/x", [&](const Request &req, Response &res) {
  3070. if (++hits == 1) {
  3071. res.status = StatusCode::Unauthorized_401;
  3072. // On the wire the quotes embedded in the values are backslash-escaped.
  3073. res.set_header("WWW-Authenticate",
  3074. "Digest realm=\"testrealm\", "
  3075. "nonce=\"n\\\"; injected=\\\"x\", "
  3076. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3077. } else {
  3078. authorization = req.get_header_value("Authorization");
  3079. res.set_content("ok", "text/plain");
  3080. }
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. std::thread t([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. t.join();
  3087. });
  3088. svr.wait_until_ready();
  3089. Client cli(HOST, port);
  3090. cli.set_digest_auth("hello", "world");
  3091. auto res = cli.Get("/x");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(2, hits.load());
  3094. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3095. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3096. // inside its quoted-string rather than starting an "injected" auth-param.
  3097. EXPECT_NE(std::string::npos,
  3098. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3099. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3100. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3101. }
  3102. #endif
  3103. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3104. auto host = "google.com";
  3105. auto another_host = "example.com";
  3106. auto wrong_ip = "0.0.0.0";
  3107. #ifdef CPPHTTPLIB_SSL_ENABLED
  3108. SSLClient cli(host);
  3109. #else
  3110. Client cli(host);
  3111. #endif
  3112. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3113. auto res = cli.Get("/");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3116. }
  3117. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3118. auto host = "google.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(!res);
  3128. EXPECT_EQ(Error::Connection, res.error());
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3131. // A mapped value that is not an IP literal must be resolved. "localhost"
  3132. // resolves from the hosts file, so this test needs no external DNS.
  3133. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3134. auto host = "target.invalid";
  3135. Server svr;
  3136. std::string received_host;
  3137. svr.Get("/hi", [&](const Request &req, Response &res) {
  3138. received_host = req.get_header_value("Host");
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, HOST}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. // The mapping only redirects the connection; the identity stays host_.
  3155. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3156. }
  3157. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3158. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3159. auto host = "target.invalid";
  3160. Server svr;
  3161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3162. res.set_content("Hello World!", "text/plain");
  3163. });
  3164. auto port = svr.bind_to_any_port("127.0.0.1");
  3165. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3166. auto se = detail::scope_exit([&] {
  3167. svr.stop();
  3168. thread.join();
  3169. ASSERT_FALSE(svr.is_running());
  3170. });
  3171. svr.wait_until_ready();
  3172. Client cli(host, port);
  3173. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3174. auto res = cli.Get("/hi");
  3175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3176. EXPECT_EQ(StatusCode::OK_200, res->status);
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3179. // An empty mapped value must leave host_ as the connection target. Without
  3180. // that guard the empty value would become the host argument, getaddrinfo
  3181. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3182. // loopback - silently connecting somewhere the caller never asked for.
  3183. // The server listens on loopback, so such a fallback would succeed and is
  3184. // therefore observable as a failure of this test.
  3185. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3186. Server svr;
  3187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. });
  3190. auto port = svr.bind_to_any_port(HOST);
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(blackhole, port);
  3199. cli.set_hostname_addr_map({{blackhole, ""}});
  3200. cli.set_connection_timeout(1);
  3201. auto res = cli.Get("/hi");
  3202. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3203. }
  3204. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3205. auto host = "httpbingo.org";
  3206. auto path = std::string{"/absolute-redirect/3"};
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. SSLClient cli(host);
  3209. #else
  3210. Client cli(host);
  3211. #endif
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get(path);
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(RedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RelativeRedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/relative-redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(TooManyRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/redirect/21"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(!res);
  3254. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3255. }
  3256. #ifdef CPPHTTPLIB_SSL_ENABLED
  3257. TEST(YahooRedirectTest, Redirect_Online) {
  3258. Client cli("yahoo.com");
  3259. auto res = cli.Get("/");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3262. cli.set_follow_location(true);
  3263. res = cli.Get("/");
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3267. }
  3268. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3269. #define REDIR_HOST "httpbingo.org"
  3270. #define REDIR_PATH "/redirect-to"
  3271. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3272. SSLClient cli(REDIR_HOST);
  3273. cli.set_follow_location(true);
  3274. auto res =
  3275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. params.emplace("status_code", "302");
  3285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3290. SSLClient cli(REDIR_HOST);
  3291. cli.set_follow_location(true);
  3292. Params params;
  3293. params.emplace("url", "http://example.com");
  3294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. TEST(UrlWithSpace, Redirect_Online) {
  3299. SSLClient cli("edge.forgecdn.net");
  3300. cli.set_follow_location(true);
  3301. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3305. }
  3306. #endif
  3307. #if !defined(_WIN32) && !defined(_WIN64)
  3308. TEST(ReceiveSignals, Signal) {
  3309. auto setupSignalHandlers = []() {
  3310. struct sigaction act;
  3311. sigemptyset(&act.sa_mask);
  3312. act.sa_flags = SA_SIGINFO;
  3313. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3314. switch (sig) {
  3315. case SIGINT:
  3316. default: break;
  3317. }
  3318. };
  3319. ::sigaction(SIGINT, &act, nullptr);
  3320. };
  3321. Server svr;
  3322. int port = 0;
  3323. auto thread = std::thread([&]() {
  3324. setupSignalHandlers();
  3325. port = svr.bind_to_any_port(HOST);
  3326. svr.listen_after_bind();
  3327. });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. ASSERT_TRUE(svr.is_running());
  3335. pthread_kill(thread.native_handle(), SIGINT);
  3336. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3337. ASSERT_TRUE(svr.is_running());
  3338. }
  3339. #endif
  3340. TEST(RedirectToDifferentPort, Redirect) {
  3341. Server svr1;
  3342. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3343. res.set_content("Hello World!", "text/plain");
  3344. });
  3345. int svr1_port = 0;
  3346. auto thread1 = std::thread([&]() {
  3347. svr1_port = svr1.bind_to_any_port(HOST);
  3348. svr1.listen_after_bind();
  3349. });
  3350. Server svr2;
  3351. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3352. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3353. });
  3354. int svr2_port = 0;
  3355. auto thread2 = std::thread([&]() {
  3356. svr2_port = svr2.bind_to_any_port(HOST);
  3357. svr2.listen_after_bind();
  3358. });
  3359. auto se = detail::scope_exit([&] {
  3360. svr2.stop();
  3361. thread2.join();
  3362. svr1.stop();
  3363. thread1.join();
  3364. ASSERT_FALSE(svr2.is_running());
  3365. ASSERT_FALSE(svr1.is_running());
  3366. });
  3367. svr1.wait_until_ready();
  3368. svr2.wait_until_ready();
  3369. Client cli("localhost", svr2_port);
  3370. cli.set_follow_location(true);
  3371. auto res = cli.Get("/2");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. EXPECT_EQ("Hello World!", res->body);
  3375. }
  3376. // GET /redir on one server redirects to /target on another port, so the
  3377. // client follows it with a new client.
  3378. static Result
  3379. GetThroughRedirectToDifferentPort(Server::Handler target,
  3380. const std::function<void(Client &)> &setup,
  3381. const Headers &headers = Headers()) {
  3382. Server target_svr;
  3383. target_svr.Get("/target", target);
  3384. int target_port = 0;
  3385. auto target_thread = std::thread([&]() {
  3386. target_port = target_svr.bind_to_any_port(HOST);
  3387. target_svr.listen_after_bind();
  3388. });
  3389. Server origin_svr;
  3390. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3391. res.set_redirect(
  3392. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3393. });
  3394. int origin_port = 0;
  3395. auto origin_thread = std::thread([&]() {
  3396. origin_port = origin_svr.bind_to_any_port(HOST);
  3397. origin_svr.listen_after_bind();
  3398. });
  3399. auto se = detail::scope_exit([&] {
  3400. origin_svr.stop();
  3401. origin_thread.join();
  3402. target_svr.stop();
  3403. target_thread.join();
  3404. });
  3405. target_svr.wait_until_ready();
  3406. origin_svr.wait_until_ready();
  3407. Client cli("localhost", origin_port);
  3408. cli.set_follow_location(true);
  3409. setup(cli);
  3410. return cli.Get("/redir", headers);
  3411. }
  3412. static void
  3413. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3414. std::string captured_authorization;
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [&](const Request &req, Response &res) {
  3417. captured_authorization = req.get_header_value("Authorization");
  3418. res.set_content("OK", "text/plain");
  3419. },
  3420. set_auth);
  3421. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3422. EXPECT_EQ(StatusCode::OK_200, result->status);
  3423. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3424. EXPECT_TRUE(captured_authorization.empty());
  3425. }
  3426. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3427. TestDoNotForwardCredentialsOnRedirect(
  3428. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3429. }
  3430. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3431. TestDoNotForwardCredentialsOnRedirect(
  3432. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3433. }
  3434. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3435. std::string captured_cookie;
  3436. auto result = GetThroughRedirectToDifferentPort(
  3437. [&](const Request &req, Response &res) {
  3438. captured_cookie = req.get_header_value("Cookie");
  3439. res.set_content("OK", "text/plain");
  3440. },
  3441. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3442. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3443. EXPECT_EQ(StatusCode::OK_200, result->status);
  3444. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3445. EXPECT_TRUE(captured_cookie.empty());
  3446. }
  3447. TEST(RedirectToSamePort, ForwardCookie) {
  3448. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3449. // header so that ordinary session flows keep working.
  3450. Server svr;
  3451. std::string captured_cookie;
  3452. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3453. res.set_redirect("/target", 302);
  3454. });
  3455. svr.Get("/target", [&](const Request &req, Response &res) {
  3456. captured_cookie = req.get_header_value("Cookie");
  3457. res.set_content("OK", "text/plain");
  3458. });
  3459. auto port = svr.bind_to_any_port(HOST);
  3460. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. Client cli(HOST, port);
  3468. cli.set_follow_location(true);
  3469. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3470. auto res = cli.Get("/redir", headers);
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3474. }
  3475. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3476. std::string authorization;
  3477. std::string trace_id;
  3478. auto result = GetThroughRedirectToDifferentPort(
  3479. [&](const Request &req, Response &res) {
  3480. authorization = req.get_header_value("Authorization");
  3481. trace_id = req.get_header_value("X-Trace-Id");
  3482. res.set_content("OK", "text/plain");
  3483. },
  3484. [](Client &cli) {
  3485. cli.set_default_headers(
  3486. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3487. });
  3488. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3489. EXPECT_EQ(StatusCode::OK_200, result->status);
  3490. // Like a header given with the request, a default one goes along unless it
  3491. // carries credentials (RFC 9110 15.4).
  3492. EXPECT_TRUE(authorization.empty());
  3493. EXPECT_EQ("42", trace_id);
  3494. }
  3495. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.set_content(std::string(2048, 'x'), "text/plain");
  3499. },
  3500. [](Client &cli) { cli.set_payload_max_length(1024); });
  3501. EXPECT_FALSE(result);
  3502. }
  3503. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3504. auto result = GetThroughRedirectToDifferentPort(
  3505. [](const Request &req, Response &res) {
  3506. // Answer after a second, or once the client gives up.
  3507. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3509. }
  3510. res.set_content("late", "text/plain");
  3511. },
  3512. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3513. ASSERT_FALSE(result);
  3514. EXPECT_EQ(Error::Read, result.error());
  3515. }
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3518. auto result = GetThroughRedirectToDifferentPort(
  3519. [](const Request &, Response &res) {
  3520. res.status = StatusCode::Unauthorized_401;
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3523. },
  3524. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3527. }
  3528. #endif
  3529. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3530. Server svr;
  3531. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3532. // Port number that overflows int — should not crash
  3533. res.set_redirect("http://localhost:99999999999999999999/target");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, port);
  3544. cli.set_follow_location(true);
  3545. auto res = cli.Get("/redir");
  3546. // Should fail gracefully, not crash (no valid response due to bad port)
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3550. Server svr;
  3551. auto port = svr.bind_to_any_port(HOST);
  3552. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3553. // The server's own port followed by junk must not be followed
  3554. res.set_redirect("http://" + std::string(HOST) + ":" +
  3555. std::to_string(port) + "junk/target");
  3556. });
  3557. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3558. res.set_content("target", "text/plain");
  3559. });
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. EXPECT_FALSE(res);
  3571. }
  3572. TEST(RedirectFromPageWithContent, Redirect) {
  3573. Server svr;
  3574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3575. res.set_content("___", "text/plain");
  3576. res.set_redirect("/2");
  3577. });
  3578. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. th.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli("localhost", PORT);
  3590. cli.set_follow_location(true);
  3591. std::string body;
  3592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3593. body.append(data, data_length);
  3594. return true;
  3595. });
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("Hello World!", body);
  3599. }
  3600. {
  3601. Client cli("localhost", PORT);
  3602. std::string body;
  3603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3604. body.append(data, data_length);
  3605. return true;
  3606. });
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::Found_302, res->status);
  3609. EXPECT_EQ("___", body);
  3610. }
  3611. }
  3612. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3613. Server svr;
  3614. auto port_str = std::to_string(PORT);
  3615. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3616. auto expected_host = "[::1]:" + port_str;
  3617. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("___", "text/plain");
  3619. // res.set_redirect("/2");
  3620. res.set_redirect(redirect_url);
  3621. });
  3622. svr.Get("/2", [&](const Request &req, Response &res) {
  3623. auto host_header = req.headers.find("Host");
  3624. ASSERT_TRUE(host_header != req.headers.end());
  3625. EXPECT_EQ(expected_host, host_header->second);
  3626. res.set_content("Hello World!", "text/plain");
  3627. });
  3628. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3629. auto se = detail::scope_exit([&] {
  3630. svr.stop();
  3631. th.join();
  3632. ASSERT_FALSE(svr.is_running());
  3633. });
  3634. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3635. // actually starts anything, so the condition !svr.is_running() will
  3636. // always remain true, and the loop never stops.
  3637. // This basically counts how many milliseconds have passed since the
  3638. // call to svr.listen(), and if after 5 seconds nothing started yet
  3639. // aborts the test.
  3640. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3641. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3642. ASSERT_LT(milliseconds, 5000U);
  3643. }
  3644. {
  3645. Client cli("::1", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("::1", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3669. Server svr;
  3670. svr.Get("/foo", [](const Request &req, Response &res) {
  3671. auto a = req.params.find("a");
  3672. if (a != req.params.end()) {
  3673. res.set_content((*a).second, "text/plain");
  3674. res.status = StatusCode::OK_200;
  3675. } else {
  3676. res.status = StatusCode::BadRequest_400;
  3677. }
  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. cli.set_path_encode(false);
  3689. auto res = cli.Get("/foo?a=explicitly+encoded");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. // This expects it back with a space, as the `+` won't have been
  3693. // url-encoded, and server-side the params get decoded turning `+`
  3694. // into spaces.
  3695. EXPECT_EQ("explicitly encoded", res->body);
  3696. }
  3697. }
  3698. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3699. // When path encoding is disabled the client must transmit the supplied
  3700. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3701. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3702. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3703. // than a space (0x20). Assert on the raw wire target to catch this.
  3704. Server svr;
  3705. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3706. svr.Get("/foo", [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(expected_target, req.target);
  3708. res.status = StatusCode::OK_200;
  3709. });
  3710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3711. auto se = detail::scope_exit([&] {
  3712. svr.stop();
  3713. thread.join();
  3714. ASSERT_FALSE(svr.is_running());
  3715. });
  3716. svr.wait_until_ready();
  3717. {
  3718. Client cli(HOST, PORT);
  3719. cli.set_path_encode(false);
  3720. auto res = cli.Get(expected_target.c_str());
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. }
  3724. }
  3725. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3726. // `open_stream()` used to skip the path encoding that the buffered send
  3727. // path applies, so the same `path` produced different bytes in the request
  3728. // line depending on which API was used. Assert the two agree.
  3729. Server svr;
  3730. std::string target;
  3731. svr.Get(".*", [&](const Request &req, Response &res) {
  3732. target = req.target;
  3733. res.status = StatusCode::OK_200;
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. struct {
  3744. const char *path;
  3745. const char *expected;
  3746. } cases[] = {
  3747. {"/a b?x=1", "/a%20b?x=1"},
  3748. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3749. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3750. };
  3751. for (const auto &c : cases) {
  3752. Client cli(HOST, port);
  3753. target.clear();
  3754. auto res = cli.Get(c.path);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3757. auto buffered_target = target;
  3758. target.clear();
  3759. auto handle = cli.open_stream("GET", c.path);
  3760. EXPECT_TRUE(handle.is_valid())
  3761. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3762. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3763. }
  3764. }
  3765. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3766. // The `set_path_encode(false)` contract — transmit the supplied target
  3767. // verbatim — must hold for the streaming API too.
  3768. Server svr;
  3769. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, port);
  3785. cli.set_path_encode(false);
  3786. auto handle = cli.open_stream("GET", expected_target);
  3787. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3788. EXPECT_EQ(expected_target, target);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3792. // With path encoding enabled a CR/LF in the target is percent-encoded
  3793. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3794. // write_request_line still backstops `set_path_encode(false)`, which is
  3795. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3796. Server svr;
  3797. // Captured before routing: the decoded path contains a newline, which a
  3798. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3799. std::string target;
  3800. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. return Server::HandlerResponse::Handled;
  3804. });
  3805. auto port = svr.bind_to_any_port(HOST);
  3806. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. {
  3814. Client cli(HOST, port);
  3815. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3816. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3817. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3818. }
  3819. }
  3820. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3821. // Every control character is percent-encoded, not just CR/LF, so the target
  3822. // passes the request-target check in write_request_line.
  3823. Server svr;
  3824. std::string target;
  3825. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3826. target = req.target;
  3827. res.status = StatusCode::OK_200;
  3828. return Server::HandlerResponse::Handled;
  3829. });
  3830. auto port = svr.bind_to_any_port(HOST);
  3831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli(HOST, port);
  3840. auto res = cli.Get("/a\tb\x1b\x7f");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ("/a%09b%1B%7F", target);
  3843. }
  3844. }
  3845. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3846. // Nothing may reach the wire: a raw CR/LF target would split the request
  3847. // line and inject headers.
  3848. Server svr;
  3849. // Pre-routing so that "not called" means nothing reached the server at all,
  3850. // rather than merely failing to match a handler pattern.
  3851. auto handler_called = false;
  3852. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3853. handler_called = true;
  3854. res.status = StatusCode::OK_200;
  3855. return Server::HandlerResponse::Handled;
  3856. });
  3857. auto port = svr.bind_to_any_port(HOST);
  3858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. {
  3866. Client cli(HOST, port);
  3867. cli.set_path_encode(false);
  3868. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3869. EXPECT_FALSE(handle.is_valid());
  3870. EXPECT_EQ(Error::Write, handle.error);
  3871. EXPECT_FALSE(handler_called);
  3872. }
  3873. }
  3874. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3875. // Which of the two branches runs is decided by whether the query component
  3876. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3877. // an empty query and must still fall back to building one from
  3878. // `req.params`, while a non-empty query must win over `req.params`.
  3879. Server svr;
  3880. std::string target;
  3881. svr.Get("/foo", [&](const Request &req, Response &res) {
  3882. target = req.target;
  3883. res.status = StatusCode::OK_200;
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. // Trailing `?` -> empty query component -> `req.params` is used.
  3895. Client cli(HOST, port);
  3896. Request req;
  3897. req.method = "GET";
  3898. req.path = "/foo?";
  3899. req.params.emplace("a", "1");
  3900. target.clear();
  3901. auto res = cli.send(req);
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ("/foo?a=1", target);
  3904. }
  3905. {
  3906. // Non-empty query in `req.path` -> `req.params` is not appended.
  3907. Client cli(HOST, port);
  3908. Request req;
  3909. req.method = "GET";
  3910. req.path = "/foo?b=2";
  3911. req.params.emplace("a", "1");
  3912. target.clear();
  3913. auto res = cli.send(req);
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ("/foo?b=2", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3919. Server svr;
  3920. svr.Get("/", [](const Request &req, Response &) {
  3921. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3922. });
  3923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. {
  3931. Client cli(HOST, PORT);
  3932. cli.set_path_encode(false);
  3933. auto res = cli.Get("/?something=%0A");
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. }
  3938. TEST(BindServerTest, BindDualStack) {
  3939. Server svr;
  3940. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("Hello World!", "text/plain");
  3942. });
  3943. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. {
  3951. Client cli("127.0.0.1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. {
  3958. Client cli("::1", PORT);
  3959. auto res = cli.Get("/1");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("Hello World!", res->body);
  3963. }
  3964. }
  3965. TEST(BindServerTest, BindAndListenSeparately) {
  3966. Server svr;
  3967. int port = svr.bind_to_any_port("0.0.0.0");
  3968. ASSERT_TRUE(svr.is_valid());
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. }
  3972. // Reports whether anything is still listening on a loopback port. A plain
  3973. // connect() is used instead of a Client request because a socket left bound by
  3974. // mistake accepts the connection into its backlog and never answers, which
  3975. // would hang the test instead of failing it.
  3976. static bool is_loopback_port_accepting(int port) {
  3977. sockaddr_in addr{};
  3978. addr.sin_family = AF_INET;
  3979. addr.sin_port = htons(static_cast<uint16_t>(port));
  3980. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3981. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3982. EXPECT_NE(sock, INVALID_SOCKET);
  3983. if (sock == INVALID_SOCKET) { return false; }
  3984. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3985. static_cast<socklen_t>(sizeof(addr)));
  3986. detail::close_socket(sock);
  3987. return ret == 0;
  3988. }
  3989. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3990. Server svr;
  3991. auto port = svr.bind_to_any_port("127.0.0.1");
  3992. ASSERT_TRUE(port > 0);
  3993. svr.stop();
  3994. // bind_to_any_port() already called listen(2), so until stop() closed the
  3995. // descriptor the port kept accepting connections into the backlog. ASSERT
  3996. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3997. // below blocks forever in the accept loop.
  3998. ASSERT_FALSE(is_loopback_port_accepting(port));
  3999. // Nothing is left to accept on, so listen_after_bind() must report failure
  4000. // instead of returning success without ever serving.
  4001. EXPECT_FALSE(svr.listen_after_bind());
  4002. // The failed listen marks the server decommissioned, so a waiter returns
  4003. // instead of spinning forever.
  4004. svr.wait_until_ready();
  4005. }
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. int port = svr.bind_to_any_port("0.0.0.0");
  4011. ASSERT_TRUE(svr.is_valid());
  4012. ASSERT_TRUE(port > 0);
  4013. svr.stop();
  4014. }
  4015. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4016. // or a rejected CustomRoute() registration would not stop the server binding.
  4017. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4019. CLIENT_CA_CERT_DIR);
  4020. ASSERT_TRUE(svr.is_valid());
  4021. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4022. EXPECT_FALSE(svr.is_valid());
  4023. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4024. }
  4025. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4026. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4027. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. svr.stop();
  4032. }
  4033. TEST(BindServerTest, UpdateCertsPem) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4035. int port = svr.bind_to_any_port("0.0.0.0");
  4036. ASSERT_TRUE(svr.is_valid());
  4037. ASSERT_TRUE(port > 0);
  4038. // Read PEM files
  4039. std::string cert_pem, key_pem, ca_pem;
  4040. read_file(SERVER_CERT_FILE, cert_pem);
  4041. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4042. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4043. // Update server certificates using PEM API
  4044. ASSERT_TRUE(
  4045. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.stop();
  4048. }
  4049. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4050. // Start server with client CA (enables client auth)
  4051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4052. ASSERT_TRUE(svr.is_valid());
  4053. bool handler_called = false;
  4054. svr.Get("/test", [&](const Request &req, Response &res) {
  4055. handler_called = true;
  4056. // Verify client certificate is present
  4057. auto cert = req.peer_cert();
  4058. EXPECT_TRUE(static_cast<bool>(cert));
  4059. res.set_content("ok", "text/plain");
  4060. });
  4061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4062. auto se = detail::scope_exit([&] {
  4063. svr.stop();
  4064. t.join();
  4065. ASSERT_FALSE(svr.is_running());
  4066. });
  4067. svr.wait_until_ready();
  4068. // Read PEM files
  4069. std::string cert_pem, key_pem, ca_pem;
  4070. read_file(SERVER_CERT_FILE, cert_pem);
  4071. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4072. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4073. // Update server certificates and client CA using PEM API while server running
  4074. ASSERT_TRUE(
  4075. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4076. // Connect with client certificate
  4077. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4078. cli.enable_server_certificate_verification(false);
  4079. cli.set_connection_timeout(30);
  4080. auto res = cli.Get("/test");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_TRUE(handler_called);
  4084. EXPECT_EQ("ok", res->body);
  4085. }
  4086. // Puts a CA that did not sign the client's certificate in the old one's place.
  4087. static bool replace_client_ca(SSLServer &svr) {
  4088. std::string cert_pem, key_pem, ca_pem;
  4089. read_file(SERVER_CERT_FILE, cert_pem);
  4090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4091. read_file(SERVER_CERT2_FILE, ca_pem);
  4092. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4093. ca_pem.c_str());
  4094. }
  4095. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. svr.Get("/test", [](const Request &, Response &res) {
  4099. res.set_content("ok", "text/plain");
  4100. });
  4101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. auto get = [] {
  4109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4110. cli.enable_server_certificate_verification(false);
  4111. return cli.Get("/test");
  4112. };
  4113. ASSERT_TRUE(get());
  4114. ASSERT_TRUE(replace_client_ca(svr));
  4115. EXPECT_FALSE(get());
  4116. }
  4117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4118. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4120. ASSERT_TRUE(svr.is_valid());
  4121. tls::set_verify_callback(svr.tls_context(),
  4122. [](const tls::VerifyContext &) -> bool {
  4123. throw std::runtime_error("verify");
  4124. });
  4125. svr.Get("/test", [](const Request &, Response &res) {
  4126. res.set_content("ok", "text/plain");
  4127. });
  4128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. t.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. auto get = [] {
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. return cli.Get("/test");
  4139. };
  4140. EXPECT_FALSE(get());
  4141. // The handshake is over, so an update does not wait for it.
  4142. std::string cert_pem, key_pem;
  4143. read_file(SERVER_CERT_FILE, cert_pem);
  4144. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4145. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4146. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4147. return v.preverify_ok;
  4148. });
  4149. auto res = get();
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("ok", res->body);
  4152. }
  4153. #endif
  4154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4155. // Sends each request over a new connection with a client certificate,
  4156. // resuming the session of the one before when there is one.
  4157. class ResumingClient {
  4158. public:
  4159. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4160. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4161. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4162. SSL_FILETYPE_PEM);
  4163. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4164. // callback, not through SSL_get1_session().
  4165. SSL_CTX_set_app_data(ctx_, this);
  4166. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4167. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4168. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4169. auto self = static_cast<ResumingClient *>(
  4170. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4171. SSL_SESSION_free(self->session_);
  4172. self->session_ = session;
  4173. return 1; // Keeps the reference
  4174. });
  4175. }
  4176. ~ResumingClient() {
  4177. SSL_SESSION_free(session_);
  4178. SSL_CTX_free(ctx_);
  4179. }
  4180. // Tells whether the request was answered.
  4181. bool get() {
  4182. auto error = Error::Success;
  4183. auto sock = detail::create_client_socket(
  4184. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4185. /*connection_timeout_sec=*/5, 0,
  4186. /*read_timeout_sec=*/5, 0,
  4187. /*write_timeout_sec=*/5, 0, std::string(), error);
  4188. if (sock == INVALID_SOCKET) { return false; }
  4189. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4190. auto ssl = SSL_new(ctx_);
  4191. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4192. SSL_set_fd(ssl, static_cast<int>(sock));
  4193. if (session_) { SSL_set_session(ssl, session_); }
  4194. if (SSL_connect(ssl) != 1) { return false; }
  4195. reused_ = SSL_session_reused(ssl) == 1;
  4196. // Reading the response also takes in a TLS 1.3 session ticket.
  4197. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4198. "Connection: close\r\n\r\n";
  4199. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4200. std::string res;
  4201. char buf[256];
  4202. int n;
  4203. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4204. res.append(buf, static_cast<size_t>(n));
  4205. }
  4206. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4207. SSL_shutdown(ssl);
  4208. return res.find("200 OK") != std::string::npos;
  4209. }
  4210. // Whether the last connection resumed a session
  4211. bool reused() const { return reused_; }
  4212. private:
  4213. SSL_CTX *ctx_;
  4214. SSL_SESSION *session_ = nullptr;
  4215. bool reused_ = false;
  4216. };
  4217. // A client that resumes its session gets through, but not once the client CA
  4218. // has changed, as a resumed session does not show the certificate again.
  4219. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. svr.Get("/test", [](const Request &, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4226. auto se = detail::scope_exit([&] {
  4227. svr.stop();
  4228. t.join();
  4229. ASSERT_FALSE(svr.is_running());
  4230. });
  4231. svr.wait_until_ready();
  4232. ResumingClient cli;
  4233. ASSERT_TRUE(cli.get());
  4234. ASSERT_TRUE(cli.get());
  4235. EXPECT_TRUE(cli.reused());
  4236. ASSERT_TRUE(replace_client_ca(svr));
  4237. EXPECT_FALSE(cli.get());
  4238. }
  4239. // A resumed session does not show the certificate again, so the server does
  4240. // not resume one with a verify callback to run on it.
  4241. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4243. ASSERT_TRUE(svr.is_valid());
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. svr.Get("/test", [](const Request &, Response &res) {
  4248. res.set_content("ok", "text/plain");
  4249. });
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. auto se = detail::scope_exit([&] {
  4252. svr.stop();
  4253. t.join();
  4254. ASSERT_FALSE(svr.is_running());
  4255. });
  4256. svr.wait_until_ready();
  4257. ResumingClient cli;
  4258. ASSERT_TRUE(cli.get());
  4259. ASSERT_TRUE(cli.get());
  4260. EXPECT_FALSE(cli.reused());
  4261. }
  4262. #endif
  4263. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4264. // wolfSSL shares its session cache between contexts, so a resumed session
  4265. // could carry a client certificate checked against another server's CA, or
  4266. // against a client CA since replaced.
  4267. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. // Trusts a CA that did not sign the client's certificate.
  4271. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4272. ASSERT_TRUE(other.is_valid());
  4273. for (auto s : {&svr, &other}) {
  4274. s->Get("/test", [](const Request &, Response &res) {
  4275. res.set_content("ok", "text/plain");
  4276. });
  4277. }
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4280. auto se = detail::scope_exit([&] {
  4281. other.stop();
  4282. svr.stop();
  4283. t2.join();
  4284. t.join();
  4285. });
  4286. svr.wait_until_ready();
  4287. other.wait_until_ready();
  4288. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4289. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4290. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4291. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4292. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4293. ASSERT_EQ(WOLFSSL_SUCCESS,
  4294. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4295. WOLFSSL_FILETYPE_PEM));
  4296. WOLFSSL_SESSION *session = nullptr;
  4297. auto session_se = detail::scope_exit([&] {
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. });
  4300. // A request over a new connection, resuming `session` when there is one and
  4301. // keeping the connection's own in its place. Tells whether it was answered.
  4302. auto get = [&](int port) {
  4303. auto error = Error::Success;
  4304. auto sock = detail::create_client_socket(
  4305. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4306. /*connection_timeout_sec=*/5, 0,
  4307. /*read_timeout_sec=*/5, 0,
  4308. /*write_timeout_sec=*/5, 0, std::string(), error);
  4309. if (sock == INVALID_SOCKET) { return false; }
  4310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4311. auto ssl = wolfSSL_new(ctx);
  4312. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4313. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4314. if (session) { wolfSSL_set_session(ssl, session); }
  4315. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4316. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4317. "Connection: close\r\n\r\n";
  4318. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4319. std::string res;
  4320. char buf[256];
  4321. int n;
  4322. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4323. res.append(buf, static_cast<size_t>(n));
  4324. }
  4325. wolfSSL_shutdown(ssl);
  4326. if (session) { wolfSSL_SESSION_free(session); }
  4327. session = wolfSSL_get1_session(ssl);
  4328. return res.find("200 OK") != std::string::npos;
  4329. };
  4330. ASSERT_TRUE(get(PORT));
  4331. EXPECT_FALSE(get(PORT + 1));
  4332. ASSERT_TRUE(get(PORT));
  4333. ASSERT_TRUE(replace_client_ca(svr));
  4334. EXPECT_FALSE(get(PORT));
  4335. }
  4336. #endif
  4337. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4339. ASSERT_TRUE(svr.is_valid());
  4340. svr.Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4344. auto se = detail::scope_exit([&] {
  4345. svr.stop();
  4346. t.join();
  4347. ASSERT_FALSE(svr.is_running());
  4348. });
  4349. svr.wait_until_ready();
  4350. // A connection that sends no ClientHello keeps its handshake in progress,
  4351. // once the server has had a moment to start it.
  4352. auto error = Error::Success;
  4353. auto sock = detail::create_client_socket(
  4354. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4355. /*connection_timeout_sec=*/5, 0,
  4356. /*read_timeout_sec=*/5, 0,
  4357. /*write_timeout_sec=*/5, 0, std::string(), error);
  4358. ASSERT_NE(INVALID_SOCKET, sock);
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4360. std::string cert_pem, key_pem;
  4361. read_file(SERVER_CERT_FILE, cert_pem);
  4362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4363. auto update = std::async(std::launch::async, [&]() {
  4364. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4365. });
  4366. EXPECT_EQ(std::future_status::timeout,
  4367. update.wait_for(std::chrono::milliseconds(200)));
  4368. detail::close_socket(sock);
  4369. EXPECT_TRUE(update.get());
  4370. SSLClient cli(HOST, PORT);
  4371. cli.enable_server_certificate_verification(false);
  4372. auto res = cli.Get("/test");
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. #endif
  4377. TEST(ErrorHandlerTest, ContentLength) {
  4378. Server svr;
  4379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4380. res.status = StatusCode::OK_200;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. res.status = 524;
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, PORT);
  4397. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4401. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4402. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4403. }
  4404. }
  4405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4406. TEST(ExceptionTest, WithoutExceptionHandler) {
  4407. Server svr;
  4408. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4409. throw std::runtime_error("exception...");
  4410. });
  4411. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4412. throw std::runtime_error("exception\r\n...");
  4413. });
  4414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4415. auto se = detail::scope_exit([&] {
  4416. svr.stop();
  4417. listen_thread.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. Client cli("localhost", PORT);
  4422. {
  4423. auto res = cli.Get("/exception");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4426. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4427. }
  4428. {
  4429. auto res = cli.Get("/unknown");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. }
  4435. TEST(ExceptionTest, WithExceptionHandler) {
  4436. Server svr;
  4437. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4438. std::exception_ptr ep) {
  4439. EXPECT_FALSE(ep == nullptr);
  4440. try {
  4441. std::rethrow_exception(ep);
  4442. } catch (std::exception &e) {
  4443. EXPECT_EQ("abc", std::string(e.what()));
  4444. } catch (...) {}
  4445. res.status = StatusCode::InternalServerError_500;
  4446. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4447. "text/html"); // <= Content-Length still 13 at this point
  4448. });
  4449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4450. res.set_content("Hello World!\n", "text/plain");
  4451. throw std::runtime_error("abc");
  4452. });
  4453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4454. auto se = detail::scope_exit([&] {
  4455. svr.stop();
  4456. thread.join();
  4457. ASSERT_FALSE(svr.is_running());
  4458. });
  4459. svr.wait_until_ready();
  4460. for (size_t i = 0; i < 10; i++) {
  4461. Client cli(HOST, PORT);
  4462. for (size_t j = 0; j < 100; j++) {
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. cli.set_keep_alive(true);
  4471. for (size_t j = 0; j < 100; j++) {
  4472. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4476. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4478. }
  4479. }
  4480. }
  4481. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4482. Server svr;
  4483. svr.set_exception_handler(
  4484. [](const Request &, Response &res, std::exception_ptr) {
  4485. res.set_content("oops", "text/plain");
  4486. });
  4487. svr.Get("/throw", [](const Request &, Response &) {
  4488. throw std::runtime_error("throw");
  4489. });
  4490. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4491. res.status = StatusCode::Created_201;
  4492. throw std::runtime_error("created-then-throw");
  4493. });
  4494. auto port = svr.bind_to_any_port(HOST);
  4495. ASSERT_GT(port, 0);
  4496. thread t = thread([&] { svr.listen_after_bind(); });
  4497. auto se = detail::scope_exit([&] {
  4498. svr.stop();
  4499. t.join();
  4500. ASSERT_FALSE(svr.is_running());
  4501. });
  4502. svr.wait_until_ready();
  4503. Client cli(HOST, port);
  4504. for (auto path : {"/throw", "/created-then-throw"}) {
  4505. auto res = cli.Get(path);
  4506. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4507. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4508. }
  4509. }
  4510. TEST(ExceptionTest, AndErrorHandler) {
  4511. Server svr;
  4512. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4513. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4514. });
  4515. svr.set_exception_handler(
  4516. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4517. EXPECT_FALSE(ep == nullptr);
  4518. try {
  4519. std::rethrow_exception(ep);
  4520. } catch (std::exception &e) {
  4521. res.set_content(e.what(), "text/html");
  4522. } catch (...) {}
  4523. res.status = StatusCode::InternalServerError_500;
  4524. });
  4525. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4526. throw std::runtime_error("EXCEPTION");
  4527. });
  4528. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4529. res.set_content("ERROR", "text/html");
  4530. res.status = StatusCode::InternalServerError_500;
  4531. });
  4532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4533. auto se = detail::scope_exit([&] {
  4534. svr.stop();
  4535. thread.join();
  4536. ASSERT_FALSE(svr.is_running());
  4537. });
  4538. svr.wait_until_ready();
  4539. Client cli(HOST, PORT);
  4540. {
  4541. auto res = cli.Get("/exception");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4544. EXPECT_EQ("EXCEPTION", res->body);
  4545. }
  4546. {
  4547. auto res = cli.Get("/error");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4550. EXPECT_EQ("ERROR", res->body);
  4551. }
  4552. {
  4553. auto res = cli.Get("/invalid");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4556. EXPECT_EQ("NOT_FOUND", res->body);
  4557. }
  4558. }
  4559. #endif
  4560. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4561. // An exception from a user callback outside process_request()'s try/catch
  4562. // used to unwind into the task queue - which does not catch - and terminate
  4563. // the process. Each test below runs the server on a single worker thread: a
  4564. // guard that catches the exception but still loses the thread would otherwise
  4565. // be hidden by a spare worker serving the follow-up request. Note that a
  4566. // regression here aborts the whole test binary rather than failing one test.
  4567. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4568. Server svr;
  4569. svr.new_task_queue = [] { return new ThreadPool(1); };
  4570. std::atomic<int> reported{0};
  4571. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4572. if (err == Error::UserCallbackException) { reported++; }
  4573. });
  4574. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4575. res.set_content_provider(
  4576. 1024, "text/plain",
  4577. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4578. sink.write("hello", 5);
  4579. throw std::runtime_error("from the content provider");
  4580. });
  4581. });
  4582. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4583. res.set_content("ok", "text/plain");
  4584. });
  4585. auto port = svr.bind_to_any_port(HOST);
  4586. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4587. auto se = detail::scope_exit([&] {
  4588. svr.stop();
  4589. listen_thread.join();
  4590. ASSERT_FALSE(svr.is_running());
  4591. });
  4592. svr.wait_until_ready();
  4593. {
  4594. Client cli(HOST, port);
  4595. cli.set_read_timeout(5, 0);
  4596. EXPECT_FALSE(cli.Get("/throw"));
  4597. }
  4598. EXPECT_TRUE(svr.is_running());
  4599. EXPECT_EQ(1, reported.load());
  4600. // A request on a fresh connection is still served.
  4601. {
  4602. Client cli(HOST, port);
  4603. auto res = cli.Get("/ok");
  4604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. EXPECT_EQ("ok", res->body);
  4607. }
  4608. }
  4609. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4610. Server svr;
  4611. svr.new_task_queue = [] { return new ThreadPool(1); };
  4612. std::atomic<bool> should_throw{true};
  4613. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4614. res.set_content("hi", "text/plain");
  4615. });
  4616. svr.set_post_routing_handler(
  4617. [&](const Request & /*req*/, Response & /*res*/) {
  4618. if (should_throw) {
  4619. throw std::runtime_error("from the post-routing handler");
  4620. }
  4621. });
  4622. auto port = svr.bind_to_any_port(HOST);
  4623. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4624. auto se = detail::scope_exit([&] {
  4625. svr.stop();
  4626. listen_thread.join();
  4627. ASSERT_FALSE(svr.is_running());
  4628. });
  4629. svr.wait_until_ready();
  4630. {
  4631. Client cli(HOST, port);
  4632. cli.set_read_timeout(5, 0);
  4633. EXPECT_FALSE(cli.Get("/hi"));
  4634. }
  4635. EXPECT_TRUE(svr.is_running());
  4636. should_throw = false;
  4637. {
  4638. Client cli(HOST, port);
  4639. auto res = cli.Get("/hi");
  4640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4641. EXPECT_EQ(StatusCode::OK_200, res->status);
  4642. EXPECT_EQ("hi", res->body);
  4643. }
  4644. }
  4645. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4646. // The guard reports the caught exception through the error logger, which is
  4647. // a user callback too. A logger that throws has to be contained as well, or
  4648. // the process would terminate from inside the catch.
  4649. Server svr;
  4650. svr.new_task_queue = [] { return new ThreadPool(1); };
  4651. std::atomic<int> reported{0};
  4652. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4653. if (err == Error::UserCallbackException) {
  4654. reported++;
  4655. throw std::runtime_error("from the error logger");
  4656. }
  4657. });
  4658. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4659. res.set_content_provider(
  4660. 1024, "text/plain",
  4661. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4662. sink.write("hello", 5);
  4663. throw std::runtime_error("from the content provider");
  4664. });
  4665. });
  4666. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4667. res.set_content("ok", "text/plain");
  4668. });
  4669. auto port = svr.bind_to_any_port(HOST);
  4670. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. listen_thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. {
  4678. Client cli(HOST, port);
  4679. cli.set_read_timeout(5, 0);
  4680. EXPECT_FALSE(cli.Get("/throw"));
  4681. }
  4682. EXPECT_TRUE(svr.is_running());
  4683. EXPECT_EQ(1, reported.load());
  4684. {
  4685. Client cli(HOST, port);
  4686. auto res = cli.Get("/ok");
  4687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4688. EXPECT_EQ(StatusCode::OK_200, res->status);
  4689. EXPECT_EQ("ok", res->body);
  4690. }
  4691. }
  4692. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4693. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4694. // so the exception unwinds through the ws::WebSocket object on its way to
  4695. // the guard. None of the HTTP cases above cross that.
  4696. Server svr;
  4697. svr.new_task_queue = [] { return new ThreadPool(1); };
  4698. std::atomic<int> reported{0};
  4699. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4700. if (err == Error::UserCallbackException) { reported++; }
  4701. });
  4702. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4703. throw std::runtime_error("from the WebSocket handler");
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4718. "/ws");
  4719. auto res = client.connect();
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. // The server dropped the connection instead of dying.
  4722. std::string msg;
  4723. EXPECT_FALSE(client.read(msg));
  4724. client.close();
  4725. }
  4726. EXPECT_TRUE(svr.is_running());
  4727. EXPECT_EQ(1, reported.load());
  4728. {
  4729. Client cli(HOST, port);
  4730. auto res = cli.Get("/ok");
  4731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4732. EXPECT_EQ(StatusCode::OK_200, res->status);
  4733. EXPECT_EQ("ok", res->body);
  4734. }
  4735. }
  4736. #ifdef CPPHTTPLIB_SSL_ENABLED
  4737. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4738. // SSLServer::process_and_close_socket() is a separate overload with its own
  4739. // guard, so it is exercised on its own.
  4740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4741. ASSERT_TRUE(svr.is_valid());
  4742. svr.new_task_queue = [] { return new ThreadPool(1); };
  4743. std::atomic<int> reported{0};
  4744. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4745. if (err == Error::UserCallbackException) { reported++; }
  4746. });
  4747. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4748. res.set_content_provider(
  4749. 1024, "text/plain",
  4750. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4751. sink.write("hello", 5);
  4752. throw std::runtime_error("from the content provider");
  4753. });
  4754. });
  4755. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4756. res.set_content("ok", "text/plain");
  4757. });
  4758. auto port = svr.bind_to_any_port(HOST);
  4759. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4760. auto se = detail::scope_exit([&] {
  4761. svr.stop();
  4762. listen_thread.join();
  4763. ASSERT_FALSE(svr.is_running());
  4764. });
  4765. svr.wait_until_ready();
  4766. {
  4767. SSLClient cli(HOST, port);
  4768. cli.enable_server_certificate_verification(false);
  4769. cli.set_read_timeout(5, 0);
  4770. EXPECT_FALSE(cli.Get("/throw"));
  4771. }
  4772. EXPECT_TRUE(svr.is_running());
  4773. EXPECT_EQ(1, reported.load());
  4774. {
  4775. SSLClient cli(HOST, port);
  4776. cli.enable_server_certificate_verification(false);
  4777. auto res = cli.Get("/ok");
  4778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. EXPECT_EQ("ok", res->body);
  4781. }
  4782. }
  4783. #endif
  4784. #endif
  4785. TEST(NoContentTest, ContentLength) {
  4786. Server svr;
  4787. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4788. res.status = StatusCode::NoContent_204;
  4789. });
  4790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4791. auto se = detail::scope_exit([&] {
  4792. svr.stop();
  4793. thread.join();
  4794. ASSERT_FALSE(svr.is_running());
  4795. });
  4796. svr.wait_until_ready();
  4797. {
  4798. Client cli(HOST, PORT);
  4799. auto res = cli.Get("/hi");
  4800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4801. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4802. // RFC 9110 8.6: none in a 204 response
  4803. EXPECT_FALSE(res->has_header("Content-Length"));
  4804. }
  4805. }
  4806. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4807. Server svr;
  4808. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4809. res.set_header("Content-Length", "5");
  4810. res.set_content("hello world", "text/plain");
  4811. });
  4812. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4813. // A body that reads as the last chunk, were it taken as chunked
  4814. res.set_header("Transfer-Encoding", "chunked");
  4815. res.set_content("0\r\n\r\n", "text/plain");
  4816. });
  4817. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4818. res.set_header("Content-Length", "2");
  4819. res.set_content_provider(5, "text/plain",
  4820. [](size_t offset, size_t length, DataSink &sink) {
  4821. sink.write(&"hello"[offset], length);
  4822. return true;
  4823. });
  4824. });
  4825. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4826. res.set_header("Content-Length", "1234");
  4827. });
  4828. thread t = thread([&] { svr.listen(HOST, PORT); });
  4829. auto se = detail::scope_exit([&] {
  4830. svr.stop();
  4831. t.join();
  4832. ASSERT_FALSE(svr.is_running());
  4833. });
  4834. svr.wait_until_ready();
  4835. Client cli(HOST, PORT);
  4836. cli.set_read_timeout(1, 0);
  4837. auto expect_body = [&](const Result &res, const std::string &body) {
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(body, res->body);
  4840. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4841. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4842. };
  4843. Headers identity{{"Accept-Encoding", ""}};
  4844. expect_body(cli.Get("/body", identity), "hello world");
  4845. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4846. expect_body(cli.Get("/body",
  4847. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4848. "he");
  4849. expect_body(cli.Get("/provider", identity), "hello");
  4850. expect_body(cli.Get("/empty", identity), "");
  4851. // A HEAD response may give the length of the body a GET would get.
  4852. auto res = cli.Head("/empty");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4855. }
  4856. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4857. Server svr;
  4858. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4859. res.set_content("short", "text/plain");
  4860. });
  4861. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4862. res.body += " with a footer";
  4863. res.set_header("Transfer-Encoding", "chunked");
  4864. });
  4865. thread t = thread([&] { svr.listen(HOST, PORT); });
  4866. auto se = detail::scope_exit([&] {
  4867. svr.stop();
  4868. t.join();
  4869. ASSERT_FALSE(svr.is_running());
  4870. });
  4871. svr.wait_until_ready();
  4872. Client cli(HOST, PORT);
  4873. cli.set_read_timeout(1, 0);
  4874. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ("short with a footer", res->body);
  4877. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4878. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4879. }
  4880. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4881. Server svr;
  4882. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4883. res.set_header("Content-Length", "3");
  4884. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4885. sink.write("abc", 3);
  4886. sink.done();
  4887. return true;
  4888. });
  4889. });
  4890. thread t = thread([&] { svr.listen(HOST, PORT); });
  4891. auto se = detail::scope_exit([&] {
  4892. svr.stop();
  4893. t.join();
  4894. ASSERT_FALSE(svr.is_running());
  4895. });
  4896. svr.wait_until_ready();
  4897. Client cli(HOST, PORT);
  4898. cli.set_keep_alive(true);
  4899. auto res = cli.Get("/");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ("abc", res->body);
  4902. EXPECT_FALSE(res->has_header("Content-Length"));
  4903. EXPECT_EQ("close", res->get_header_value("Connection"));
  4904. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4905. // No body to delimit
  4906. auto head = cli.Head("/");
  4907. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4908. EXPECT_FALSE(head->has_header("Connection"));
  4909. }
  4910. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4911. #ifdef CPPHTTPLIB_SSL_ENABLED
  4912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4913. ASSERT_TRUE(svr.is_valid());
  4914. #else
  4915. Server svr;
  4916. #endif
  4917. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4918. if (req.path == "/routing_handler") {
  4919. res.set_header("PRE_ROUTING", "on");
  4920. res.set_content("Routing Handler", "text/plain");
  4921. return httplib::Server::HandlerResponse::Handled;
  4922. }
  4923. return httplib::Server::HandlerResponse::Unhandled;
  4924. });
  4925. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4926. res.set_content("Error", "text/html");
  4927. });
  4928. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4929. if (req.path == "/routing_handler") {
  4930. res.set_header("POST_ROUTING", "on");
  4931. }
  4932. });
  4933. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4934. res.set_content("Hello World!\n", "text/plain");
  4935. });
  4936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. {
  4944. #ifdef CPPHTTPLIB_SSL_ENABLED
  4945. SSLClient cli(HOST, PORT);
  4946. cli.enable_server_certificate_verification(false);
  4947. #else
  4948. Client cli(HOST, PORT);
  4949. #endif
  4950. auto res = cli.Get("/routing_handler");
  4951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4952. EXPECT_EQ(StatusCode::OK_200, res->status);
  4953. EXPECT_EQ("Routing Handler", res->body);
  4954. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4955. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4956. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4957. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4958. }
  4959. {
  4960. #ifdef CPPHTTPLIB_SSL_ENABLED
  4961. SSLClient cli(HOST, PORT);
  4962. cli.enable_server_certificate_verification(false);
  4963. #else
  4964. Client cli(HOST, PORT);
  4965. #endif
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("Hello World!\n", res->body);
  4970. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4971. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4972. }
  4973. {
  4974. #ifdef CPPHTTPLIB_SSL_ENABLED
  4975. SSLClient cli(HOST, PORT);
  4976. cli.enable_server_certificate_verification(false);
  4977. #else
  4978. Client cli(HOST, PORT);
  4979. #endif
  4980. auto res = cli.Get("/aaa");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4983. EXPECT_EQ("Error", res->body);
  4984. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4985. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4986. }
  4987. }
  4988. TEST(RequestHandlerTest, PreRequestHandler) {
  4989. auto route_path = "/user/:user";
  4990. Server svr;
  4991. svr.Get("/hi", [](const Request &, Response &res) {
  4992. res.set_content("hi", "text/plain");
  4993. });
  4994. svr.Get(route_path, [](const Request &req, Response &res) {
  4995. res.set_content(req.path_params.at("user"), "text/plain");
  4996. });
  4997. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4998. if (req.matched_route == route_path) {
  4999. auto user = req.path_params.at("user");
  5000. if (user != "john") {
  5001. res.status = StatusCode::Forbidden_403;
  5002. res.set_content("error", "text/html");
  5003. return Server::HandlerResponse::Handled;
  5004. }
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. {
  5017. auto res = cli.Get("/hi");
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. EXPECT_EQ("hi", res->body);
  5021. }
  5022. {
  5023. auto res = cli.Get("/user/john");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("john", res->body);
  5027. }
  5028. {
  5029. auto res = cli.Get("/user/invalid-user");
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5032. EXPECT_EQ("error", res->body);
  5033. }
  5034. }
  5035. // The pre-request handler must run before the request body is read, so a
  5036. // rejected request never forces the server to buffer a (potentially large)
  5037. // body. Here the posted body is larger than the payload limit: if the body
  5038. // were read first the server would answer 413, but because the pre-request
  5039. // handler runs first it answers 403 and the body is never read.
  5040. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5041. Server svr;
  5042. svr.set_payload_max_length(8);
  5043. auto handler_ran = false;
  5044. svr.Post("/reject", [&](const Request &req, Response &res) {
  5045. handler_ran = true;
  5046. res.set_content(req.body, "text/plain");
  5047. });
  5048. svr.Post("/accept", [](const Request &req, Response &res) {
  5049. res.set_content(req.body, "text/plain");
  5050. });
  5051. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5052. if (req.matched_route == "/reject") {
  5053. res.status = StatusCode::Forbidden_403;
  5054. res.set_content("denied", "text/plain");
  5055. return Server::HandlerResponse::Handled;
  5056. }
  5057. return Server::HandlerResponse::Unhandled;
  5058. });
  5059. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5060. auto se = detail::scope_exit([&] {
  5061. svr.stop();
  5062. thread.join();
  5063. ASSERT_FALSE(svr.is_running());
  5064. });
  5065. svr.wait_until_ready();
  5066. Client cli(HOST, PORT);
  5067. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5068. // rejects with 403 before the body is read, so 413 is never reached.
  5069. {
  5070. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5073. EXPECT_EQ("denied", res->body);
  5074. EXPECT_FALSE(handler_ran);
  5075. }
  5076. // An approved route still reads the body and enforces the payload limit.
  5077. {
  5078. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5081. }
  5082. }
  5083. TEST(UserDataTest, BasicOperations) {
  5084. httplib::UserData ud;
  5085. // Initially empty
  5086. EXPECT_FALSE(ud.has("key"));
  5087. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5088. // set and get
  5089. ud.set("key", 42);
  5090. EXPECT_TRUE(ud.has("key"));
  5091. auto *p = ud.get<int>("key");
  5092. ASSERT_NE(nullptr, p);
  5093. EXPECT_EQ(42, *p);
  5094. // Type mismatch → nullptr
  5095. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5096. // Overwrite with different type
  5097. ud.set("key", std::string("hello"));
  5098. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5099. auto *s = ud.get<std::string>("key");
  5100. ASSERT_NE(nullptr, s);
  5101. EXPECT_EQ("hello", *s);
  5102. // erase
  5103. ud.erase("key");
  5104. EXPECT_FALSE(ud.has("key"));
  5105. // clear
  5106. ud.set("a", 1);
  5107. ud.set("b", 2);
  5108. ud.clear();
  5109. EXPECT_FALSE(ud.has("a"));
  5110. EXPECT_FALSE(ud.has("b"));
  5111. }
  5112. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5113. struct AuthCtx {
  5114. std::string user_id;
  5115. };
  5116. Server svr;
  5117. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5118. res.user_data.set("auth", AuthCtx{"alice"});
  5119. return Server::HandlerResponse::Unhandled;
  5120. });
  5121. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5122. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5123. ASSERT_NE(nullptr, ctx);
  5124. res.set_content("Hello " + ctx->user_id, "text/plain");
  5125. });
  5126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5127. auto se = detail::scope_exit([&] {
  5128. svr.stop();
  5129. thread.join();
  5130. ASSERT_FALSE(svr.is_running());
  5131. });
  5132. svr.wait_until_ready();
  5133. Client cli(HOST, PORT);
  5134. auto res = cli.Get("/me");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. EXPECT_EQ("Hello alice", res->body);
  5138. }
  5139. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5140. struct RoleCtx {
  5141. std::string role;
  5142. };
  5143. Server svr;
  5144. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5145. res.user_data.set("role", RoleCtx{"admin"});
  5146. return Server::HandlerResponse::Unhandled;
  5147. });
  5148. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5149. auto *ctx = res.user_data.get<RoleCtx>("role");
  5150. ASSERT_NE(nullptr, ctx);
  5151. res.set_content(ctx->role, "text/plain");
  5152. });
  5153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5154. auto se = detail::scope_exit([&] {
  5155. svr.stop();
  5156. thread.join();
  5157. ASSERT_FALSE(svr.is_running());
  5158. });
  5159. svr.wait_until_ready();
  5160. Client cli(HOST, PORT);
  5161. auto res = cli.Get("/role");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. EXPECT_EQ("admin", res->body);
  5165. }
  5166. TEST(InvalidFormatTest, StatusCode) {
  5167. Server svr;
  5168. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5169. res.set_content("Hello World!\n", "text/plain");
  5170. res.status = 9999; // Status should be a three-digit code...
  5171. });
  5172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5173. auto se = detail::scope_exit([&] {
  5174. svr.stop();
  5175. thread.join();
  5176. ASSERT_FALSE(svr.is_running());
  5177. });
  5178. svr.wait_until_ready();
  5179. {
  5180. Client cli(HOST, PORT);
  5181. auto res = cli.Get("/hi");
  5182. ASSERT_FALSE(res);
  5183. }
  5184. }
  5185. TEST(URLFragmentTest, WithFragment) {
  5186. Server svr;
  5187. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5188. EXPECT_TRUE(req.target == "/hi");
  5189. });
  5190. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5191. auto se = detail::scope_exit([&] {
  5192. svr.stop();
  5193. thread.join();
  5194. ASSERT_FALSE(svr.is_running());
  5195. });
  5196. svr.wait_until_ready();
  5197. {
  5198. Client cli(HOST, PORT);
  5199. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5200. EXPECT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::OK_200, res->status);
  5202. res = cli.Get("/hi%23key1=val1=key2=val2");
  5203. EXPECT_TRUE(res);
  5204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5205. }
  5206. }
  5207. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5208. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5209. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5210. Server svr;
  5211. std::vector<std::string> targets;
  5212. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5213. targets.push_back(req.target);
  5214. });
  5215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. thread.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. Client cli(HOST, PORT);
  5223. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5224. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5225. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5226. // A '?' after the '#' belongs to the fragment, not to the query.
  5227. Request req;
  5228. req.method = "GET";
  5229. req.path = "/hi#f?x=1";
  5230. req.params.emplace("a", "1");
  5231. Response res;
  5232. auto error = Error::Success;
  5233. EXPECT_TRUE(cli.send(req, res, error));
  5234. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5235. "/hi?a=1"}),
  5236. targets);
  5237. }
  5238. TEST(HeaderWriter, SetHeaderWriter) {
  5239. Server svr;
  5240. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5241. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5242. return detail::write_headers(strm, hdrs);
  5243. });
  5244. svr.Get("/hi", [](const Request &req, Response &res) {
  5245. auto it = req.headers.find("CustomClientHeader");
  5246. EXPECT_TRUE(it != req.headers.end());
  5247. EXPECT_EQ(it->second, "CustomClientValue");
  5248. res.set_content("Hello World!\n", "text/plain");
  5249. });
  5250. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5251. auto se = detail::scope_exit([&] {
  5252. svr.stop();
  5253. thread.join();
  5254. ASSERT_FALSE(svr.is_running());
  5255. });
  5256. svr.wait_until_ready();
  5257. {
  5258. Client cli(HOST, PORT);
  5259. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5260. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5261. return detail::write_headers(strm, hdrs);
  5262. });
  5263. auto res = cli.Get("/hi");
  5264. EXPECT_TRUE(res);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. auto it = res->headers.find("CustomServerHeader");
  5267. EXPECT_TRUE(it != res->headers.end());
  5268. EXPECT_EQ(it->second, "CustomServerValue");
  5269. }
  5270. }
  5271. class ServerTest : public ::testing::Test {
  5272. protected:
  5273. ServerTest()
  5274. : cli_(HOST, PORT)
  5275. #ifdef CPPHTTPLIB_SSL_ENABLED
  5276. ,
  5277. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5278. #endif
  5279. {
  5280. #ifdef CPPHTTPLIB_SSL_ENABLED
  5281. cli_.enable_server_certificate_verification(false);
  5282. #endif
  5283. // Allow LARGE_DATA (100MB) responses
  5284. cli_.set_payload_max_length(200 * 1024 * 1024);
  5285. }
  5286. virtual void SetUp() {
  5287. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5288. svr_.set_payload_max_length(200 * 1024 * 1024);
  5289. svr_.set_mount_point("/", "./www");
  5290. svr_.set_mount_point("/mount", "./www2");
  5291. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5292. svr_.Get("/hi",
  5293. [&](const Request & /*req*/, Response &res) {
  5294. res.set_content("Hello World!", "text/plain");
  5295. })
  5296. .Get("/file_content",
  5297. [&](const Request & /*req*/, Response &res) {
  5298. res.set_file_content("./www/dir/test.html");
  5299. })
  5300. .Get("/file_content_with_content_type",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_file_content("./www/file", "text/plain");
  5303. })
  5304. .Get("/invalid_file_content",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. res.set_file_content("./www/dir/invalid_file_path");
  5307. })
  5308. .Get("/http_response_splitting",
  5309. [&](const Request & /*req*/, Response &res) {
  5310. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5311. EXPECT_EQ(0U, res.headers.size());
  5312. EXPECT_FALSE(res.has_header("a"));
  5313. res.set_header("a", "1\nSet-Cookie: a=1");
  5314. EXPECT_EQ(0U, res.headers.size());
  5315. EXPECT_FALSE(res.has_header("a"));
  5316. res.set_header("a", "1\rSet-Cookie: a=1");
  5317. EXPECT_EQ(0U, res.headers.size());
  5318. EXPECT_FALSE(res.has_header("a"));
  5319. res.set_header("a\r\nb", "0");
  5320. EXPECT_EQ(0U, res.headers.size());
  5321. EXPECT_FALSE(res.has_header("a"));
  5322. res.set_header("a\rb", "0");
  5323. EXPECT_EQ(0U, res.headers.size());
  5324. EXPECT_FALSE(res.has_header("a"));
  5325. res.set_header("a\nb", "0");
  5326. EXPECT_EQ(0U, res.headers.size());
  5327. EXPECT_FALSE(res.has_header("a"));
  5328. res.set_redirect("1\r\nSet-Cookie: a=1");
  5329. EXPECT_EQ(0U, res.headers.size());
  5330. EXPECT_FALSE(res.has_header("Location"));
  5331. })
  5332. .Get("/slow",
  5333. [&](const Request & /*req*/, Response &res) {
  5334. std::this_thread::sleep_for(std::chrono::seconds(4));
  5335. res.set_content("slow", "text/plain");
  5336. })
  5337. #if 0
  5338. .Post("/slowpost",
  5339. [&](const Request & /*req*/, Response &res) {
  5340. std::this_thread::sleep_for(std::chrono::seconds(2));
  5341. res.set_content("slow", "text/plain");
  5342. })
  5343. #endif
  5344. .Get("/remote_addr",
  5345. [&](const Request &req, Response &res) {
  5346. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5347. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5348. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5349. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5350. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5351. #endif
  5352. res.set_content(req.remote_addr, "text/plain");
  5353. })
  5354. .Get("/local_addr",
  5355. [&](const Request &req, Response &res) {
  5356. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5357. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5358. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5359. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5360. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5361. #endif
  5362. auto local_addr = req.local_addr;
  5363. auto local_port = std::to_string(req.local_port);
  5364. res.set_content(local_addr.append(":").append(local_port),
  5365. "text/plain");
  5366. })
  5367. .Get("/endwith%",
  5368. [&](const Request & /*req*/, Response &res) {
  5369. res.set_content("Hello World!", "text/plain");
  5370. })
  5371. .Get("/a\\+\\+b",
  5372. [&](const Request &req, Response &res) {
  5373. ASSERT_TRUE(req.has_param("a +b"));
  5374. auto val = req.get_param_value("a +b");
  5375. res.set_content(val, "text/plain");
  5376. })
  5377. .Get("/", [&](const Request & /*req*/,
  5378. Response &res) { res.set_redirect("/hi"); })
  5379. .Post("/1",
  5380. [](const Request & /*req*/, Response &res) {
  5381. res.set_redirect("/2", StatusCode::SeeOther_303);
  5382. })
  5383. .Get("/2",
  5384. [](const Request & /*req*/, Response &res) {
  5385. res.set_content("redirected.", "text/plain");
  5386. res.status = StatusCode::OK_200;
  5387. })
  5388. .Post("/person",
  5389. [&](const Request &req, Response &res) {
  5390. if (req.has_param("name") && req.has_param("note")) {
  5391. persons_[req.get_param_value("name")] =
  5392. req.get_param_value("note");
  5393. } else {
  5394. res.status = StatusCode::BadRequest_400;
  5395. }
  5396. })
  5397. .Put("/person",
  5398. [&](const Request &req, Response &res) {
  5399. if (req.has_param("name") && req.has_param("note")) {
  5400. persons_[req.get_param_value("name")] =
  5401. req.get_param_value("note");
  5402. } else {
  5403. res.status = StatusCode::BadRequest_400;
  5404. }
  5405. })
  5406. .Get("/person/(.*)",
  5407. [&](const Request &req, Response &res) {
  5408. string name = req.matches[1];
  5409. if (persons_.find(name) != persons_.end()) {
  5410. auto note = persons_[name];
  5411. res.set_content(note, "text/plain");
  5412. } else {
  5413. res.status = StatusCode::NotFound_404;
  5414. }
  5415. })
  5416. .Delete("/person",
  5417. [&](const Request &req, Response &res) {
  5418. if (req.has_param("name")) {
  5419. string name = req.get_param_value("name");
  5420. if (persons_.find(name) != persons_.end()) {
  5421. persons_.erase(name);
  5422. res.set_content("DELETED", "text/plain");
  5423. } else {
  5424. res.status = StatusCode::NotFound_404;
  5425. }
  5426. } else {
  5427. res.status = StatusCode::BadRequest_400;
  5428. }
  5429. })
  5430. .Post("/x-www-form-urlencoded-json",
  5431. [&](const Request &req, Response &res) {
  5432. auto json = req.get_param_value("json");
  5433. ASSERT_EQ(JSON_DATA, json);
  5434. res.set_content(json, "appliation/json");
  5435. res.status = StatusCode::OK_200;
  5436. })
  5437. .Get("/streamed-chunked",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. res.set_chunked_content_provider(
  5440. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5441. sink.os << "123";
  5442. sink.os << "456";
  5443. sink.os << "789";
  5444. sink.done();
  5445. return true;
  5446. });
  5447. })
  5448. .Get("/streamed-chunked-with-prohibited-trailer",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. auto i = new int(0);
  5451. // Declare both a prohibited trailer (Content-Length) and an
  5452. // allowed one
  5453. res.set_header("Trailer", "Content-Length, X-Allowed");
  5454. res.set_chunked_content_provider(
  5455. "text/plain",
  5456. [i](size_t /*offset*/, DataSink &sink) {
  5457. switch (*i) {
  5458. case 0: sink.os << "123"; break;
  5459. case 1: sink.os << "456"; break;
  5460. case 2: sink.os << "789"; break;
  5461. case 3: {
  5462. sink.done_with_trailer(
  5463. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5464. } break;
  5465. }
  5466. (*i)++;
  5467. return true;
  5468. },
  5469. [i](bool success) {
  5470. EXPECT_TRUE(success);
  5471. delete i;
  5472. });
  5473. })
  5474. .Get("/streamed-chunked2",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. auto i = new int(0);
  5477. res.set_chunked_content_provider(
  5478. "text/plain",
  5479. [i](size_t /*offset*/, DataSink &sink) {
  5480. switch (*i) {
  5481. case 0: sink.os << "123"; break;
  5482. case 1: sink.os << "456"; break;
  5483. case 2: sink.os << "789"; break;
  5484. case 3: sink.done(); break;
  5485. }
  5486. (*i)++;
  5487. return true;
  5488. },
  5489. [i](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete i;
  5492. });
  5493. })
  5494. .Get("/streamed-chunked-with-trailer",
  5495. [&](const Request & /*req*/, Response &res) {
  5496. auto i = new int(0);
  5497. res.set_header("Trailer", "Dummy1, Dummy2");
  5498. res.set_chunked_content_provider(
  5499. "text/plain",
  5500. [i](size_t /*offset*/, DataSink &sink) {
  5501. switch (*i) {
  5502. case 0: sink.os << "123"; break;
  5503. case 1: sink.os << "456"; break;
  5504. case 2: sink.os << "789"; break;
  5505. case 3: {
  5506. sink.done_with_trailer(
  5507. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5508. } break;
  5509. }
  5510. (*i)++;
  5511. return true;
  5512. },
  5513. [i](bool success) {
  5514. EXPECT_TRUE(success);
  5515. delete i;
  5516. });
  5517. })
  5518. .Get("/streamed",
  5519. [&](const Request & /*req*/, Response &res) {
  5520. res.set_content_provider(
  5521. 6, "text/plain",
  5522. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5523. sink.os << (offset < 3 ? "a" : "b");
  5524. return true;
  5525. });
  5526. })
  5527. .Get("/streamed-without-length",
  5528. [&](const Request & /*req*/, Response &res) {
  5529. auto data = new std::string("abcdefg");
  5530. res.set_content_provider(
  5531. "text/plain",
  5532. [data](size_t offset, DataSink &sink) {
  5533. if (offset < data->size()) {
  5534. sink.os << data->substr(offset);
  5535. }
  5536. sink.done();
  5537. return true;
  5538. },
  5539. [data](bool success) {
  5540. EXPECT_TRUE(success);
  5541. delete data;
  5542. });
  5543. })
  5544. .Get("/streamed-with-range",
  5545. [&](const Request &req, Response &res) {
  5546. auto data = new std::string("abcdefg");
  5547. // An explicit status keeps the server from picking the 206 it
  5548. // would otherwise choose for a ranged request, so the response
  5549. // is not a partial representation.
  5550. auto status = req.get_param_value("status");
  5551. if (status == "200") {
  5552. res.status = StatusCode::OK_200;
  5553. } else if (status == "403") {
  5554. res.status = StatusCode::Forbidden_403;
  5555. }
  5556. res.set_content_provider(
  5557. data->size(), "text/plain",
  5558. [data](size_t offset, size_t length, DataSink &sink) {
  5559. size_t DATA_CHUNK_SIZE = 4;
  5560. const auto &d = *data;
  5561. auto out_len =
  5562. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5563. auto ret =
  5564. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5565. EXPECT_TRUE(ret);
  5566. return true;
  5567. },
  5568. [data, &req](bool success) {
  5569. EXPECT_EQ(success, !req.has_param("error"));
  5570. delete data;
  5571. });
  5572. })
  5573. .Get("/streamed-cancel",
  5574. [&](const Request & /*req*/, Response &res) {
  5575. res.set_content_provider(
  5576. size_t(-1), "text/plain",
  5577. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5578. sink.os << "data_chunk";
  5579. return true;
  5580. });
  5581. })
  5582. .Get("/regex-with-delimiter",
  5583. [&](const Request &req, Response & /*res*/) {
  5584. ASSERT_TRUE(req.has_param("key"));
  5585. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5586. })
  5587. .Get("/with-range",
  5588. [&](const Request & /*req*/, Response &res) {
  5589. res.set_content("abcdefg", "text/plain");
  5590. })
  5591. .Get("/test-start-time",
  5592. [&](const Request &req, Response & /*res*/) {
  5593. EXPECT_NE(req.start_time_,
  5594. std::chrono::steady_clock::time_point::min());
  5595. })
  5596. .Get("/with-range-customized-response",
  5597. [&](const Request & /*req*/, Response &res) {
  5598. res.status = StatusCode::BadRequest_400;
  5599. res.set_content(JSON_DATA, "application/json");
  5600. })
  5601. .Post("/chunked",
  5602. [&](const Request &req, Response & /*res*/) {
  5603. EXPECT_EQ(req.body, "dechunked post body");
  5604. })
  5605. .Post("/large-chunked",
  5606. [&](const Request &req, Response & /*res*/) {
  5607. std::string expected(6 * 30 * 1024u, 'a');
  5608. EXPECT_EQ(req.body, expected);
  5609. })
  5610. .Post("/multipart",
  5611. [&](const Request &req, Response & /*res*/) {
  5612. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5613. req.form.get_field_count("text2") +
  5614. req.form.get_field_count("file3") +
  5615. req.form.get_field_count("file4"));
  5616. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5617. req.form.get_file_count("file2"));
  5618. ASSERT_TRUE(!req.form.has_file("???"));
  5619. ASSERT_TRUE(!req.form.has_field("???"));
  5620. ASSERT_TRUE(req.body.empty());
  5621. {
  5622. const auto &text = req.form.get_field("text1");
  5623. EXPECT_EQ("text default", text);
  5624. }
  5625. {
  5626. const auto &text = req.form.get_field("text2");
  5627. EXPECT_EQ("aωb", text);
  5628. }
  5629. {
  5630. const auto &file = req.form.get_file("file1");
  5631. EXPECT_EQ("hello.txt", file.filename);
  5632. EXPECT_EQ("text/plain", file.content_type);
  5633. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5634. }
  5635. {
  5636. const auto &file = req.form.get_file("file2");
  5637. EXPECT_EQ("world.json", file.filename);
  5638. EXPECT_EQ("application/json", file.content_type);
  5639. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5640. }
  5641. {
  5642. const auto &text = req.form.get_field("file3");
  5643. EXPECT_EQ(0u, text.size());
  5644. }
  5645. {
  5646. const auto &text = req.form.get_field("file4");
  5647. EXPECT_EQ(0u, text.size());
  5648. }
  5649. })
  5650. .Post("/multipart/multi_file_values",
  5651. [&](const Request &req, Response & /*res*/) {
  5652. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5653. req.form.get_field_count("multi_text1"));
  5654. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5655. ASSERT_TRUE(!req.form.has_file("???"));
  5656. ASSERT_TRUE(!req.form.has_field("???"));
  5657. ASSERT_TRUE(req.body.empty());
  5658. {
  5659. const auto &text = req.form.get_field("text");
  5660. EXPECT_EQ("default text", text);
  5661. }
  5662. {
  5663. const auto &text1_values = req.form.get_fields("multi_text1");
  5664. EXPECT_EQ(2u, text1_values.size());
  5665. EXPECT_EQ("aaaaa", text1_values[0]);
  5666. EXPECT_EQ("bbbbb", text1_values[1]);
  5667. }
  5668. {
  5669. const auto &file1_values = req.form.get_files("multi_file1");
  5670. EXPECT_EQ(2u, file1_values.size());
  5671. auto file1 = file1_values[0];
  5672. EXPECT_EQ(file1.filename, "hello.txt");
  5673. EXPECT_EQ(file1.content_type, "text/plain");
  5674. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5675. auto file2 = file1_values[1];
  5676. EXPECT_EQ(file2.filename, "world.json");
  5677. EXPECT_EQ(file2.content_type, "application/json");
  5678. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5679. }
  5680. })
  5681. .Post("/empty",
  5682. [&](const Request &req, Response &res) {
  5683. EXPECT_EQ(req.body, "");
  5684. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5685. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5686. res.set_content("empty", "text/plain");
  5687. })
  5688. .Post("/empty-no-content-type",
  5689. [&](const Request &req, Response &res) {
  5690. EXPECT_EQ(req.body, "");
  5691. EXPECT_FALSE(req.has_header("Content-Type"));
  5692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5693. res.set_content("empty-no-content-type", "text/plain");
  5694. })
  5695. .Post("/path-only",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("path-only", "text/plain");
  5701. })
  5702. .Post("/path-headers-only",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "");
  5705. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5706. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5707. EXPECT_EQ("world", req.get_header_value("hello"));
  5708. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5709. res.set_content("path-headers-only", "text/plain");
  5710. })
  5711. .Post("/post-large",
  5712. [&](const Request &req, Response &res) {
  5713. EXPECT_EQ(req.body, LARGE_DATA);
  5714. res.set_content(req.body, "text/plain");
  5715. })
  5716. .Post("/post-loopback",
  5717. [&](const Request &, Response &res,
  5718. ContentReader const &content_reader) {
  5719. std::string body;
  5720. content_reader([&](const char *data, size_t data_length) {
  5721. body.append(data, data_length);
  5722. return true;
  5723. });
  5724. res.set_content(body, "text/plain");
  5725. })
  5726. .Put("/put-loopback",
  5727. [&](const Request &, Response &res,
  5728. ContentReader const &content_reader) {
  5729. std::string body;
  5730. content_reader([&](const char *data, size_t data_length) {
  5731. body.append(data, data_length);
  5732. return true;
  5733. });
  5734. res.set_content(body, "text/plain");
  5735. })
  5736. .Patch("/patch-loopback",
  5737. [&](const Request &, Response &res,
  5738. ContentReader const &content_reader) {
  5739. std::string body;
  5740. content_reader([&](const char *data, size_t data_length) {
  5741. body.append(data, data_length);
  5742. return true;
  5743. });
  5744. res.set_content(body, "text/plain");
  5745. })
  5746. .Put("/empty-no-content-type",
  5747. [&](const Request &req, Response &res) {
  5748. EXPECT_EQ(req.body, "");
  5749. EXPECT_FALSE(req.has_header("Content-Type"));
  5750. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5751. res.set_content("empty-no-content-type", "text/plain");
  5752. })
  5753. .Put("/put",
  5754. [&](const Request &req, Response &res) {
  5755. EXPECT_EQ(req.body, "PUT");
  5756. res.set_content(req.body, "text/plain");
  5757. })
  5758. .Put("/put-large",
  5759. [&](const Request &req, Response &res) {
  5760. EXPECT_EQ(req.body, LARGE_DATA);
  5761. res.set_content(req.body, "text/plain");
  5762. })
  5763. .Patch("/patch",
  5764. [&](const Request &req, Response &res) {
  5765. EXPECT_EQ(req.body, "PATCH");
  5766. res.set_content(req.body, "text/plain");
  5767. })
  5768. .Delete("/delete",
  5769. [&](const Request & /*req*/, Response &res) {
  5770. res.set_content("DELETE", "text/plain");
  5771. })
  5772. .Delete("/delete-body",
  5773. [&](const Request &req, Response &res) {
  5774. EXPECT_EQ(req.body, "content");
  5775. res.set_content(req.body, "text/plain");
  5776. })
  5777. .Options(R"(\*)",
  5778. [&](const Request & /*req*/, Response &res) {
  5779. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5780. })
  5781. .CustomRoute("PROPFIND", "/dav/:id",
  5782. [&](const Request &req, Response &res) {
  5783. res.set_header("x-body-size",
  5784. std::to_string(req.body.size()));
  5785. res.set_header("x-matched-route", req.matched_route);
  5786. res.set_header("x-dav-id", req.path_params.at("id"));
  5787. res.status = StatusCode::MultiStatus_207;
  5788. res.set_content(req.body, "application/xml");
  5789. })
  5790. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5791. [&](const Request &req, Response &res) {
  5792. res.set_header("x-dav-match", req.matches[1]);
  5793. res.status = StatusCode::MultiStatus_207;
  5794. })
  5795. .CustomRoute("MKCOL", "/dav-mkcol",
  5796. [&](const Request &req, Response &res) {
  5797. EXPECT_TRUE(req.body.empty());
  5798. res.status = StatusCode::Created_201;
  5799. })
  5800. .CustomRoute(
  5801. "REPORT", "/dav-report",
  5802. [&](const Request & /*req*/, Response &res,
  5803. const ContentReader &content_reader) {
  5804. std::string body;
  5805. content_reader([&](const char *data, size_t data_length) {
  5806. body.append(data, data_length);
  5807. return true;
  5808. });
  5809. res.set_header("x-body-size", std::to_string(body.size()));
  5810. res.status = StatusCode::MultiStatus_207;
  5811. res.set_content(body, "application/xml");
  5812. })
  5813. .Get("/request-target",
  5814. [&](const Request &req, Response & /*res*/) {
  5815. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5816. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5817. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5818. })
  5819. .Get("/long-query-value",
  5820. [&](const Request &req, Response & /*res*/) {
  5821. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5822. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5823. })
  5824. .Get("/too-long-query-value",
  5825. [&](const Request &req, Response & /*res*/) {
  5826. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5827. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5828. })
  5829. .Get("/array-param",
  5830. [&](const Request &req, Response & /*res*/) {
  5831. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5832. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5833. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5834. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5835. })
  5836. .Get("/array-param-values",
  5837. [&](const Request &req, Response & /*res*/) {
  5838. auto values = req.get_param_values("array");
  5839. EXPECT_EQ(3u, values.size());
  5840. EXPECT_EQ("value1", values[0]);
  5841. EXPECT_EQ("value2", values[1]);
  5842. EXPECT_EQ("value3", values[2]);
  5843. auto empty = req.get_param_values("nonexistent");
  5844. EXPECT_TRUE(empty.empty());
  5845. })
  5846. .Post("/validate-no-multiple-headers",
  5847. [&](const Request &req, Response & /*res*/) {
  5848. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5849. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5850. })
  5851. .Post("/content_receiver",
  5852. [&](const Request &req, Response &res,
  5853. const ContentReader &content_reader) {
  5854. if (req.is_multipart_form_data()) {
  5855. std::vector<FormData> items;
  5856. content_reader(
  5857. [&](const FormData &file) {
  5858. items.push_back(file);
  5859. return true;
  5860. },
  5861. [&](const char *data, size_t data_length) {
  5862. items.back().content.append(data, data_length);
  5863. return true;
  5864. });
  5865. EXPECT_EQ(5u, items.size());
  5866. {
  5867. const auto &file = get_file_value(items, "text1");
  5868. EXPECT_TRUE(file.filename.empty());
  5869. EXPECT_EQ("text default", file.content);
  5870. }
  5871. {
  5872. const auto &file = get_file_value(items, "text2");
  5873. EXPECT_TRUE(file.filename.empty());
  5874. EXPECT_EQ("aωb", file.content);
  5875. }
  5876. {
  5877. const auto &file = get_file_value(items, "file1");
  5878. EXPECT_EQ("hello.txt", file.filename);
  5879. EXPECT_EQ("text/plain", file.content_type);
  5880. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5881. }
  5882. {
  5883. const auto &file = get_file_value(items, "file2");
  5884. EXPECT_EQ("world.json", file.filename);
  5885. EXPECT_EQ("application/json", file.content_type);
  5886. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5887. }
  5888. {
  5889. const auto &file = get_file_value(items, "file3");
  5890. EXPECT_TRUE(file.filename.empty());
  5891. EXPECT_EQ("application/octet-stream", file.content_type);
  5892. EXPECT_EQ(0u, file.content.size());
  5893. }
  5894. } else {
  5895. std::string body;
  5896. content_reader([&](const char *data, size_t data_length) {
  5897. EXPECT_EQ(7U, data_length);
  5898. body.append(data, data_length);
  5899. return true;
  5900. });
  5901. EXPECT_EQ(body, "content");
  5902. res.set_content(body, "text/plain");
  5903. }
  5904. })
  5905. .Put("/content_receiver",
  5906. [&](const Request & /*req*/, Response &res,
  5907. const ContentReader &content_reader) {
  5908. std::string body;
  5909. content_reader([&](const char *data, size_t data_length) {
  5910. body.append(data, data_length);
  5911. return true;
  5912. });
  5913. EXPECT_EQ(body, "content");
  5914. res.set_content(body, "text/plain");
  5915. })
  5916. .Patch("/content_receiver",
  5917. [&](const Request & /*req*/, Response &res,
  5918. const ContentReader &content_reader) {
  5919. std::string body;
  5920. content_reader([&](const char *data, size_t data_length) {
  5921. body.append(data, data_length);
  5922. return true;
  5923. });
  5924. EXPECT_EQ(body, "content");
  5925. res.set_content(body, "text/plain");
  5926. })
  5927. .Post("/query-string-and-body",
  5928. [&](const Request &req, Response & /*res*/) {
  5929. ASSERT_TRUE(req.has_param("key"));
  5930. EXPECT_EQ(req.get_param_value("key"), "value");
  5931. EXPECT_EQ(req.body, "content");
  5932. })
  5933. .Get("/last-request",
  5934. [&](const Request &req, Response & /*res*/) {
  5935. EXPECT_EQ("close", req.get_header_value("Connection"));
  5936. })
  5937. .Get(R"(/redirect/(\d+))",
  5938. [&](const Request &req, Response &res) {
  5939. auto num = std::stoi(req.matches[1]) + 1;
  5940. std::string url = "/redirect/" + std::to_string(num);
  5941. res.set_redirect(url);
  5942. })
  5943. .Post("/binary",
  5944. [&](const Request &req, Response &res) {
  5945. EXPECT_EQ(4U, req.body.size());
  5946. EXPECT_EQ("application/octet-stream",
  5947. req.get_header_value("Content-Type"));
  5948. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5949. res.set_content(req.body, "application/octet-stream");
  5950. })
  5951. .Put("/binary",
  5952. [&](const Request &req, Response &res) {
  5953. EXPECT_EQ(4U, req.body.size());
  5954. EXPECT_EQ("application/octet-stream",
  5955. req.get_header_value("Content-Type"));
  5956. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5957. res.set_content(req.body, "application/octet-stream");
  5958. })
  5959. .Patch("/binary",
  5960. [&](const Request &req, Response &res) {
  5961. EXPECT_EQ(4U, req.body.size());
  5962. EXPECT_EQ("application/octet-stream",
  5963. req.get_header_value("Content-Type"));
  5964. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5965. res.set_content(req.body, "application/octet-stream");
  5966. })
  5967. .Delete("/binary",
  5968. [&](const Request &req, Response &res) {
  5969. EXPECT_EQ(4U, req.body.size());
  5970. EXPECT_EQ("application/octet-stream",
  5971. req.get_header_value("Content-Type"));
  5972. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5973. res.set_content(req.body, "application/octet-stream");
  5974. })
  5975. .Get("/issue1772",
  5976. [&](const Request & /*req*/, Response &res) {
  5977. res.status = 401;
  5978. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5979. })
  5980. .Delete("/issue609",
  5981. [](const httplib::Request &, httplib::Response &res,
  5982. const httplib::ContentReader &) {
  5983. res.set_content("ok", "text/plain");
  5984. })
  5985. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5986. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5987. .Get("/compress",
  5988. [&](const Request & /*req*/, Response &res) {
  5989. res.set_content(
  5990. "12345678901234567890123456789012345678901234567890123456789"
  5991. "01234567890123456789012345678901234567890",
  5992. "text/plain");
  5993. })
  5994. .Get("/compress-with-charset",
  5995. [&](const Request & /*req*/, Response &res) {
  5996. res.set_content(
  5997. "12345678901234567890123456789012345678901234567890123456789"
  5998. "01234567890123456789012345678901234567890",
  5999. "application/json; charset=utf-8");
  6000. })
  6001. .Get("/nocompress",
  6002. [&](const Request & /*req*/, Response &res) {
  6003. res.set_content(
  6004. "12345678901234567890123456789012345678901234567890123456789"
  6005. "01234567890123456789012345678901234567890",
  6006. "application/octet-stream");
  6007. })
  6008. .Post("/compress-multipart",
  6009. [&](const Request &req, Response & /*res*/) {
  6010. EXPECT_EQ(2u, req.form.fields.size());
  6011. ASSERT_TRUE(!req.form.has_field("???"));
  6012. {
  6013. const auto &text = req.form.get_field("key1");
  6014. EXPECT_EQ("test", text);
  6015. }
  6016. {
  6017. const auto &text = req.form.get_field("key2");
  6018. EXPECT_EQ("--abcdefg123", text);
  6019. }
  6020. })
  6021. #endif
  6022. ;
  6023. persons_["john"] = "programmer";
  6024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6025. svr_.wait_until_ready();
  6026. }
  6027. virtual void TearDown() {
  6028. svr_.stop();
  6029. if (!request_threads_.empty()) {
  6030. std::this_thread::sleep_for(std::chrono::seconds(1));
  6031. for (auto &t : request_threads_) {
  6032. t.join();
  6033. }
  6034. }
  6035. t_.join();
  6036. }
  6037. map<string, string> persons_;
  6038. #ifdef CPPHTTPLIB_SSL_ENABLED
  6039. SSLClient cli_;
  6040. SSLServer svr_;
  6041. #else
  6042. Client cli_;
  6043. Server svr_;
  6044. #endif
  6045. thread t_;
  6046. std::vector<thread> request_threads_;
  6047. };
  6048. TEST_F(ServerTest, GetMethod200) {
  6049. auto res = cli_.Get("/hi");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ("HTTP/1.1", res->version);
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. EXPECT_EQ("OK", res->reason);
  6054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6055. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6056. EXPECT_EQ("Hello World!", res->body);
  6057. }
  6058. TEST_F(ServerTest, GetEmptyFile) {
  6059. auto res = cli_.Get("/empty_file");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6063. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6064. EXPECT_EQ("", res->body);
  6065. }
  6066. TEST_F(ServerTest, GetFileContent) {
  6067. auto res = cli_.Get("/file_content");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6071. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6072. EXPECT_EQ("test.html", res->body);
  6073. }
  6074. TEST_F(ServerTest, GetFileContentWithRange) {
  6075. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6078. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6079. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6080. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6081. EXPECT_EQ("est", res->body);
  6082. }
  6083. TEST_F(ServerTest, GetFileContentWithContentType) {
  6084. auto res = cli_.Get("/file_content_with_content_type");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6089. EXPECT_EQ("file\n", res->body);
  6090. }
  6091. TEST_F(ServerTest, GetInvalidFileContent) {
  6092. auto res = cli_.Get("/invalid_file_content");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6095. }
  6096. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6097. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ("HTTP/1.1", res->version);
  6100. EXPECT_EQ(StatusCode::OK_200, res->status);
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6103. EXPECT_EQ("Hello World!", res->body);
  6104. }
  6105. TEST_F(ServerTest, GetMethod302) {
  6106. auto res = cli_.Get("/");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::Found_302, res->status);
  6109. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6110. }
  6111. TEST_F(ServerTest, GetMethod302Redirect) {
  6112. cli_.set_follow_location(true);
  6113. auto res = cli_.Get("/");
  6114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6115. EXPECT_EQ(StatusCode::OK_200, res->status);
  6116. EXPECT_EQ("Hello World!", res->body);
  6117. EXPECT_EQ("/hi", res->location);
  6118. }
  6119. TEST_F(ServerTest, GetMethod404) {
  6120. auto res = cli_.Get("/invalid");
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6123. }
  6124. TEST_F(ServerTest, HeadMethod200) {
  6125. auto res = cli_.Head("/hi");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::OK_200, res->status);
  6128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. EXPECT_TRUE(res->body.empty());
  6130. }
  6131. TEST_F(ServerTest, HeadMethod200Static) {
  6132. auto res = cli_.Head("/mount/dir/index.html");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6136. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6137. EXPECT_TRUE(res->body.empty());
  6138. }
  6139. TEST_F(ServerTest, HeadMethod404) {
  6140. auto res = cli_.Head("/invalid");
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6143. EXPECT_TRUE(res->body.empty());
  6144. }
  6145. TEST_F(ServerTest, GetMethodPersonJohn) {
  6146. auto res = cli_.Get("/person/john");
  6147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6148. EXPECT_EQ(StatusCode::OK_200, res->status);
  6149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("programmer", res->body);
  6151. }
  6152. TEST_F(ServerTest, PostMethod1) {
  6153. auto res = cli_.Get("/person/john1");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6156. res = cli_.Post("/person", "name=john1&note=coder",
  6157. "application/x-www-form-urlencoded");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. res = cli_.Get("/person/john1");
  6161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6162. ASSERT_EQ(StatusCode::OK_200, res->status);
  6163. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6164. ASSERT_EQ("coder", res->body);
  6165. }
  6166. TEST_F(ServerTest, PostMethod2) {
  6167. auto res = cli_.Get("/person/john2");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6170. Params params;
  6171. params.emplace("name", "john2");
  6172. params.emplace("note", "coder");
  6173. res = cli_.Post("/person", params);
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. res = cli_.Get("/person/john2");
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. ASSERT_EQ(StatusCode::OK_200, res->status);
  6179. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6180. ASSERT_EQ("coder", res->body);
  6181. }
  6182. TEST_F(ServerTest, PutMethod3) {
  6183. auto res = cli_.Get("/person/john3");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6186. Params params;
  6187. params.emplace("name", "john3");
  6188. params.emplace("note", "coder");
  6189. res = cli_.Put("/person", params);
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. ASSERT_EQ(StatusCode::OK_200, res->status);
  6192. res = cli_.Get("/person/john3");
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6196. ASSERT_EQ("coder", res->body);
  6197. }
  6198. TEST_F(ServerTest, DeleteMethod1) {
  6199. auto res = cli_.Get("/person/john4");
  6200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6201. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6202. Params params;
  6203. params.emplace("name", "john4");
  6204. params.emplace("note", "coder");
  6205. res = cli_.Post("/person", params);
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. res = cli_.Get("/person/john4");
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. ASSERT_EQ(StatusCode::OK_200, res->status);
  6211. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6212. ASSERT_EQ("coder", res->body);
  6213. Params delete_params;
  6214. delete_params.emplace("name", "john4");
  6215. res = cli_.Delete("/person", delete_params);
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. ASSERT_EQ(StatusCode::OK_200, res->status);
  6218. ASSERT_EQ("DELETED", res->body);
  6219. res = cli_.Get("/person/john4");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6222. }
  6223. TEST_F(ServerTest, DeleteMethod2) {
  6224. auto res = cli_.Get("/person/john5");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6227. Params params;
  6228. params.emplace("name", "john5");
  6229. params.emplace("note", "developer");
  6230. res = cli_.Post("/person", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. res = cli_.Get("/person/john5");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. ASSERT_EQ(StatusCode::OK_200, res->status);
  6236. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6237. ASSERT_EQ("developer", res->body);
  6238. Params delete_params;
  6239. delete_params.emplace("name", "john5");
  6240. Headers headers;
  6241. headers.emplace("Custom-Header", "test-value");
  6242. res = cli_.Delete("/person", headers, delete_params);
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("DELETED", res->body);
  6246. res = cli_.Get("/person/john5");
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6249. }
  6250. TEST_F(ServerTest, DeleteMethod3) {
  6251. auto res = cli_.Get("/person/john6");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6254. Params params;
  6255. params.emplace("name", "john6");
  6256. params.emplace("note", "tester");
  6257. res = cli_.Post("/person", params);
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. ASSERT_EQ(StatusCode::OK_200, res->status);
  6260. res = cli_.Get("/person/john6");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6264. ASSERT_EQ("tester", res->body);
  6265. Params delete_params;
  6266. delete_params.emplace("name", "john6");
  6267. Headers headers;
  6268. headers.emplace("Custom-Header", "test-value");
  6269. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. ASSERT_EQ(StatusCode::OK_200, res->status);
  6272. ASSERT_EQ("DELETED", res->body);
  6273. res = cli_.Get("/person/john6");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6276. }
  6277. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6278. Params params;
  6279. params.emplace("json", JSON_DATA);
  6280. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. ASSERT_EQ(StatusCode::OK_200, res->status);
  6283. ASSERT_EQ(JSON_DATA, res->body);
  6284. }
  6285. TEST_F(ServerTest, PostEmptyContent) {
  6286. auto res = cli_.Post("/empty", "", "text/plain");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. ASSERT_EQ(StatusCode::OK_200, res->status);
  6289. ASSERT_EQ("empty", res->body);
  6290. }
  6291. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6292. auto res = cli_.Post("/empty-no-content-type");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. ASSERT_EQ(StatusCode::OK_200, res->status);
  6295. ASSERT_EQ("empty-no-content-type", res->body);
  6296. }
  6297. TEST_F(ServerTest, PostPathOnly) {
  6298. auto res = cli_.Post("/path-only");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. ASSERT_EQ(StatusCode::OK_200, res->status);
  6301. ASSERT_EQ("path-only", res->body);
  6302. }
  6303. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6304. auto res = cli_.Post("/path-headers-only",
  6305. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. ASSERT_EQ(StatusCode::OK_200, res->status);
  6308. ASSERT_EQ("path-headers-only", res->body);
  6309. }
  6310. TEST_F(ServerTest, PostLarge) {
  6311. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. ASSERT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ(LARGE_DATA, res->body);
  6315. }
  6316. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6317. auto res = cli_.Put("/empty-no-content-type");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. ASSERT_EQ(StatusCode::OK_200, res->status);
  6320. ASSERT_EQ("empty-no-content-type", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDir) {
  6323. auto res = cli_.Get("/dir/");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::OK_200, res->status);
  6326. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6327. auto body = R"(<html>
  6328. <head>
  6329. </head>
  6330. <body>
  6331. <a href="/dir/test.html">Test</a>
  6332. <a href="/hi">hi</a>
  6333. </body>
  6334. </html>
  6335. )";
  6336. EXPECT_EQ(body, res->body);
  6337. }
  6338. TEST_F(ServerTest, GetMethodDirTest) {
  6339. auto res = cli_.Get("/dir/test.html");
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. EXPECT_EQ(StatusCode::OK_200, res->status);
  6342. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6343. EXPECT_EQ("test.html", res->body);
  6344. }
  6345. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6346. auto res = cli_.Get("/dir/../dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodInvalidPath) {
  6351. auto res = cli_.Get("/dir/../test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6356. auto res = cli_.Get("/../www/dir/test.html");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6359. }
  6360. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6361. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST_F(ServerTest, GetMethodDirMountTest) {
  6366. auto res = cli_.Get("/mount/dir/test.html");
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6370. EXPECT_EQ("test.html", res->body);
  6371. }
  6372. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6373. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6376. }
  6377. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6378. auto res = cli_.Get("/mount/dir/../test.html");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6381. }
  6382. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6383. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6386. }
  6387. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6388. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6391. }
  6392. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6393. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6396. }
  6397. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6398. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6401. }
  6402. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6403. auto res = cli_.Get("/mount/dir");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6406. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6407. }
  6408. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6409. auto res = cli_.Get("//dir");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6412. EXPECT_FALSE(res->has_header("Location"));
  6413. }
  6414. TEST_F(ServerTest, PostMethod303) {
  6415. auto res = cli_.Post("/1", "body", "text/plain");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6418. EXPECT_EQ("/2", res->get_header_value("Location"));
  6419. }
  6420. TEST_F(ServerTest, PostMethod303Redirect) {
  6421. cli_.set_follow_location(true);
  6422. auto res = cli_.Post("/1", "body", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::OK_200, res->status);
  6425. EXPECT_EQ("redirected.", res->body);
  6426. EXPECT_EQ("/2", res->location);
  6427. }
  6428. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6429. auto res = cli_.Get("/dir/test.abcde");
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::OK_200, res->status);
  6432. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6433. EXPECT_EQ("abcde", res->body);
  6434. }
  6435. TEST_F(ServerTest, StaticFileRange) {
  6436. auto res =
  6437. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6440. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6444. EXPECT_EQ(std::string("cd"), res->body);
  6445. }
  6446. TEST_F(ServerTest, StaticFileRanges) {
  6447. auto res = cli_.Get("/dir/test.abcde",
  6448. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6451. EXPECT_TRUE(
  6452. res->get_header_value("Content-Type")
  6453. .find(
  6454. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6455. 0);
  6456. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6457. }
  6458. TEST_F(ServerTest, StaticFileRangeHead) {
  6459. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6462. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6463. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6464. EXPECT_EQ(true, res->has_header("Content-Range"));
  6465. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6466. }
  6467. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6468. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6472. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6473. EXPECT_EQ(true, res->has_header("Content-Range"));
  6474. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6475. res->get_header_value("Content-Range"));
  6476. EXPECT_EQ("LAST\n", res->body);
  6477. }
  6478. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6479. auto res =
  6480. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6484. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6485. EXPECT_EQ(true, res->has_header("Content-Range"));
  6486. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6487. }
  6488. TEST_F(ServerTest, StaticFileBigFile) {
  6489. auto res = cli_.Get("/dir/1MB.txt");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6494. }
  6495. TEST_F(ServerTest, InvalidBaseDirMount) {
  6496. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6497. }
  6498. TEST_F(ServerTest, Binary) {
  6499. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6500. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6501. "application/octet-stream");
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. ASSERT_EQ(StatusCode::OK_200, res->status);
  6504. ASSERT_EQ(4U, res->body.size());
  6505. res = cli_.Put("/binary", binary.data(), binary.size(),
  6506. "application/octet-stream");
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. ASSERT_EQ(StatusCode::OK_200, res->status);
  6509. ASSERT_EQ(4U, res->body.size());
  6510. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6511. "application/octet-stream");
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. ASSERT_EQ(StatusCode::OK_200, res->status);
  6514. ASSERT_EQ(4U, res->body.size());
  6515. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6516. "application/octet-stream");
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. ASSERT_EQ(StatusCode::OK_200, res->status);
  6519. ASSERT_EQ(4U, res->body.size());
  6520. }
  6521. TEST_F(ServerTest, BinaryString) {
  6522. auto binary = std::string("\x00\x01\x02\x03", 4);
  6523. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. ASSERT_EQ(StatusCode::OK_200, res->status);
  6526. ASSERT_EQ(4U, res->body.size());
  6527. res = cli_.Put("/binary", binary, "application/octet-stream");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. ASSERT_EQ(StatusCode::OK_200, res->status);
  6530. ASSERT_EQ(4U, res->body.size());
  6531. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6533. ASSERT_EQ(StatusCode::OK_200, res->status);
  6534. ASSERT_EQ(4U, res->body.size());
  6535. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. ASSERT_EQ(StatusCode::OK_200, res->status);
  6538. ASSERT_EQ(4U, res->body.size());
  6539. }
  6540. TEST_F(ServerTest, EmptyRequest) {
  6541. auto res = cli_.Get("");
  6542. ASSERT_TRUE(!res);
  6543. EXPECT_EQ(Error::Connection, res.error());
  6544. }
  6545. TEST_F(ServerTest, LongRequest) {
  6546. std::string request;
  6547. for (size_t i = 0; i < 545; i++) {
  6548. request += "/TooLongRequest";
  6549. }
  6550. request += "OK";
  6551. auto res = cli_.Get(request.c_str());
  6552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6554. }
  6555. TEST_F(ServerTest, TooLongRequest) {
  6556. std::string request;
  6557. for (size_t i = 0; i < 546; i++) {
  6558. request += "/TooLongRequest";
  6559. }
  6560. request += "_NG";
  6561. auto start = std::chrono::high_resolution_clock::now();
  6562. cli_.set_keep_alive(true);
  6563. auto res = cli_.Get(request.c_str());
  6564. auto end = std::chrono::high_resolution_clock::now();
  6565. auto elapsed =
  6566. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6567. .count();
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6570. EXPECT_LE(elapsed, 1000);
  6571. EXPECT_EQ("close", res->get_header_value("Connection"));
  6572. EXPECT_FALSE(cli_.is_socket_open());
  6573. }
  6574. TEST_F(ServerTest, AlmostTooLongRequest) {
  6575. // test for #2046 - URI length check shouldn't include other content on req
  6576. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6577. // leading /, space, HTTP/1.1)
  6578. std::string request =
  6579. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6580. auto res = cli_.Get(request.c_str());
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6583. }
  6584. TEST_F(ServerTest, LongHeader) {
  6585. Request req;
  6586. req.method = "GET";
  6587. req.path = "/hi";
  6588. std::string host_and_port;
  6589. host_and_port += HOST;
  6590. host_and_port += ":";
  6591. host_and_port += std::to_string(PORT);
  6592. req.headers.emplace("Host", host_and_port.c_str());
  6593. req.headers.emplace("Accept", "*/*");
  6594. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6595. req.headers.emplace(
  6596. "Header-Name",
  6597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@");
  6626. auto res = std::make_shared<Response>();
  6627. auto error = Error::Success;
  6628. auto ret = cli_.send(req, *res, error);
  6629. ASSERT_TRUE(ret);
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. }
  6632. TEST_F(ServerTest, LongQueryValue) {
  6633. auto start = std::chrono::high_resolution_clock::now();
  6634. cli_.set_keep_alive(true);
  6635. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6636. auto end = std::chrono::high_resolution_clock::now();
  6637. auto elapsed =
  6638. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6639. .count();
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6642. EXPECT_LE(elapsed, 1000);
  6643. EXPECT_EQ("close", res->get_header_value("Connection"));
  6644. EXPECT_FALSE(cli_.is_socket_open());
  6645. }
  6646. TEST_F(ServerTest, TooLongQueryValue) {
  6647. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6648. ASSERT_FALSE(res);
  6649. EXPECT_EQ(Error::Read, res.error());
  6650. }
  6651. TEST_F(ServerTest, TooLongHeader) {
  6652. Request req;
  6653. req.method = "GET";
  6654. req.path = "/hi";
  6655. std::string host_and_port;
  6656. host_and_port += HOST;
  6657. host_and_port += ":";
  6658. host_and_port += std::to_string(PORT);
  6659. req.headers.emplace("Host", host_and_port.c_str());
  6660. req.headers.emplace("Accept", "*/*");
  6661. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6662. req.headers.emplace(
  6663. "Header-Name",
  6664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6692. "@@@@@@@@@@@@@@@@@");
  6693. auto res = std::make_shared<Response>();
  6694. auto error = Error::Success;
  6695. auto ret = cli_.send(req, *res, error);
  6696. ASSERT_TRUE(ret);
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. }
  6699. TEST_F(ServerTest, HeaderCountAtLimit) {
  6700. // Test with headers just under the 100 limit
  6701. httplib::Headers headers;
  6702. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6703. // This should keep us just under the 100 header limit
  6704. for (int i = 0; i < 95; i++) {
  6705. std::string name = "X-Test-Header-" + std::to_string(i);
  6706. std::string value = "value" + std::to_string(i);
  6707. headers.emplace(name, value);
  6708. }
  6709. // This should work fine as we're under the limit
  6710. auto res = cli_.Get("/hi", headers);
  6711. EXPECT_TRUE(res);
  6712. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6713. }
  6714. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6715. // Test with many headers to exceed the 100 limit
  6716. httplib::Headers headers;
  6717. // Add 150 headers to definitely exceed the 100 limit
  6718. for (int i = 0; i < 150; i++) {
  6719. std::string name = "X-Test-Header-" + std::to_string(i);
  6720. std::string value = "value" + std::to_string(i);
  6721. headers.emplace(name, value);
  6722. }
  6723. // This should fail due to exceeding header count limit
  6724. cli_.set_keep_alive(true);
  6725. auto res = cli_.Get("/hi", headers);
  6726. // The server should respond with 400 Bad Request
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ("close", res->get_header_value("Connection"));
  6730. EXPECT_FALSE(cli_.is_socket_open());
  6731. }
  6732. TEST_F(ServerTest, PercentEncoding) {
  6733. auto res = cli_.Get("/e%6edwith%");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, PercentEncodingUnicode) {
  6738. auto res = cli_.Get("/e%u006edwith%");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::OK_200, res->status);
  6741. }
  6742. TEST_F(ServerTest, InvalidPercentEncoding) {
  6743. auto res = cli_.Get("/%endwith%");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6746. }
  6747. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6748. auto res = cli_.Get("/%uendwith%");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6751. }
  6752. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6753. auto res = cli_.Get("/hello?aaa=bbb%");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6756. }
  6757. TEST_F(ServerTest, PlusSignEncoding) {
  6758. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ("a +b", res->body);
  6762. }
  6763. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6764. // This test simulates a potential DoS attack using many headers
  6765. // to verify our security fix prevents memory exhaustion
  6766. httplib::Headers attack_headers;
  6767. // Attempt to add many headers like an attacker would (200 headers to far
  6768. // exceed limit)
  6769. for (int i = 0; i < 200; i++) {
  6770. std::string name = "X-Attack-Header-" + std::to_string(i);
  6771. std::string value = "attack_payload_" + std::to_string(i);
  6772. attack_headers.emplace(name, value);
  6773. }
  6774. // Try to POST with excessive headers
  6775. cli_.set_keep_alive(true);
  6776. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6777. // Should either fail or return 400 Bad Request due to security limit
  6778. if (res) {
  6779. // If we get a response, it should be 400 Bad Request
  6780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6781. EXPECT_EQ("close", res->get_header_value("Connection"));
  6782. }
  6783. EXPECT_FALSE(cli_.is_socket_open());
  6784. }
  6785. TEST_F(ServerTest, MultipartFormData) {
  6786. UploadFormDataItems items = {
  6787. {"text1", "text default", "", ""},
  6788. {"text2", "aωb", "", ""},
  6789. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6790. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6791. {"file3", "", "", "application/octet-stream"},
  6792. {"file4", "", "", " application/json tmp-string "}};
  6793. auto res = cli_.Post("/multipart", items);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6798. UploadFormDataItems items = {
  6799. {"text", "default text", "", ""},
  6800. {"multi_text1", "aaaaa", "", ""},
  6801. {"multi_text1", "bbbbb", "", ""},
  6802. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6803. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6804. "application/json"},
  6805. };
  6806. auto res = cli_.Post("/multipart/multi_file_values", items);
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. }
  6810. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6811. auto res = cli_.Get("/hi");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6815. EXPECT_EQ("Hello World!", res->body);
  6816. }
  6817. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6818. Request req;
  6819. req.method = "POST";
  6820. req.path = "/chunked";
  6821. std::string host_and_port;
  6822. host_and_port += HOST;
  6823. host_and_port += ":";
  6824. host_and_port += std::to_string(PORT);
  6825. req.headers.emplace("Host", host_and_port.c_str());
  6826. req.headers.emplace("Accept", "*/*");
  6827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6828. req.headers.emplace("Content-Type", "text/plain");
  6829. req.headers.emplace("Content-Length", "0");
  6830. req.headers.emplace(
  6831. "Transfer-Encoding",
  6832. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6833. // Client does not chunk, so make a chunked body manually.
  6834. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6835. auto res = std::make_shared<Response>();
  6836. auto error = Error::Success;
  6837. auto ret = cli_.send(req, *res, error);
  6838. ASSERT_TRUE(ret);
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. template <typename ClientT>
  6842. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6843. int expected_status) {
  6844. Request req;
  6845. req.method = "POST";
  6846. req.path = "/chunked";
  6847. std::string host_and_port;
  6848. host_and_port += HOST;
  6849. host_and_port += ":";
  6850. host_and_port += std::to_string(PORT);
  6851. req.headers.emplace("Host", host_and_port.c_str());
  6852. req.headers.emplace("Content-Length", "0");
  6853. req.headers.emplace("Transfer-Encoding", "chunked");
  6854. req.body = body;
  6855. auto res = std::make_shared<Response>();
  6856. auto error = Error::Success;
  6857. ASSERT_TRUE(cli.send(req, *res, error));
  6858. EXPECT_EQ(expected_status, res->status);
  6859. }
  6860. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6861. // rather than treat them as valid lengths.
  6862. template <typename ClientT>
  6863. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6864. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6865. }
  6866. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6867. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6868. }
  6869. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6870. expect_chunked_body_rejected(
  6871. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6872. }
  6873. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6874. // chunk-size line carries no CR, LF or other control character ahead of its
  6875. // terminator. Such a line must be refused rather than read as extension text.
  6876. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6877. expect_chunked_body_rejected(
  6878. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6879. }
  6880. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6881. expect_chunked_body_rejected(
  6882. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6883. }
  6884. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6885. expect_chunked_body_rejected(
  6886. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6887. }
  6888. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6889. // The literal stays split: a hex escape consumes every hex digit that
  6890. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6891. expect_chunked_body_rejected(
  6892. cli_, "4;a\x01"
  6893. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6894. }
  6895. // The bytes around chunk data are no payload, so they cannot ride on the
  6896. // payload limit
  6897. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6898. // Small enough that the whole request is sent before the server turns it
  6899. // down, yet past the limit by the last chunks
  6900. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6901. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6902. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6903. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6904. SCOPED_TRACE(size_line.substr(0, 2));
  6905. std::string body;
  6906. for (auto c : std::string("dechunked post body")) {
  6907. body += size_line + "\r\n" + c + "\r\n";
  6908. }
  6909. body += "0\r\n\r\n";
  6910. expect_chunked_body_rejected(cli_, body.c_str());
  6911. }
  6912. }
  6913. TEST_F(ServerTest, AcceptsChunkExtension) {
  6914. expect_chunked_body_status(cli_,
  6915. "4;name=value\r\ndech\r\n"
  6916. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6917. "0;last\r\n\r\n",
  6918. StatusCode::OK_200);
  6919. }
  6920. TEST_F(ServerTest, GetStreamed2) {
  6921. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6924. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6925. EXPECT_EQ(true, res->has_header("Content-Range"));
  6926. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6927. EXPECT_EQ(std::string("ab"), res->body);
  6928. }
  6929. TEST_F(ServerTest, GetStreamed) {
  6930. auto res = cli_.Get("/streamed");
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6934. EXPECT_EQ(std::string("aaabbb"), res->body);
  6935. }
  6936. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6937. auto res = cli_.Get("/streamed-without-length",
  6938. Headers{make_range_header({{0, -1}})});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ(false, res->has_header("Content-Length"));
  6942. EXPECT_EQ(false, res->has_header("Content-Range"));
  6943. EXPECT_EQ(std::string("abcdefg"), res->body);
  6944. }
  6945. TEST_F(ServerTest, GetStreamedWithRange1) {
  6946. auto res =
  6947. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6950. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6951. EXPECT_EQ(true, res->has_header("Content-Range"));
  6952. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6953. EXPECT_EQ(std::string("def"), res->body);
  6954. }
  6955. TEST_F(ServerTest, GetStreamedWithRange2) {
  6956. auto res =
  6957. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6960. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6961. EXPECT_EQ(true, res->has_header("Content-Range"));
  6962. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6963. EXPECT_EQ(std::string("bcdefg"), res->body);
  6964. }
  6965. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6966. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6969. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(true, res->has_header("Content-Range"));
  6971. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6972. EXPECT_EQ(std::string("efg"), res->body);
  6973. }
  6974. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6975. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6976. // the entire representation.
  6977. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6978. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6982. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6983. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6984. }
  6985. }
  6986. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6987. auto res =
  6988. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6991. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6992. EXPECT_EQ(false, res->has_header("Content-Range"));
  6993. EXPECT_EQ(0U, res->body.size());
  6994. }
  6995. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6996. // Only a 206 is served as a partial representation. Under any other status
  6997. // `apply_ranges()` reported the full content length, so the body must match
  6998. // that header, and the content provider must never be asked for an offset
  6999. // outside the representation.
  7000. auto check = [&](int status, const char *range) {
  7001. auto path =
  7002. std::string("/streamed-with-range?status=") + std::to_string(status);
  7003. auto ctx = path + " Range: " + range;
  7004. auto res = cli_.Get(path, Headers{{"Range", range}});
  7005. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7006. EXPECT_EQ(status, res->status) << ctx;
  7007. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7009. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7010. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7011. };
  7012. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7013. check(403, "bytes=3-5");
  7014. // The offset is far past the representation.
  7015. check(403, "bytes=100000-100200");
  7016. // `first_pos` is still -1 here, and the bounds asserts in
  7017. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7018. check(403, "bytes=-3");
  7019. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7020. // multipart branch would have written one that is empty.
  7021. check(403, "bytes=1-2, 4-5");
  7022. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7023. // covers the whole representation.
  7024. check(200, "bytes=3-5");
  7025. check(200, "bytes=1-2, 4-5");
  7026. }
  7027. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7028. auto res =
  7029. cli_.Get("/streamed-with-range",
  7030. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7031. "92233720368547758079223372036854775807"}});
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7034. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7035. EXPECT_EQ(false, res->has_header("Content-Range"));
  7036. EXPECT_EQ(0U, res->body.size());
  7037. }
  7038. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7039. auto res = cli_.Get(
  7040. "/with-range",
  7041. Headers{{"Range",
  7042. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7043. {"Accept-Encoding", ""}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7047. EXPECT_EQ(true, res->has_header("Content-Range"));
  7048. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7049. EXPECT_EQ(std::string("abcdefg"), res->body);
  7050. }
  7051. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7052. auto res = cli_.Get("/with-range", Headers{
  7053. {"Range", "bytes=0-"},
  7054. {"Accept-Encoding", ""},
  7055. });
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7059. EXPECT_EQ(true, res->has_header("Content-Range"));
  7060. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7061. EXPECT_EQ(std::string("abcdefg"), res->body);
  7062. }
  7063. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7064. auto res = cli_.Get("/streamed-with-range",
  7065. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7068. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7069. EXPECT_EQ(false, res->has_header("Content-Range"));
  7070. EXPECT_EQ(267U, res->body.size());
  7071. // Check that both range contents are present
  7072. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7073. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7074. // Check that Content-Range headers are present for both ranges
  7075. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7076. std::string::npos);
  7077. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7078. std::string::npos);
  7079. }
  7080. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7081. Ranges ranges;
  7082. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7083. ranges.emplace_back(0, -1);
  7084. }
  7085. auto res = cli_.Get("/streamed-with-range?error",
  7086. Headers{{make_range_header(ranges)}});
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7089. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7090. EXPECT_EQ(false, res->has_header("Content-Range"));
  7091. EXPECT_EQ(0U, res->body.size());
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7094. auto res = cli_.Get("/streamed-with-range",
  7095. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ(5U, res->body.size());
  7099. // Check that overlapping ranges are coalesced into a single range
  7100. EXPECT_EQ("bcdef", res->body);
  7101. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7102. // Should be single range, not multipart
  7103. EXPECT_TRUE(res->has_header("Content-Range"));
  7104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7105. }
  7106. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7107. auto res = cli_.Get("/streamed-with-range",
  7108. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7111. EXPECT_EQ(268U, res->body.size());
  7112. // Check that both range contents are present
  7113. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7114. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7115. // Check that Content-Range headers are present for both ranges
  7116. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7117. std::string::npos);
  7118. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7119. std::string::npos);
  7120. }
  7121. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7122. auto res = cli_.Get("/streamed-with-range",
  7123. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ(269U, res->body.size());
  7127. // Check that both duplicate range contents are present
  7128. size_t first_abc = res->body.find("abc\r\n");
  7129. EXPECT_TRUE(first_abc != std::string::npos);
  7130. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7131. EXPECT_TRUE(second_abc != std::string::npos);
  7132. // Check that Content-Range headers are present for both ranges
  7133. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7134. EXPECT_TRUE(first_range != std::string::npos);
  7135. size_t second_range =
  7136. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7137. EXPECT_TRUE(second_range != std::string::npos);
  7138. }
  7139. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7140. auto res =
  7141. cli_.Get("/streamed-with-range?error",
  7142. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7145. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7146. EXPECT_EQ(false, res->has_header("Content-Range"));
  7147. EXPECT_EQ(0U, res->body.size());
  7148. }
  7149. TEST_F(ServerTest, GetStreamedEndless) {
  7150. uint64_t offset = 0;
  7151. auto res = cli_.Get("/streamed-cancel",
  7152. [&](const char * /*data*/, uint64_t data_length) {
  7153. if (offset < 100) {
  7154. offset += data_length;
  7155. return true;
  7156. }
  7157. return false;
  7158. });
  7159. ASSERT_TRUE(!res);
  7160. EXPECT_EQ(Error::Canceled, res.error());
  7161. }
  7162. TEST_F(ServerTest, ClientStop) {
  7163. std::atomic_size_t count{4};
  7164. std::vector<std::thread> threads;
  7165. for (auto i = count.load(); i != 0; --i) {
  7166. threads.emplace_back([&]() {
  7167. auto res = cli_.Get("/streamed-cancel",
  7168. [&](const char *, uint64_t) { return true; });
  7169. --count;
  7170. ASSERT_TRUE(!res);
  7171. EXPECT_TRUE(res.error() == Error::Canceled ||
  7172. res.error() == Error::Read || res.error() == Error::Write);
  7173. });
  7174. }
  7175. std::this_thread::sleep_for(std::chrono::seconds(2));
  7176. while (count != 0) {
  7177. cli_.stop();
  7178. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7179. }
  7180. for (auto &t : threads) {
  7181. t.join();
  7182. }
  7183. }
  7184. TEST_F(ServerTest, GetWithRange1) {
  7185. auto res = cli_.Get("/with-range", Headers{
  7186. make_range_header({{3, 5}}),
  7187. {"Accept-Encoding", ""},
  7188. });
  7189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7191. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7192. EXPECT_EQ(true, res->has_header("Content-Range"));
  7193. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7194. EXPECT_EQ(std::string("def"), res->body);
  7195. }
  7196. TEST_F(ServerTest, GetWithRange2) {
  7197. auto res = cli_.Get("/with-range", Headers{
  7198. make_range_header({{1, -1}}),
  7199. {"Accept-Encoding", ""},
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(true, res->has_header("Content-Range"));
  7205. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7206. EXPECT_EQ(std::string("bcdefg"), res->body);
  7207. }
  7208. TEST_F(ServerTest, GetWithRange3) {
  7209. auto res = cli_.Get("/with-range", Headers{
  7210. make_range_header({{0, 0}}),
  7211. {"Accept-Encoding", ""},
  7212. });
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7215. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7216. EXPECT_EQ(true, res->has_header("Content-Range"));
  7217. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7218. EXPECT_EQ(std::string("a"), res->body);
  7219. }
  7220. TEST_F(ServerTest, GetWithRange4) {
  7221. auto res = cli_.Get("/with-range", Headers{
  7222. make_range_header({{-1, 2}}),
  7223. {"Accept-Encoding", ""},
  7224. });
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7228. EXPECT_EQ(true, res->has_header("Content-Range"));
  7229. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7230. EXPECT_EQ(std::string("fg"), res->body);
  7231. }
  7232. TEST_F(ServerTest, GetWithRange5) {
  7233. auto res = cli_.Get("/with-range", Headers{
  7234. make_range_header({{0, 5}}),
  7235. {"Accept-Encoding", ""},
  7236. });
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7239. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7240. EXPECT_EQ(true, res->has_header("Content-Range"));
  7241. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7242. EXPECT_EQ(std::string("abcdef"), res->body);
  7243. }
  7244. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7245. auto res =
  7246. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7249. }
  7250. TEST_F(ServerTest, GetWithRangeMultipart) {
  7251. auto res =
  7252. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7256. EXPECT_EQ(false, res->has_header("Content-Range"));
  7257. EXPECT_EQ(267U, res->body.size());
  7258. }
  7259. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7260. auto res = cli_.Get("/with-range",
  7261. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7264. }
  7265. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7266. auto res = cli_.Get("/with-range-customized-response",
  7267. Headers{{make_range_header({{1, 2}})}});
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7270. EXPECT_EQ(true, res->has_header("Content-Length"));
  7271. EXPECT_EQ(false, res->has_header("Content-Range"));
  7272. EXPECT_EQ(JSON_DATA, res->body);
  7273. }
  7274. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7275. auto res = cli_.Get("/with-range-customized-response",
  7276. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7279. EXPECT_EQ(true, res->has_header("Content-Length"));
  7280. EXPECT_EQ(false, res->has_header("Content-Range"));
  7281. EXPECT_EQ(JSON_DATA, res->body);
  7282. }
  7283. TEST_F(ServerTest, Issue1772) {
  7284. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7287. }
  7288. TEST_F(ServerTest, Issue609) {
  7289. auto res = cli_.Delete("/issue609");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. EXPECT_EQ(std::string("ok"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetStreamedChunked) {
  7295. auto res = cli_.Get("/streamed-chunked");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ(std::string("123456789"), res->body);
  7299. }
  7300. TEST_F(ServerTest, GetStreamedChunked2) {
  7301. auto res = cli_.Get("/streamed-chunked2");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ(std::string("123456789"), res->body);
  7305. }
  7306. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7307. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ(std::string("123456789"), res->body);
  7311. EXPECT_TRUE(res->has_header("Trailer"));
  7312. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7313. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7314. // Trailers are now stored separately from headers (security fix)
  7315. EXPECT_EQ(2U, res->trailers.size());
  7316. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7317. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7318. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7319. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7320. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7321. // Verify trailers are NOT in headers (security verification)
  7322. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7323. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7324. }
  7325. TEST_F(ServerTest, LargeChunkedPost) {
  7326. Request req;
  7327. req.method = "POST";
  7328. req.path = "/large-chunked";
  7329. std::string host_and_port;
  7330. host_and_port += HOST;
  7331. host_and_port += ":";
  7332. host_and_port += std::to_string(PORT);
  7333. req.headers.emplace("Host", host_and_port.c_str());
  7334. req.headers.emplace("Accept", "*/*");
  7335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7336. req.headers.emplace("Content-Type", "text/plain");
  7337. req.headers.emplace("Content-Length", "0");
  7338. req.headers.emplace("Transfer-Encoding", "chunked");
  7339. std::string long_string(30 * 1024u, 'a');
  7340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7341. // Attempt to make a large enough post to exceed OS buffers, to test that
  7342. // the server handles short reads if the full chunk data isn't available.
  7343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7344. auto res = std::make_shared<Response>();
  7345. auto error = Error::Success;
  7346. auto ret = cli_.send(req, *res, error);
  7347. ASSERT_TRUE(ret);
  7348. EXPECT_EQ(StatusCode::OK_200, res->status);
  7349. }
  7350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7351. auto res = cli_.Get("/remote_addr");
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::OK_200, res->status);
  7354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7356. }
  7357. TEST_F(ServerTest, GetMethodLocalAddr) {
  7358. auto res = cli_.Get("/local_addr");
  7359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7362. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7363. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7364. }
  7365. TEST_F(ServerTest, HTTPResponseSplitting) {
  7366. auto res = cli_.Get("/http_response_splitting");
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. }
  7370. TEST_F(ServerTest, SlowRequest) {
  7371. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7372. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7373. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7374. }
  7375. #if 0
  7376. TEST_F(ServerTest, SlowPost) {
  7377. char buffer[64 * 1024];
  7378. memset(buffer, 0x42, sizeof(buffer));
  7379. auto res = cli_.Post(
  7380. "/slowpost", 64 * 1024 * 1024,
  7381. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7382. auto ret = sink.write(buffer, sizeof(buffer));
  7383. EXPECT_TRUE(ret);
  7384. return true;
  7385. },
  7386. "text/plain");
  7387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7388. EXPECT_EQ(StatusCode::OK_200, res->status);
  7389. }
  7390. TEST_F(ServerTest, SlowPostFail) {
  7391. char buffer[64 * 1024];
  7392. memset(buffer, 0x42, sizeof(buffer));
  7393. cli_.set_write_timeout(std::chrono::seconds(0));
  7394. auto res = cli_.Post(
  7395. "/slowpost", 64 * 1024 * 1024,
  7396. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7397. sink.write(buffer, sizeof(buffer));
  7398. return true;
  7399. },
  7400. "text/plain");
  7401. ASSERT_TRUE(!res);
  7402. EXPECT_EQ(Error::Write, res.error());
  7403. }
  7404. #endif
  7405. TEST_F(ServerTest, Put) {
  7406. auto res = cli_.Put("/put", "PUT", "text/plain");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ("PUT", res->body);
  7410. }
  7411. TEST_F(ServerTest, PutWithContentProvider) {
  7412. auto res = cli_.Put(
  7413. "/put", 3,
  7414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7415. sink.os << "PUT";
  7416. return true;
  7417. },
  7418. "text/plain");
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ("PUT", res->body);
  7422. }
  7423. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7424. auto res = cli_.Post(
  7425. "/post", 42,
  7426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7427. return false;
  7428. },
  7429. "text/plain");
  7430. ASSERT_TRUE(!res);
  7431. EXPECT_EQ(Error::Canceled, res.error());
  7432. }
  7433. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7434. auto res = cli_.Put(
  7435. "/put",
  7436. [](size_t /*offset*/, DataSink &sink) {
  7437. sink.os << "PUT";
  7438. sink.done();
  7439. return true;
  7440. },
  7441. "text/plain");
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::OK_200, res->status);
  7444. EXPECT_EQ("PUT", res->body);
  7445. }
  7446. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7447. auto res = cli_.Post(
  7448. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7449. "text/plain");
  7450. ASSERT_TRUE(!res);
  7451. EXPECT_EQ(Error::Canceled, res.error());
  7452. }
  7453. TEST_F(ServerTest, PostLoopBack) {
  7454. std::string body;
  7455. auto res = cli_.Post(
  7456. "/post-loopback", 9,
  7457. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7458. EXPECT_EQ(9u, length);
  7459. sink.write("123", 3);
  7460. sink.write("456", 3);
  7461. sink.write("789", 3);
  7462. return true;
  7463. },
  7464. "text/plain",
  7465. [&body](const char *data, size_t data_length) {
  7466. body.append(data, data_length);
  7467. return true;
  7468. });
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. EXPECT_EQ("123456789", body);
  7472. }
  7473. TEST_F(ServerTest, PutLoopBack) {
  7474. std::string body;
  7475. auto res = cli_.Put(
  7476. "/put-loopback", 9,
  7477. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7478. EXPECT_EQ(9u, length);
  7479. sink.write("123", 3);
  7480. sink.write("456", 3);
  7481. sink.write("789", 3);
  7482. return true;
  7483. },
  7484. "text/plain",
  7485. [&body](const char *data, size_t data_length) {
  7486. body.append(data, data_length);
  7487. return true;
  7488. });
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ("123456789", body);
  7492. }
  7493. TEST_F(ServerTest, PatchLoopBack) {
  7494. std::string body;
  7495. auto res = cli_.Patch(
  7496. "/patch-loopback", 9,
  7497. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7498. EXPECT_EQ(9u, length);
  7499. sink.write("123", 3);
  7500. sink.write("456", 3);
  7501. sink.write("789", 3);
  7502. return true;
  7503. },
  7504. "text/plain",
  7505. [&body](const char *data, size_t data_length) {
  7506. body.append(data, data_length);
  7507. return true;
  7508. });
  7509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7510. EXPECT_EQ(StatusCode::OK_200, res->status);
  7511. EXPECT_EQ("123456789", body);
  7512. }
  7513. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7514. std::string body;
  7515. auto res = cli_.Post(
  7516. "/post-loopback",
  7517. [](size_t /*offset*/, DataSink &sink) {
  7518. sink.write("123", 3);
  7519. sink.write("456", 3);
  7520. sink.write("789", 3);
  7521. sink.done();
  7522. return true;
  7523. },
  7524. "text/plain",
  7525. [&body](const char *data, size_t data_length) {
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. EXPECT_EQ("123456789", body);
  7532. }
  7533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7534. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7535. cli_.set_compress(true);
  7536. auto res = cli_.Put(
  7537. "/put", 3,
  7538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7539. sink.os << "PUT";
  7540. return true;
  7541. },
  7542. "text/plain");
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. EXPECT_EQ("PUT", res->body);
  7546. }
  7547. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7548. cli_.set_compress(true);
  7549. auto res = cli_.Post(
  7550. "/post", 42,
  7551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7552. return false;
  7553. },
  7554. "text/plain");
  7555. ASSERT_TRUE(!res);
  7556. EXPECT_EQ(Error::Canceled, res.error());
  7557. }
  7558. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7559. cli_.set_compress(true);
  7560. auto res = cli_.Put(
  7561. "/put",
  7562. [](size_t /*offset*/, DataSink &sink) {
  7563. sink.os << "PUT";
  7564. sink.done();
  7565. return true;
  7566. },
  7567. "text/plain");
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("PUT", res->body);
  7571. }
  7572. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7573. cli_.set_compress(true);
  7574. auto res = cli_.Post(
  7575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7576. "text/plain");
  7577. ASSERT_TRUE(!res);
  7578. EXPECT_EQ(Error::Canceled, res.error());
  7579. }
  7580. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7581. cli_.set_compress(true);
  7582. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. EXPECT_EQ(LARGE_DATA, res->body);
  7586. }
  7587. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7588. #ifdef CPPHTTPLIB_SSL_ENABLED
  7589. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7590. Client cli(s.c_str());
  7591. cli.enable_server_certificate_verification(false);
  7592. #else
  7593. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7594. Client cli(s.c_str());
  7595. #endif
  7596. cli.set_compress(true);
  7597. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ(LARGE_DATA, res->body);
  7601. // The compressed size should be less than a 10th of the original. May vary
  7602. // depending on the zlib library.
  7603. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7604. static_cast<uint64_t>(10 * 1024 * 1024));
  7605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7606. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7607. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7608. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7609. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7610. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7611. #endif
  7612. }
  7613. TEST_F(ServerTest, PutContentWithDeflate) {
  7614. cli_.set_compress(false);
  7615. Headers headers;
  7616. headers.emplace("Content-Encoding", "deflate");
  7617. // PUT in deflate format:
  7618. auto res = cli_.Put("/put", headers,
  7619. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7621. EXPECT_EQ(StatusCode::OK_200, res->status);
  7622. EXPECT_EQ("PUT", res->body);
  7623. }
  7624. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7625. Headers headers;
  7626. headers.emplace("Accept-Encoding", "gzip, deflate");
  7627. auto res = cli_.Get("/streamed-chunked", headers);
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::OK_200, res->status);
  7630. EXPECT_EQ(std::string("123456789"), res->body);
  7631. }
  7632. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7633. Headers headers;
  7634. headers.emplace("Accept-Encoding", "gzip, deflate");
  7635. auto res = cli_.Get("/streamed-chunked2", headers);
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. EXPECT_EQ(std::string("123456789"), res->body);
  7639. }
  7640. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7641. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. }
  7645. TEST(GzipDecompressor, ChunkedDecompression) {
  7646. std::string data;
  7647. for (size_t i = 0; i < 32 * 1024; ++i) {
  7648. data.push_back(static_cast<char>('a' + i % 26));
  7649. }
  7650. std::string compressed_data;
  7651. {
  7652. httplib::detail::gzip_compressor compressor;
  7653. bool result = compressor.compress(
  7654. data.data(), data.size(),
  7655. /*last=*/true,
  7656. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7657. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7658. compressed_data_size);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(result);
  7662. }
  7663. std::string decompressed_data;
  7664. {
  7665. httplib::detail::gzip_decompressor decompressor;
  7666. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7667. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7668. size_t chunk_size = 130;
  7669. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7670. chunk_begin += chunk_size) {
  7671. size_t current_chunk_size =
  7672. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7673. bool result = decompressor.decompress(
  7674. compressed_data.data() + chunk_begin, current_chunk_size,
  7675. [&](const char *decompressed_data_chunk,
  7676. size_t decompressed_data_chunk_size) {
  7677. decompressed_data.insert(decompressed_data.size(),
  7678. decompressed_data_chunk,
  7679. decompressed_data_chunk_size);
  7680. return true;
  7681. });
  7682. ASSERT_TRUE(result);
  7683. }
  7684. }
  7685. ASSERT_EQ(data, decompressed_data);
  7686. }
  7687. TEST(GzipDecompressor, DeflateDecompression) {
  7688. std::string original_text = "Raw deflate without gzip";
  7689. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7690. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7691. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7692. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7693. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7694. std::string decompressed_data;
  7695. {
  7696. httplib::detail::gzip_decompressor decompressor;
  7697. bool result = decompressor.decompress(
  7698. compressed_data.data(), compressed_data.size(),
  7699. [&](const char *decompressed_data_chunk,
  7700. size_t decompressed_data_chunk_size) {
  7701. decompressed_data.insert(decompressed_data.size(),
  7702. decompressed_data_chunk,
  7703. decompressed_data_chunk_size);
  7704. return true;
  7705. });
  7706. ASSERT_TRUE(result);
  7707. }
  7708. ASSERT_EQ(original_text, decompressed_data);
  7709. }
  7710. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7711. std::string original_text = "Raw deflate without gzip";
  7712. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7713. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7714. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7715. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7716. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7717. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7718. std::string decompressed_data;
  7719. {
  7720. httplib::detail::gzip_decompressor decompressor;
  7721. bool result = decompressor.decompress(
  7722. compressed_data.data(), compressed_data.size(),
  7723. [&](const char *decompressed_data_chunk,
  7724. size_t decompressed_data_chunk_size) {
  7725. decompressed_data.insert(decompressed_data.size(),
  7726. decompressed_data_chunk,
  7727. decompressed_data_chunk_size);
  7728. return true;
  7729. });
  7730. ASSERT_TRUE(result);
  7731. }
  7732. ASSERT_EQ(original_text, decompressed_data);
  7733. }
  7734. #endif
  7735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7736. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7737. Headers headers;
  7738. headers.emplace("Accept-Encoding", "br");
  7739. auto res = cli_.Get("/streamed-chunked", headers);
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ(std::string("123456789"), res->body);
  7743. }
  7744. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7745. Headers headers;
  7746. headers.emplace("Accept-Encoding", "br");
  7747. auto res = cli_.Get("/streamed-chunked2", headers);
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. EXPECT_EQ(std::string("123456789"), res->body);
  7751. }
  7752. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7753. cli_.set_compress(true);
  7754. auto res = cli_.Put(
  7755. "/put", 3,
  7756. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7757. sink.os << "PUT";
  7758. return true;
  7759. },
  7760. "text/plain");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("PUT", res->body);
  7764. }
  7765. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7766. cli_.set_compress(true);
  7767. auto res = cli_.Put(
  7768. "/put",
  7769. [](size_t /*offset*/, DataSink &sink) {
  7770. sink.os << "PUT";
  7771. sink.done();
  7772. return true;
  7773. },
  7774. "text/plain");
  7775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7776. EXPECT_EQ(StatusCode::OK_200, res->status);
  7777. EXPECT_EQ("PUT", res->body);
  7778. }
  7779. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7780. cli_.set_compress(true);
  7781. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7783. EXPECT_EQ(StatusCode::OK_200, res->status);
  7784. EXPECT_EQ(LARGE_DATA, res->body);
  7785. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7786. }
  7787. #endif
  7788. TEST_F(ServerTest, Patch) {
  7789. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. EXPECT_EQ(StatusCode::OK_200, res->status);
  7792. EXPECT_EQ("PATCH", res->body);
  7793. }
  7794. TEST_F(ServerTest, Delete) {
  7795. auto res = cli_.Delete("/delete");
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("DELETE", res->body);
  7799. }
  7800. TEST_F(ServerTest, DeleteContentReceiver) {
  7801. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("content", res->body);
  7805. }
  7806. TEST_F(ServerTest, Options) {
  7807. auto res = cli_.Options("*");
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7811. EXPECT_TRUE(res->body.empty());
  7812. }
  7813. TEST_F(ServerTest, URL) {
  7814. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST_F(ServerTest, ArrayParam) {
  7819. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. }
  7823. TEST_F(ServerTest, ArrayParamValues) {
  7824. auto res =
  7825. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. }
  7829. TEST_F(ServerTest, NoMultipleHeaders) {
  7830. Headers headers = {{"Content-Length", "5"}};
  7831. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7832. "text/plain");
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(StatusCode::OK_200, res->status);
  7835. }
  7836. TEST_F(ServerTest, PostContentReceiver) {
  7837. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7839. ASSERT_EQ(StatusCode::OK_200, res->status);
  7840. ASSERT_EQ("content", res->body);
  7841. }
  7842. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7843. UploadFormDataItems items = {
  7844. {"text1", "text default", "", ""},
  7845. {"text2", "aωb", "", ""},
  7846. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7847. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7848. {"file3", "", "", "application/octet-stream"},
  7849. };
  7850. auto res = cli_.Post("/content_receiver", items);
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::OK_200, res->status);
  7853. }
  7854. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7855. UploadFormDataItems items = {
  7856. {"text1", "text default", "", ""},
  7857. {"text2", "aωb", "", ""},
  7858. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7859. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7860. {"file3", "", "", "application/octet-stream"},
  7861. };
  7862. auto boundary = std::string("+++++");
  7863. std::string body;
  7864. for (const auto &item : items) {
  7865. body += "--" + boundary + "\r\n";
  7866. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7867. if (!item.filename.empty()) {
  7868. body += "; filename=\"" + item.filename + "\"";
  7869. }
  7870. body += "\r\n";
  7871. if (!item.content_type.empty()) {
  7872. body += "Content-Type: " + item.content_type + "\r\n";
  7873. }
  7874. body += "\r\n";
  7875. body += item.content + "\r\n";
  7876. }
  7877. body += "--" + boundary + "--\r\n";
  7878. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7879. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. }
  7883. TEST(MultipartFormDataTest, FieldEscaping) {
  7884. Server svr;
  7885. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7886. const ContentReader &content_reader) {
  7887. ASSERT_TRUE(req.is_multipart_form_data());
  7888. std::vector<FormData> received;
  7889. content_reader(
  7890. [&](const FormData &file) {
  7891. received.push_back(file);
  7892. return true;
  7893. },
  7894. [&](const char *data, size_t data_length) {
  7895. received.back().content.append(data, data_length);
  7896. return true;
  7897. });
  7898. // '"', CR and LF in names and filenames are escaped following the
  7899. // WHATWG HTML standard, so each part still parses as a single part
  7900. // with no injected headers. Content types get CR/LF escaped too,
  7901. // while '"' (legal there, e.g. quoted charset) is preserved.
  7902. ASSERT_EQ(4U, received.size());
  7903. EXPECT_EQ("na%22me", received[0].name);
  7904. EXPECT_EQ("quoted name", received[0].content);
  7905. EXPECT_EQ("file", received[1].name);
  7906. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7907. received[1].filename);
  7908. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7909. EXPECT_EQ("injected", received[1].content);
  7910. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7911. EXPECT_EQ("my%22file.txt", received[2].filename);
  7912. EXPECT_EQ("cr lf name", received[2].content);
  7913. EXPECT_EQ("typed", received[3].name);
  7914. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7915. received[3].content_type);
  7916. EXPECT_EQ("typed content", received[3].content);
  7917. });
  7918. auto port = svr.bind_to_any_port("localhost");
  7919. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. t.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. Client cli("localhost", port);
  7927. UploadFormDataItems items = {
  7928. {"na\"me", "quoted name", "", ""},
  7929. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7930. "application/octet-stream"},
  7931. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7932. {"typed", "typed content", "",
  7933. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7934. };
  7935. auto res = cli.Post("/post", items);
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. }
  7939. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7940. const UploadFormDataItems items = {
  7941. {"name1", "Content 1", "", ""},
  7942. {"name2", "Content 2", "file2.txt", "text/plain"},
  7943. };
  7944. Server svr;
  7945. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7946. const ContentReader &content_reader) {
  7947. ASSERT_TRUE(req.is_multipart_form_data());
  7948. std::vector<FormData> received;
  7949. content_reader(
  7950. [&](const FormData &file) {
  7951. received.push_back(file);
  7952. return true;
  7953. },
  7954. [&](const char *data, size_t data_length) {
  7955. received.back().content.append(data, data_length);
  7956. return true;
  7957. });
  7958. ASSERT_EQ(2U, received.size());
  7959. EXPECT_EQ("name1", received[0].name);
  7960. EXPECT_EQ("Content 1", received[0].content);
  7961. EXPECT_EQ("name2", received[1].name);
  7962. EXPECT_EQ("Content 2", received[1].content);
  7963. EXPECT_EQ("file2.txt", received[1].filename);
  7964. EXPECT_EQ("text/plain", received[1].content_type);
  7965. });
  7966. auto port = svr.bind_to_any_port("localhost");
  7967. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. t.join();
  7971. ASSERT_FALSE(svr.is_running());
  7972. });
  7973. svr.wait_until_ready();
  7974. Client cli("localhost", port);
  7975. // Whole-body serialization with a generated boundary
  7976. {
  7977. MultipartFormDataWriter writer;
  7978. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7979. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7980. writer.content_type());
  7981. auto body = writer.serialize(items);
  7982. EXPECT_EQ(body.size(), writer.content_length(items));
  7983. auto res = cli.Post("/post", body, writer.content_type());
  7984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7985. EXPECT_EQ(StatusCode::OK_200, res->status);
  7986. }
  7987. // Per-part framing with a custom boundary via a content provider
  7988. {
  7989. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7990. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7991. MultipartFormDataWriter writer("custom-boundary_123");
  7992. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7993. std::string body;
  7994. for (const auto &item : items) {
  7995. body += writer.item_begin(item);
  7996. body += item.content;
  7997. body += MultipartFormDataWriter::item_end();
  7998. }
  7999. body += writer.finish();
  8000. EXPECT_EQ(body.size(), writer.content_length(items));
  8001. auto res = cli.Post(
  8002. "/post", body.size(),
  8003. [&](size_t offset, size_t length, DataSink &sink) {
  8004. sink.write(body.data() + offset, length);
  8005. return true;
  8006. },
  8007. writer.content_type());
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::OK_200, res->status);
  8010. }
  8011. }
  8012. TEST_F(ServerTest, PostContentReceiverGzip) {
  8013. cli_.set_compress(true);
  8014. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8016. ASSERT_EQ(StatusCode::OK_200, res->status);
  8017. ASSERT_EQ("content", res->body);
  8018. }
  8019. TEST_F(ServerTest, PutContentReceiver) {
  8020. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. ASSERT_EQ("content", res->body);
  8024. }
  8025. TEST_F(ServerTest, PatchContentReceiver) {
  8026. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. ASSERT_EQ(StatusCode::OK_200, res->status);
  8029. ASSERT_EQ("content", res->body);
  8030. }
  8031. template <typename ClientType>
  8032. void TestWithHeadersAndContentReceiver(
  8033. ClientType &cli,
  8034. std::function<Result(ClientType &, const std::string &, const Headers &,
  8035. const std::string &, const std::string &,
  8036. ContentReceiver, DownloadProgress)>
  8037. request_func) {
  8038. Headers headers;
  8039. headers.emplace("X-Custom-Header", "test-value");
  8040. std::string received_body;
  8041. auto res = request_func(
  8042. cli, "/content_receiver", headers, "content", "application/json",
  8043. [&](const char *data, size_t data_length) {
  8044. received_body.append(data, data_length);
  8045. return true;
  8046. },
  8047. nullptr);
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. EXPECT_EQ("content", received_body);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiver<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiver<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiver<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverWithProgress(
  8093. ClientType &cli,
  8094. std::function<Result(ClientType &, const std::string &, const Headers &,
  8095. const std::string &, const std::string &,
  8096. ContentReceiver, DownloadProgress)>
  8097. request_func) {
  8098. Headers headers;
  8099. headers.emplace("X-Test-Header", "progress-test");
  8100. std::string received_body;
  8101. auto progress_called = false;
  8102. auto res = request_func(
  8103. cli, "/content_receiver", headers, "content", "text/plain",
  8104. [&](const char *data, size_t data_length) {
  8105. received_body.append(data, data_length);
  8106. return true;
  8107. },
  8108. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8109. progress_called = true;
  8110. return true;
  8111. });
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_EQ(StatusCode::OK_200, res->status);
  8114. EXPECT_EQ("content", received_body);
  8115. EXPECT_TRUE(progress_called);
  8116. }
  8117. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8118. #ifdef CPPHTTPLIB_SSL_ENABLED
  8119. using ClientT = SSLClient;
  8120. #else
  8121. using ClientT = Client;
  8122. #endif
  8123. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8124. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8125. const std::string &body, const std::string &content_type,
  8126. ContentReceiver receiver, DownloadProgress progress) {
  8127. return cli.Post(path, headers, body, content_type, receiver, progress);
  8128. });
  8129. }
  8130. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8131. #ifdef CPPHTTPLIB_SSL_ENABLED
  8132. using ClientT = SSLClient;
  8133. #else
  8134. using ClientT = Client;
  8135. #endif
  8136. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8137. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8138. const std::string &body, const std::string &content_type,
  8139. ContentReceiver receiver, DownloadProgress progress) {
  8140. return cli.Put(path, headers, body, content_type, receiver, progress);
  8141. });
  8142. }
  8143. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8144. #ifdef CPPHTTPLIB_SSL_ENABLED
  8145. using ClientT = SSLClient;
  8146. #else
  8147. using ClientT = Client;
  8148. #endif
  8149. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8150. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8151. const std::string &body, const std::string &content_type,
  8152. ContentReceiver receiver, DownloadProgress progress) {
  8153. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8154. });
  8155. }
  8156. template <typename ClientType>
  8157. void TestWithHeadersAndContentReceiverError(
  8158. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8159. const Headers &, const std::string &,
  8160. const std::string &, ContentReceiver)>
  8161. request_func) {
  8162. Headers headers;
  8163. headers.emplace("X-Error-Test", "true");
  8164. std::string received_body;
  8165. auto receiver_failed = false;
  8166. auto res =
  8167. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8168. [&](const char *data, size_t data_length) {
  8169. received_body.append(data, data_length);
  8170. receiver_failed = true;
  8171. return false;
  8172. });
  8173. ASSERT_FALSE(res);
  8174. EXPECT_TRUE(receiver_failed);
  8175. }
  8176. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8177. #ifdef CPPHTTPLIB_SSL_ENABLED
  8178. using ClientT = SSLClient;
  8179. #else
  8180. using ClientT = Client;
  8181. #endif
  8182. TestWithHeadersAndContentReceiverError<ClientT>(
  8183. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8184. const std::string &body, const std::string &content_type,
  8185. ContentReceiver receiver) {
  8186. return cli.Post(path, headers, body, content_type, receiver);
  8187. });
  8188. }
  8189. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8190. #ifdef CPPHTTPLIB_SSL_ENABLED
  8191. using ClientT = SSLClient;
  8192. #else
  8193. using ClientT = Client;
  8194. #endif
  8195. TestWithHeadersAndContentReceiverError<ClientT>(
  8196. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8197. const std::string &body, const std::string &content_type,
  8198. ContentReceiver receiver) {
  8199. return cli.Put(path, headers, body, content_type, receiver);
  8200. });
  8201. }
  8202. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8203. #ifdef CPPHTTPLIB_SSL_ENABLED
  8204. using ClientT = SSLClient;
  8205. #else
  8206. using ClientT = Client;
  8207. #endif
  8208. TestWithHeadersAndContentReceiverError<ClientT>(
  8209. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8210. const std::string &body, const std::string &content_type,
  8211. ContentReceiver receiver) {
  8212. return cli.Patch(path, headers, body, content_type, receiver);
  8213. });
  8214. }
  8215. TEST_F(ServerTest, PostQueryStringAndBody) {
  8216. auto res =
  8217. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. ASSERT_EQ(StatusCode::OK_200, res->status);
  8220. }
  8221. TEST_F(ServerTest, HTTP2Magic) {
  8222. Request req;
  8223. req.method = "PRI";
  8224. req.path = "*";
  8225. req.body = "SM";
  8226. auto res = std::make_shared<Response>();
  8227. auto error = Error::Success;
  8228. auto ret = cli_.send(req, *res, error);
  8229. ASSERT_TRUE(ret);
  8230. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8231. }
  8232. TEST_F(ServerTest, KeepAlive) {
  8233. auto res = cli_.Get("/hi");
  8234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8237. EXPECT_EQ("Hello World!", res->body);
  8238. res = cli_.Get("/hi");
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::OK_200, res->status);
  8241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8242. EXPECT_EQ("Hello World!", res->body);
  8243. res = cli_.Get("/hi");
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ(StatusCode::OK_200, res->status);
  8246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8247. EXPECT_EQ("Hello World!", res->body);
  8248. res = cli_.Get("/not-exist");
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8251. res = cli_.Post("/empty", "", "text/plain");
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8255. EXPECT_EQ("empty", res->body);
  8256. EXPECT_EQ("close", res->get_header_value("Connection"));
  8257. res = cli_.Post(
  8258. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8259. "text/plain");
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8263. EXPECT_EQ("empty", res->body);
  8264. cli_.set_keep_alive(false);
  8265. res = cli_.Get("/last-request");
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("close", res->get_header_value("Connection"));
  8269. }
  8270. TEST_F(ServerTest, TooManyRedirect) {
  8271. cli_.set_follow_location(true);
  8272. auto res = cli_.Get("/redirect/0");
  8273. ASSERT_TRUE(!res);
  8274. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8275. }
  8276. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8277. Request req;
  8278. req.method = "FOOBAR";
  8279. req.path = "/hi";
  8280. cli_.set_keep_alive(true);
  8281. auto res = cli_.send(req);
  8282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8283. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8284. EXPECT_EQ("close", res->get_header_value("Connection"));
  8285. EXPECT_FALSE(cli_.is_socket_open());
  8286. }
  8287. TEST_F(ServerTest, CustomRouteReadsBody) {
  8288. const std::string xml =
  8289. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8290. Request req;
  8291. req.method = "PROPFIND";
  8292. req.path = "/dav/dir";
  8293. req.set_header("Depth", "1");
  8294. req.body = xml;
  8295. auto res = cli_.send(req);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8298. EXPECT_EQ(xml, res->body);
  8299. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8300. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8301. }
  8302. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8303. Request req;
  8304. req.method = "PROPFIND";
  8305. req.path = "/dav/42";
  8306. auto res = cli_.send(req);
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8309. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8310. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8311. }
  8312. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8313. Request req;
  8314. req.method = "PROPFIND";
  8315. req.path = "/dav-re/123";
  8316. auto res = cli_.send(req);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8319. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8320. }
  8321. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8322. Request req;
  8323. req.method = "MKCOL";
  8324. req.path = "/dav-mkcol";
  8325. auto res = cli_.send(req);
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. EXPECT_EQ(StatusCode::Created_201, res->status);
  8328. }
  8329. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8330. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8331. Request req;
  8332. req.method = "REPORT";
  8333. req.path = "/dav-report";
  8334. req.body = xml;
  8335. auto res = cli_.send(req);
  8336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8337. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8338. EXPECT_EQ(xml, res->body);
  8339. }
  8340. // A content reader route must fire even when the request carries no body,
  8341. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8342. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8343. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8344. Request req;
  8345. req.method = "REPORT";
  8346. req.path = "/dav-report";
  8347. auto res = cli_.send(req);
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8350. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8351. }
  8352. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8353. Request req;
  8354. req.method = "PROPFIND";
  8355. req.path = "/not-dav";
  8356. auto res = cli_.send(req);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8359. }
  8360. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8361. Request req;
  8362. req.method = "UNLOCK";
  8363. req.path = "/dav/dir";
  8364. cli_.set_keep_alive(true);
  8365. auto res = cli_.send(req);
  8366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8367. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8368. EXPECT_EQ("close", res->get_header_value("Connection"));
  8369. EXPECT_FALSE(cli_.is_socket_open());
  8370. }
  8371. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8372. // The mount point serves this path, but only for GET and HEAD.
  8373. auto get_res = cli_.Get("/dir/index.html");
  8374. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8375. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8376. Request req;
  8377. req.method = "PROPFIND";
  8378. req.path = "/dir/index.html";
  8379. auto res = cli_.send(req);
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8382. }
  8383. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8384. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8385. cli_.set_keep_alive(true);
  8386. for (auto i = 0; i < 2; i++) {
  8387. Request req;
  8388. req.method = "PROPFIND";
  8389. req.path = "/dav/dir";
  8390. req.body = xml;
  8391. auto res = cli_.send(req);
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8394. EXPECT_EQ(xml, res->body);
  8395. EXPECT_TRUE(cli_.is_socket_open());
  8396. }
  8397. // A built-in method must still be served on the same connection.
  8398. cli_.set_keep_alive(false);
  8399. auto res = cli_.Get("/hi");
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("close", res->get_header_value("Connection"));
  8403. }
  8404. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8405. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8406. Request req;
  8407. req.method = "PROPFIND";
  8408. req.path = "/dav/dir";
  8409. req.set_header("Expect", "100-continue");
  8410. req.body = xml;
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ(xml, res->body);
  8415. }
  8416. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8418. TEST_F(ServerTest, Gzip) {
  8419. Headers headers;
  8420. headers.emplace("Accept-Encoding", "gzip, deflate");
  8421. auto res = cli_.Get("/compress", headers);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8425. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8426. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8427. "7890123456789012345678901234567890",
  8428. res->body);
  8429. EXPECT_EQ(StatusCode::OK_200, res->status);
  8430. }
  8431. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8432. Headers headers;
  8433. headers.emplace("Accept-Encoding", "gzip, deflate");
  8434. auto res = cli_.Get("/compress-with-charset", headers);
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8437. EXPECT_EQ("application/json; charset=utf-8",
  8438. res->get_header_value("Content-Type"));
  8439. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8440. "7890123456789012345678901234567890",
  8441. res->body);
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8445. Headers headers;
  8446. headers.emplace("Accept-Encoding", "");
  8447. auto res = cli_.Get("/compress", headers);
  8448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8449. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8451. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8452. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8453. "7890123456789012345678901234567890",
  8454. res->body);
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, GzipWithContentReceiver) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "gzip, deflate");
  8460. std::string body;
  8461. auto res =
  8462. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8463. EXPECT_EQ(100U, data_length);
  8464. body.append(data, data_length);
  8465. return true;
  8466. });
  8467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8468. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8470. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8471. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8472. "7890123456789012345678901234567890",
  8473. body);
  8474. EXPECT_EQ(StatusCode::OK_200, res->status);
  8475. }
  8476. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8477. Headers headers;
  8478. headers.emplace("Accept-Encoding", "gzip, deflate");
  8479. cli_.set_decompress(false);
  8480. auto res = cli_.Get("/compress", headers);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8484. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8485. EXPECT_EQ(33U, res->body.size());
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. }
  8488. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8489. Headers headers;
  8490. headers.emplace("Accept-Encoding", "");
  8491. std::string body;
  8492. auto res =
  8493. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8494. EXPECT_EQ(100U, data_length);
  8495. body.append(data, data_length);
  8496. return true;
  8497. });
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8501. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8503. "7890123456789012345678901234567890",
  8504. body);
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. TEST_F(ServerTest, NoGzip) {
  8508. Headers headers;
  8509. headers.emplace("Accept-Encoding", "gzip, deflate");
  8510. auto res = cli_.Get("/nocompress", headers);
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8513. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8514. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8515. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8516. "7890123456789012345678901234567890",
  8517. res->body);
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. }
  8520. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "gzip, deflate");
  8523. std::string body;
  8524. auto res = cli_.Get("/nocompress", headers,
  8525. [&](const char *data, size_t data_length) {
  8526. EXPECT_EQ(100U, data_length);
  8527. body.append(data, data_length);
  8528. return true;
  8529. });
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8532. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8533. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8534. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8535. "7890123456789012345678901234567890",
  8536. body);
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. }
  8539. TEST_F(ServerTest, MultipartFormDataGzip) {
  8540. UploadFormDataItems items = {
  8541. {"key1", "test", "", ""},
  8542. {"key2", "--abcdefg123", "", ""},
  8543. };
  8544. cli_.set_compress(true);
  8545. auto res = cli_.Post("/compress-multipart", items);
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. #endif
  8550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8551. // Static file compression is opt-in, so these run their own server rather than
  8552. // flipping it on for the shared ServerTest fixture, which would silently
  8553. // rewrite what every other static file test is asserting.
  8554. class StaticFileCompressionTest : public ::testing::Test {
  8555. protected:
  8556. void TearDown() override {
  8557. if (t_.joinable()) {
  8558. svr_.stop();
  8559. t_.join();
  8560. }
  8561. }
  8562. int start(const std::function<void(Server &)> &configure = nullptr) {
  8563. // Serves the same tree as a directory of build-time compressed assets
  8564. // would be served: the mount point names the coding the files are already
  8565. // stored in. Registered before "/" so it is the one that matches.
  8566. svr_.set_mount_point("/pre-encoded", "./www",
  8567. {{"Content-Encoding", "gzip"}});
  8568. svr_.set_mount_point("/", "./www");
  8569. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8570. res.set_file_content("./www/dir/index.html", "text/html");
  8571. });
  8572. svr_.Get("/pre-encoded-file-content",
  8573. [](const Request & /*req*/, Response &res) {
  8574. res.set_header("Content-Encoding", "gzip");
  8575. res.set_file_content("./www/dir/index.html", "text/html");
  8576. });
  8577. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8578. res.set_content_provider(
  8579. 6, "text/plain",
  8580. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8581. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8582. return true;
  8583. });
  8584. });
  8585. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8586. res.set_content_provider(
  8587. 1000, "text/plain",
  8588. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8589. if (offset < 100) {
  8590. std::string data(100, 'A');
  8591. sink.write(data.data(), data.size());
  8592. return true;
  8593. }
  8594. std::this_thread::sleep_for(std::chrono::seconds(2));
  8595. std::string data(900, 'B');
  8596. sink.write(data.data(), data.size());
  8597. return true;
  8598. });
  8599. });
  8600. if (configure) { configure(svr_); }
  8601. auto port = svr_.bind_to_any_port(HOST);
  8602. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8603. svr_.wait_until_ready();
  8604. return port;
  8605. }
  8606. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8607. // Every file under ./www except 1MB.txt is smaller than the default
  8608. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8609. // it out of the way.
  8610. static void enable_without_floor(Server &svr) {
  8611. svr.set_static_file_compression(true);
  8612. svr.set_static_file_compression_min_length(0);
  8613. }
  8614. Server svr_;
  8615. std::thread t_;
  8616. };
  8617. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8618. auto port = start();
  8619. Client cli(HOST, port);
  8620. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8624. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8625. EXPECT_EQ(1048576U, res->body.size());
  8626. }
  8627. TEST_F(StaticFileCompressionTest, MountPoint) {
  8628. auto port = start(enable);
  8629. Client cli(HOST, port);
  8630. cli.set_decompress(false);
  8631. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8633. EXPECT_EQ(StatusCode::OK_200, res->status);
  8634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8635. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8636. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8637. // The response stays self-delimiting: a length, not a chunked body.
  8638. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8639. EXPECT_EQ(std::to_string(res->body.size()),
  8640. res->get_header_value("Content-Length"));
  8641. EXPECT_LT(res->body.size(), 1048576U);
  8642. EXPECT_FALSE(res->body.empty());
  8643. }
  8644. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8645. auto port = start(enable);
  8646. Client cli(HOST, port);
  8647. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8649. EXPECT_EQ(StatusCode::OK_200, res->status);
  8650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8651. EXPECT_EQ(1048576U, res->body.size());
  8652. }
  8653. TEST_F(StaticFileCompressionTest, FileContent) {
  8654. auto port = start(enable_without_floor);
  8655. Client cli(HOST, port);
  8656. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8658. EXPECT_EQ(StatusCode::OK_200, res->status);
  8659. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8660. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8661. EXPECT_EQ(104U, res->body.size());
  8662. }
  8663. // A handler that serves an already-encoded file names the coding itself. The
  8664. // file-backed path decided its coding from Accept-Encoding and the content
  8665. // type alone, so it compressed the stored bytes a second time and appended a
  8666. // second Content-Encoding field line.
  8667. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8668. auto port = start(enable_without_floor);
  8669. Client cli(HOST, port);
  8670. cli.set_decompress(false);
  8671. auto res = cli.Get("/pre-encoded-file-content",
  8672. Headers{{"Accept-Encoding", "gzip"}});
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8677. // Vary belongs to a coding the server chose, and it chose none here.
  8678. EXPECT_FALSE(res->has_header("Vary"));
  8679. // The file travels exactly as it is stored on disk.
  8680. EXPECT_EQ(104U, res->body.size());
  8681. }
  8682. // The 1MB file clears the default floor, so this one runs the configuration a
  8683. // deployment would actually have.
  8684. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8685. auto port = start(enable);
  8686. Client cli(HOST, port);
  8687. cli.set_decompress(false);
  8688. auto res =
  8689. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8693. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8694. EXPECT_FALSE(res->has_header("Vary"));
  8695. EXPECT_EQ(1048576U, res->body.size());
  8696. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8697. }
  8698. TEST_F(StaticFileCompressionTest, Head) {
  8699. auto port = start(enable);
  8700. Client cli(HOST, port);
  8701. cli.set_decompress(false);
  8702. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8703. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8704. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8706. EXPECT_EQ(StatusCode::OK_200, res->status);
  8707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8708. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8709. // HEAD still reports the size a GET would return.
  8710. EXPECT_EQ(get->get_header_value("Content-Length"),
  8711. res->get_header_value("Content-Length"));
  8712. EXPECT_TRUE(res->body.empty());
  8713. }
  8714. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8715. auto port = start(enable);
  8716. Client cli(HOST, port);
  8717. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8718. {"Accept-Encoding", "gzip"}});
  8719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8721. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8722. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8723. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8724. EXPECT_EQ("cd", res->body);
  8725. }
  8726. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8727. auto port = start(enable);
  8728. Client cli(HOST, port);
  8729. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8733. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8734. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8735. }
  8736. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8737. auto port = start(enable);
  8738. Client cli(HOST, port);
  8739. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::OK_200, res->status);
  8742. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8743. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8744. EXPECT_TRUE(res->body.empty());
  8745. }
  8746. TEST_F(StaticFileCompressionTest, MinLength) {
  8747. auto port = start(enable);
  8748. Client cli(HOST, port);
  8749. // 104 bytes, well under the default floor. Compressing it would add the
  8750. // gzip header and trailer to a body that already fits in one packet.
  8751. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8753. EXPECT_EQ(StatusCode::OK_200, res->status);
  8754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8755. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8756. }
  8757. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8758. auto port = start([](Server &svr) {
  8759. svr.set_static_file_compression(true);
  8760. svr.set_static_file_compression_min_length(1);
  8761. });
  8762. Client cli(HOST, port);
  8763. cli.set_decompress(false);
  8764. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8767. // A 9-byte file comes back larger than it went in, because gzip's header and
  8768. // trailer outweigh anything deflate can save. That is the end of the range
  8769. // the floor exists to keep out.
  8770. EXPECT_GT(res->body.size(), 9U);
  8771. }
  8772. TEST_F(StaticFileCompressionTest, MaxLength) {
  8773. auto port = start([](Server &svr) {
  8774. svr.set_static_file_compression(true);
  8775. svr.set_static_file_compression_min_length(0);
  8776. svr.set_static_file_compression_max_length(1024);
  8777. });
  8778. Client cli(HOST, port);
  8779. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8780. // defines `small` as a macro on Windows.
  8781. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8782. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8783. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8784. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8785. // Under it: compressed.
  8786. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8787. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8788. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8789. }
  8790. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8791. auto port = start(enable_without_floor);
  8792. Client cli(HOST, port);
  8793. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8794. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8795. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8796. auto identity_etag = identity->get_header_value("ETag");
  8797. ASSERT_FALSE(identity_etag.empty());
  8798. auto gzipped =
  8799. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8800. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8801. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8802. auto gzip_etag = gzipped->get_header_value("ETag");
  8803. ASSERT_FALSE(gzip_etag.empty());
  8804. // Two representations, two validators.
  8805. EXPECT_NE(identity_etag, gzip_etag);
  8806. // Each one revalidates against the request that would produce it...
  8807. auto fresh =
  8808. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8809. {"If-None-Match", gzip_etag}});
  8810. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8811. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8812. auto fresh_identity =
  8813. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8814. {"If-None-Match", identity_etag}});
  8815. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8816. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8817. // ...and not against the other representation.
  8818. auto crossed =
  8819. cli.Get("/dir/index.html",
  8820. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8821. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8822. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8823. }
  8824. // The opt-in covers responses the server reads off disk itself. A caller's own
  8825. // known-length provider keeps its Content-Length and, more importantly, keeps
  8826. // delivering incrementally: routing it through a compressor would hold every
  8827. // write back until zlib's window filled.
  8828. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8829. auto port = start(enable);
  8830. Client cli(HOST, port);
  8831. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8835. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("aaabbb", res->body);
  8837. }
  8838. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8839. auto port = start(enable);
  8840. Client cli(HOST, port);
  8841. cli.set_read_timeout(1, 0);
  8842. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8843. Headers{{"Accept-Encoding", "gzip"}});
  8844. ASSERT_TRUE(handle.is_valid());
  8845. // The provider writes 100 bytes and then stalls for longer than the read
  8846. // timeout. Those first bytes have to arrive anyway: run the response through
  8847. // a compressor and zlib holds them until its window fills, so the read would
  8848. // come back empty instead.
  8849. char buf[256];
  8850. auto n = handle.read(buf, sizeof(buf));
  8851. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8852. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8853. }
  8854. #endif
  8855. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8856. TEST_F(ServerTest, Brotli) {
  8857. Headers headers;
  8858. headers.emplace("Accept-Encoding", "br");
  8859. auto res = cli_.Get("/compress", headers);
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8865. "7890123456789012345678901234567890",
  8866. res->body);
  8867. EXPECT_EQ(StatusCode::OK_200, res->status);
  8868. }
  8869. #endif
  8870. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8871. TEST_F(ServerTest, Zstd) {
  8872. Headers headers;
  8873. headers.emplace("Accept-Encoding", "zstd");
  8874. auto res = cli_.Get("/compress", headers);
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8878. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8879. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8880. "7890123456789012345678901234567890",
  8881. res->body);
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. }
  8884. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8885. Headers headers;
  8886. headers.emplace("Accept-Encoding", "");
  8887. auto res = cli_.Get("/compress", headers);
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8890. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8891. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8893. "7890123456789012345678901234567890",
  8894. res->body);
  8895. EXPECT_EQ(StatusCode::OK_200, res->status);
  8896. }
  8897. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8898. Headers headers;
  8899. headers.emplace("Accept-Encoding", "zstd");
  8900. std::string body;
  8901. auto res =
  8902. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8903. EXPECT_EQ(100U, data_length);
  8904. body.append(data, data_length);
  8905. return true;
  8906. });
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8910. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8912. "7890123456789012345678901234567890",
  8913. body);
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8917. Headers headers;
  8918. headers.emplace("Accept-Encoding", "zstd");
  8919. cli_.set_decompress(false);
  8920. auto res = cli_.Get("/compress", headers);
  8921. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8922. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8923. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8924. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8926. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8928. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8929. EXPECT_EQ(StatusCode::OK_200, res->status);
  8930. ASSERT_EQ(26U, res->body.size());
  8931. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8932. 0);
  8933. }
  8934. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8935. Headers headers;
  8936. headers.emplace("Accept-Encoding", "");
  8937. std::string body;
  8938. auto res =
  8939. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8940. EXPECT_EQ(100U, data_length);
  8941. body.append(data, data_length);
  8942. return true;
  8943. });
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8947. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8948. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8949. "7890123456789012345678901234567890",
  8950. body);
  8951. EXPECT_EQ(StatusCode::OK_200, res->status);
  8952. }
  8953. TEST_F(ServerTest, NoZstd) {
  8954. Headers headers;
  8955. headers.emplace("Accept-Encoding", "zstd");
  8956. auto res = cli_.Get("/nocompress", headers);
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8959. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8960. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8962. "7890123456789012345678901234567890",
  8963. res->body);
  8964. EXPECT_EQ(StatusCode::OK_200, res->status);
  8965. }
  8966. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8967. Headers headers;
  8968. headers.emplace("Accept-Encoding", "zstd");
  8969. std::string body;
  8970. auto res = cli_.Get("/nocompress", headers,
  8971. [&](const char *data, size_t data_length) {
  8972. EXPECT_EQ(100U, data_length);
  8973. body.append(data, data_length);
  8974. return true;
  8975. });
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8978. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8979. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8980. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8981. "7890123456789012345678901234567890",
  8982. body);
  8983. EXPECT_EQ(StatusCode::OK_200, res->status);
  8984. }
  8985. // TODO: How to enable zstd ??
  8986. TEST_F(ServerTest, MultipartFormDataZstd) {
  8987. UploadFormDataItems items = {
  8988. {"key1", "test", "", ""},
  8989. {"key2", "--abcdefg123", "", ""},
  8990. };
  8991. Headers headers;
  8992. headers.emplace("Accept-Encoding", "zstd");
  8993. cli_.set_compress(true);
  8994. auto res = cli_.Post("/compress-multipart", headers, items);
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. }
  8998. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8999. Headers headers;
  9000. headers.emplace("Accept-Encoding", "zstd");
  9001. cli_.set_compress(true);
  9002. auto res = cli_.Put(
  9003. "/put", headers, 3,
  9004. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9005. sink.os << "PUT";
  9006. return true;
  9007. },
  9008. "text/plain");
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::OK_200, res->status);
  9011. EXPECT_EQ("PUT", res->body);
  9012. }
  9013. // Pre-compression logging tests
  9014. TEST_F(ServerTest, PreCompressionLogging) {
  9015. // Test data for compression (matches the actual /compress endpoint content)
  9016. const std::string test_content =
  9017. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9018. "3456789012345678901234567890";
  9019. // Variables to capture logging data
  9020. std::string pre_compression_body;
  9021. std::string pre_compression_content_type;
  9022. std::string pre_compression_content_encoding;
  9023. std::string post_compression_body;
  9024. std::string post_compression_content_type;
  9025. std::string post_compression_content_encoding;
  9026. // Set up pre-compression logger
  9027. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9028. const Response &res) {
  9029. pre_compression_body = res.body;
  9030. pre_compression_content_type = res.get_header_value("Content-Type");
  9031. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9032. });
  9033. // Set up post-compression logger
  9034. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9035. post_compression_body = res.body;
  9036. post_compression_content_type = res.get_header_value("Content-Type");
  9037. post_compression_content_encoding =
  9038. res.get_header_value("Content-Encoding");
  9039. });
  9040. // Test with gzip compression
  9041. Headers headers;
  9042. headers.emplace("Accept-Encoding", "gzip");
  9043. auto res = cli_.Get("/compress", headers);
  9044. // Verify response was compressed
  9045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9046. EXPECT_EQ(StatusCode::OK_200, res->status);
  9047. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9048. // Verify pre-compression logger captured uncompressed content
  9049. EXPECT_EQ(test_content, pre_compression_body);
  9050. EXPECT_EQ("text/plain", pre_compression_content_type);
  9051. EXPECT_TRUE(pre_compression_content_encoding
  9052. .empty()); // No encoding header before compression
  9053. // Verify post-compression logger captured compressed content
  9054. EXPECT_NE(test_content,
  9055. post_compression_body); // Should be different after compression
  9056. EXPECT_EQ("text/plain", post_compression_content_type);
  9057. EXPECT_EQ("gzip", post_compression_content_encoding);
  9058. // Verify compressed content is smaller
  9059. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. std::string post_compression_body;
  9067. svr_.set_pre_compression_logger(
  9068. [&](const Request & /*req*/, const Response &res) {
  9069. pre_compression_body = res.body;
  9070. });
  9071. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9072. post_compression_body = res.body;
  9073. });
  9074. Headers headers;
  9075. headers.emplace("Accept-Encoding", "br");
  9076. auto res = cli_.Get("/compress", headers);
  9077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9078. EXPECT_EQ(StatusCode::OK_200, res->status);
  9079. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9080. // Verify pre-compression content is uncompressed
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. // Verify post-compression content is compressed
  9083. EXPECT_NE(test_content, post_compression_body);
  9084. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9085. }
  9086. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9087. const std::string test_content =
  9088. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9089. "3456789012345678901234567890";
  9090. std::string pre_compression_body;
  9091. std::string post_compression_body;
  9092. svr_.set_pre_compression_logger(
  9093. [&](const Request & /*req*/, const Response &res) {
  9094. pre_compression_body = res.body;
  9095. });
  9096. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9097. post_compression_body = res.body;
  9098. });
  9099. // Request without compression (use /nocompress endpoint)
  9100. Headers headers;
  9101. auto res = cli_.Get("/nocompress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ(StatusCode::OK_200, res->status);
  9104. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9105. // Pre-compression logger should not be called when no compression is applied
  9106. EXPECT_TRUE(
  9107. pre_compression_body.empty()); // Pre-compression logger not called
  9108. EXPECT_EQ(
  9109. test_content,
  9110. post_compression_body); // Post-compression logger captures final content
  9111. }
  9112. TEST_F(ServerTest, LoggerSeesContentLength) {
  9113. size_t logged_content_length = 0;
  9114. std::string logged_content_length_header;
  9115. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9116. logged_content_length = res.content_length_;
  9117. logged_content_length_header = res.get_header_value("Content-Length");
  9118. });
  9119. auto res = cli_.Get("/nocompress");
  9120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ(res->body.size(), logged_content_length);
  9123. EXPECT_EQ(std::to_string(logged_content_length),
  9124. logged_content_length_header);
  9125. }
  9126. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9127. const std::string test_content =
  9128. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9129. "3456789012345678901234567890";
  9130. std::string pre_compression_body;
  9131. bool pre_logger_called = false;
  9132. // Set only pre-compression logger
  9133. svr_.set_pre_compression_logger(
  9134. [&](const Request & /*req*/, const Response &res) {
  9135. pre_compression_body = res.body;
  9136. pre_logger_called = true;
  9137. });
  9138. Headers headers;
  9139. headers.emplace("Accept-Encoding", "gzip");
  9140. auto res = cli_.Get("/compress", headers);
  9141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9142. EXPECT_EQ(StatusCode::OK_200, res->status);
  9143. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9144. // Verify pre-compression logger was called
  9145. EXPECT_TRUE(pre_logger_called);
  9146. EXPECT_EQ(test_content, pre_compression_body);
  9147. }
  9148. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9149. {
  9150. // Test with Expect: 100-continue header - success case
  9151. // Server returns 100 Continue, client sends body, server returns 200 OK
  9152. Request req;
  9153. req.method = "POST";
  9154. req.path = "/post-large";
  9155. req.set_header("Expect", "100-continue");
  9156. req.body = LARGE_DATA;
  9157. Response res;
  9158. auto error = Error::Success;
  9159. cli_.set_keep_alive(true);
  9160. auto ret = cli_.send(req, res, error);
  9161. EXPECT_TRUE(ret);
  9162. EXPECT_EQ(StatusCode::OK_200, res.status);
  9163. EXPECT_EQ(LARGE_DATA, res.body);
  9164. }
  9165. {
  9166. // Test with Expect: 100-continue header - error case
  9167. // Client should not send the body when server returns an error
  9168. Request req;
  9169. req.method = "POST";
  9170. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9171. req.set_header("Expect", "100-continue");
  9172. req.body = LARGE_DATA;
  9173. Response res;
  9174. auto error = Error::Success;
  9175. auto start = std::chrono::high_resolution_clock::now();
  9176. cli_.set_keep_alive(true);
  9177. auto ret = cli_.send(req, res, error);
  9178. auto end = std::chrono::high_resolution_clock::now();
  9179. auto elapsed =
  9180. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9181. .count();
  9182. // With Expect: 100-continue, request completes successfully but with error
  9183. EXPECT_TRUE(ret);
  9184. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9185. EXPECT_EQ("close", res.get_header_value("Connection"));
  9186. EXPECT_FALSE(cli_.is_socket_open());
  9187. EXPECT_LE(elapsed, 2000);
  9188. }
  9189. {
  9190. // Send an extra GET request to ensure error recovery without hanging
  9191. Request req;
  9192. req.method = "GET";
  9193. req.path = "/hi";
  9194. auto start = std::chrono::high_resolution_clock::now();
  9195. auto res = cli_.send(req);
  9196. auto end = std::chrono::high_resolution_clock::now();
  9197. auto elapsed =
  9198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9199. .count();
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ(StatusCode::OK_200, res->status);
  9202. EXPECT_EQ("Hello World!", res->body);
  9203. EXPECT_LE(elapsed, 500);
  9204. }
  9205. }
  9206. TEST(ZstdDecompressor, ChunkedDecompression) {
  9207. std::string data;
  9208. for (size_t i = 0; i < 32 * 1024; ++i) {
  9209. data.push_back(static_cast<char>('a' + i % 26));
  9210. }
  9211. std::string compressed_data;
  9212. {
  9213. httplib::detail::zstd_compressor compressor;
  9214. bool result = compressor.compress(
  9215. data.data(), data.size(),
  9216. /*last=*/true,
  9217. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9218. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9219. compressed_data_size);
  9220. return true;
  9221. });
  9222. ASSERT_TRUE(result);
  9223. }
  9224. std::string decompressed_data;
  9225. {
  9226. httplib::detail::zstd_decompressor decompressor;
  9227. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9228. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9229. size_t chunk_size = 130;
  9230. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9231. chunk_begin += chunk_size) {
  9232. size_t current_chunk_size =
  9233. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9234. bool result = decompressor.decompress(
  9235. compressed_data.data() + chunk_begin, current_chunk_size,
  9236. [&](const char *decompressed_data_chunk,
  9237. size_t decompressed_data_chunk_size) {
  9238. decompressed_data.insert(decompressed_data.size(),
  9239. decompressed_data_chunk,
  9240. decompressed_data_chunk_size);
  9241. return true;
  9242. });
  9243. ASSERT_TRUE(result);
  9244. }
  9245. }
  9246. ASSERT_EQ(data, decompressed_data);
  9247. }
  9248. TEST(ZstdDecompressor, Decompress) {
  9249. std::string original_text = "Compressed with ZSTD";
  9250. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9251. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9252. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9253. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9254. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9255. std::string decompressed_data;
  9256. {
  9257. httplib::detail::zstd_decompressor decompressor;
  9258. bool result = decompressor.decompress(
  9259. compressed_data.data(), compressed_data.size(),
  9260. [&](const char *decompressed_data_chunk,
  9261. size_t decompressed_data_chunk_size) {
  9262. decompressed_data.insert(decompressed_data.size(),
  9263. decompressed_data_chunk,
  9264. decompressed_data_chunk_size);
  9265. return true;
  9266. });
  9267. ASSERT_TRUE(result);
  9268. }
  9269. ASSERT_EQ(original_text, decompressed_data);
  9270. }
  9271. #endif
  9272. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9273. // separate chunks so that the server sees each part in its own read(). Used to
  9274. // place a read boundary at a specific offset of a request body.
  9275. static bool send_request_in_parts(time_t read_timeout_sec,
  9276. const std::vector<std::string> &parts,
  9277. std::string *resp = nullptr,
  9278. int port = PORT) {
  9279. auto error = Error::Success;
  9280. auto client_sock = detail::create_client_socket(
  9281. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9282. /*connection_timeout_sec=*/5, 0,
  9283. /*read_timeout_sec=*/5, 0,
  9284. /*write_timeout_sec=*/5, 0, std::string(), error);
  9285. if (client_sock == INVALID_SOCKET) { return false; }
  9286. auto ret = detail::process_client_socket(
  9287. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9288. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9289. for (size_t i = 0; i < parts.size(); i++) {
  9290. const auto &part = parts[i];
  9291. if (part.size() !=
  9292. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9293. return false;
  9294. }
  9295. if (i + 1 < parts.size()) {
  9296. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9297. }
  9298. }
  9299. char buf[512];
  9300. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9301. while (line_reader.getline()) {
  9302. if (resp) { *resp += line_reader.ptr(); }
  9303. }
  9304. return true;
  9305. });
  9306. detail::close_socket(client_sock);
  9307. return ret;
  9308. }
  9309. // Sends a raw request to a server listening at HOST:PORT.
  9310. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9311. std::string *resp = nullptr, int port = PORT) {
  9312. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9313. }
  9314. #ifdef CPPHTTPLIB_SSL_ENABLED
  9315. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9317. ASSERT_TRUE(svr.is_valid());
  9318. svr.set_read_timeout(1, 0);
  9319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9320. auto se = detail::scope_exit([&] {
  9321. svr.stop();
  9322. t.join();
  9323. ASSERT_FALSE(svr.is_running());
  9324. });
  9325. svr.wait_until_ready();
  9326. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9327. // keeps each wait well within the read timeout. The server gives up a
  9328. // second in, so the bytes sent after that fail.
  9329. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9330. parts.resize(26, std::string(1, '\0'));
  9331. EXPECT_FALSE(send_request_in_parts(5, parts));
  9332. }
  9333. #endif
  9334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9335. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9336. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9337. const std::vector<std::string> &parts,
  9338. std::string *resp = nullptr,
  9339. int port = PORT) {
  9340. auto error = Error::Success;
  9341. auto sock = detail::create_client_socket(
  9342. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9343. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9344. /*write_timeout_sec=*/5, 0, std::string(), error);
  9345. if (sock == INVALID_SOCKET) { return false; }
  9346. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9347. auto ctx = SSL_CTX_new(TLS_client_method());
  9348. auto ssl = SSL_new(ctx);
  9349. auto ssl_se = detail::scope_exit([&] {
  9350. SSL_free(ssl);
  9351. SSL_CTX_free(ctx);
  9352. });
  9353. SSL_set_fd(ssl, static_cast<int>(sock));
  9354. if (SSL_connect(ssl) != 1) { return false; }
  9355. for (size_t i = 0; i < parts.size(); i++) {
  9356. const auto &part = parts[i];
  9357. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9358. static_cast<int>(part.size())) {
  9359. return false;
  9360. }
  9361. if (i + 1 < parts.size()) {
  9362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9363. }
  9364. }
  9365. char buf[512];
  9366. int n;
  9367. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9368. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9369. }
  9370. return true;
  9371. }
  9372. #endif
  9373. // The request line, then a header value a byte at a time.
  9374. static std::vector<std::string> slow_request_head_parts() {
  9375. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9376. parts.resize(26, "a");
  9377. parts.emplace_back("\r\n\r\n");
  9378. return parts;
  9379. }
  9380. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9381. // within the one-second read timeout. The server gives up a second in, before
  9382. // the head is complete.
  9383. static void
  9384. expect_slow_request_head_dropped(Server &svr,
  9385. const std::function<std::string()> &send) {
  9386. std::atomic<bool> handled(false);
  9387. svr.Get("/", [&](const Request &, Response &res) {
  9388. handled = true;
  9389. res.set_content("ok", "text/plain");
  9390. });
  9391. svr.set_read_timeout(1, 0);
  9392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9393. auto se = detail::scope_exit([&] {
  9394. svr.stop();
  9395. t.join();
  9396. ASSERT_FALSE(svr.is_running());
  9397. });
  9398. svr.wait_until_ready();
  9399. auto resp = send();
  9400. EXPECT_FALSE(handled);
  9401. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9402. }
  9403. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9404. Server svr;
  9405. expect_slow_request_head_dropped(svr, [] {
  9406. std::string resp;
  9407. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9408. return resp;
  9409. });
  9410. }
  9411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9412. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9414. ASSERT_TRUE(svr.is_valid());
  9415. expect_slow_request_head_dropped(svr, [] {
  9416. std::string resp;
  9417. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9418. return resp;
  9419. });
  9420. }
  9421. #endif
  9422. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9423. Server svr;
  9424. std::string header_value;
  9425. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9426. header_value = req.get_header_value("foo");
  9427. res.set_content("ok", "text/plain");
  9428. });
  9429. thread t = thread([&] { svr.listen(HOST, PORT); });
  9430. auto se = detail::scope_exit([&] {
  9431. svr.stop();
  9432. t.join();
  9433. ASSERT_FALSE(svr.is_running());
  9434. });
  9435. svr.wait_until_ready();
  9436. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9437. // like characters are not treated the same - use vertical tab and escape.
  9438. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9439. "foo: \t \v bar \x1B\t \r\n"
  9440. "Connection: close\r\n"
  9441. "\r\n";
  9442. std::string res;
  9443. ASSERT_TRUE(send_request(5, req, &res));
  9444. EXPECT_EQ(header_value, "");
  9445. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9446. }
  9447. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9448. Server svr;
  9449. std::string received;
  9450. svr.Get("/order", [&](const Request &req, Response &res) {
  9451. received = entries_to_string(req.headers);
  9452. res.set_content("ok", "text/plain");
  9453. });
  9454. auto port = svr.bind_to_any_port(HOST);
  9455. thread t = thread([&] { svr.listen_after_bind(); });
  9456. auto se = detail::scope_exit([&] {
  9457. svr.stop();
  9458. t.join();
  9459. ASSERT_FALSE(svr.is_running());
  9460. });
  9461. svr.wait_until_ready();
  9462. const std::string req = "GET /order HTTP/1.1\r\n"
  9463. "Host: localhost\r\n"
  9464. "X-First: 1\r\n"
  9465. "X-Dup: a\r\n"
  9466. "X-Second: 2\r\n"
  9467. "X-Dup: b\r\n"
  9468. "Connection: close\r\n"
  9469. "\r\n";
  9470. std::string res;
  9471. ASSERT_TRUE(send_request(5, req, &res, port));
  9472. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9473. EXPECT_EQ(
  9474. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9475. received);
  9476. }
  9477. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9478. Server svr;
  9479. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9480. res.set_header("Set-Cookie", "first=1");
  9481. res.set_header("X-Between", "y");
  9482. res.set_header("Set-Cookie", "second=2");
  9483. res.set_content("ok", "text/plain");
  9484. });
  9485. auto port = svr.bind_to_any_port(HOST);
  9486. thread t = thread([&] { svr.listen_after_bind(); });
  9487. auto se = detail::scope_exit([&] {
  9488. svr.stop();
  9489. t.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. Client cli(HOST, port);
  9494. auto res = cli.Get("/cookies");
  9495. ASSERT_TRUE(res);
  9496. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9497. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9498. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9499. }
  9500. // A stream may send a byte at a time with a small extension on each chunk,
  9501. // however long it runs
  9502. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9503. Server svr;
  9504. svr.Post("/count", [](const Request &req, Response &res) {
  9505. res.set_content(std::to_string(req.body.size()), "text/plain");
  9506. });
  9507. auto port = svr.bind_to_any_port(HOST);
  9508. ASSERT_LT(0, port);
  9509. thread t = thread([&] { svr.listen_after_bind(); });
  9510. auto se = detail::scope_exit([&] {
  9511. svr.stop();
  9512. t.join();
  9513. ASSERT_FALSE(svr.is_running());
  9514. });
  9515. svr.wait_until_ready();
  9516. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9517. "\r\nTransfer-Encoding: chunked\r\n"
  9518. "Connection: close\r\n\r\n";
  9519. for (auto i = 0; i < 4096; i++) {
  9520. req += "1;a=b\r\nx\r\n";
  9521. }
  9522. req += "0\r\n\r\n";
  9523. std::string res;
  9524. ASSERT_TRUE(send_request(5, req, &res, port));
  9525. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9526. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9527. }
  9528. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9529. Server svr;
  9530. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9531. auto i = new int(0);
  9532. res.set_header("Trailer", "X-Safe, X-Reflected");
  9533. res.set_chunked_content_provider(
  9534. "text/plain",
  9535. [i](size_t /*offset*/, DataSink &sink) {
  9536. if (*i == 0) {
  9537. sink.os << "body";
  9538. } else {
  9539. Headers trailer;
  9540. // A valid trailer that must survive.
  9541. trailer.emplace("X-Safe", "safe");
  9542. // Attacker-controlled value carrying CR/LF (response splitting).
  9543. trailer.emplace("X-Reflected",
  9544. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9545. // Attacker-controlled name carrying CR/LF.
  9546. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9547. sink.done_with_trailer(trailer);
  9548. }
  9549. (*i)++;
  9550. return true;
  9551. },
  9552. [i](bool /*success*/) { delete i; });
  9553. });
  9554. thread t = thread([&] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9562. "Host: " + HOST +
  9563. "\r\n"
  9564. "Connection: close\r\n"
  9565. "\r\n";
  9566. std::string res;
  9567. ASSERT_TRUE(send_request(5, req, &res));
  9568. // The injected fields must not appear anywhere in the raw response.
  9569. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9570. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9571. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9572. // Invalid trailers are dropped entirely, matching set_header().
  9573. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9574. // The valid trailer still passes through.
  9575. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9576. }
  9577. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9578. // A custom header writer gets only the fields the default one writes
  9579. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9580. std::string s;
  9581. for (const auto &h : hdrs) {
  9582. s += h.first + ": " + h.second + "\r\n";
  9583. }
  9584. s += "\r\n";
  9585. return strm.write(s.data(), s.size());
  9586. };
  9587. for (auto custom_writer : {false, true}) {
  9588. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9589. Server svr;
  9590. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9591. svr.set_post_routing_handler([](const Request &, Response &res) {
  9592. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9593. });
  9594. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9595. // res.headers is a public field an application can populate directly,
  9596. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9597. // A valid header that must survive.
  9598. res.headers.emplace("X-Safe", "safe");
  9599. // Attacker-controlled value carrying CR/LF (response splitting).
  9600. res.headers.emplace("X-Reflected",
  9601. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9602. // Attacker-controlled name carrying CR/LF.
  9603. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9604. res.set_content("body", "text/plain");
  9605. });
  9606. thread t = thread([&] { svr.listen(HOST, PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. ASSERT_FALSE(svr.is_running());
  9611. });
  9612. svr.wait_until_ready();
  9613. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9614. "Host: " + HOST +
  9615. "\r\n"
  9616. "Connection: close\r\n"
  9617. "\r\n";
  9618. std::string res;
  9619. ASSERT_TRUE(send_request(5, req, &res));
  9620. // The injected fields must not appear anywhere in the raw response.
  9621. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9622. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9623. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9624. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9625. // Invalid headers are dropped entirely, matching set_header().
  9626. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9627. // The valid header still passes through.
  9628. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9629. }
  9630. }
  9631. // Forward declaration: in split builds split.py strips `inline` and moves the
  9632. // definition into httplib.cc, so detail::write_request_line is not visible from
  9633. // the public httplib.h. Re-declaring it here lets the tests link against the
  9634. // symbol in both header-only and split builds.
  9635. namespace httplib {
  9636. namespace detail {
  9637. ssize_t write_request_line(Stream &strm, const std::string &method,
  9638. const std::string &path);
  9639. } // namespace detail
  9640. } // namespace httplib
  9641. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9642. // A well-formed target is written verbatim.
  9643. {
  9644. detail::BufferStream strm;
  9645. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9646. EXPECT_GT(n, 0);
  9647. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9648. }
  9649. // A target carrying CR/LF, SP or other control octets must be rejected
  9650. // before anything reaches the wire, otherwise it splits the request line and
  9651. // injects a header or a whole request.
  9652. const std::string evil_targets[] = {
  9653. "/a\r\nInjected: pwned",
  9654. "/a\rInjected",
  9655. "/a\nInjected",
  9656. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9657. "/a b",
  9658. "/a\tb",
  9659. "/a\x7f",
  9660. };
  9661. for (const auto &evil : evil_targets) {
  9662. detail::BufferStream strm;
  9663. auto n = detail::write_request_line(strm, "GET", evil);
  9664. EXPECT_LT(n, 0);
  9665. EXPECT_TRUE(strm.get_buffer().empty());
  9666. }
  9667. }
  9668. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9669. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9670. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9671. // target reaches write_request. The client must fail cleanly with
  9672. // Error::Write instead of putting a request-line-less, header-injecting
  9673. // request on the wire.
  9674. Server svr;
  9675. svr.Get("/a", [](const Request &, Response &res) {
  9676. res.set_content("ok", "text/plain");
  9677. });
  9678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. thread.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. });
  9684. svr.wait_until_ready();
  9685. {
  9686. Client cli(HOST, PORT);
  9687. cli.set_path_encode(false);
  9688. // The request is rejected before anything is written, so the connection
  9689. // stays silent and the subsequent response read would otherwise block for
  9690. // the full default read timeout. Shorten it -- the assertion is on the
  9691. // error, not the timeout.
  9692. cli.set_read_timeout(1, 0);
  9693. auto res = cli.Get("/a\r\nInjected: pwned");
  9694. EXPECT_FALSE(res);
  9695. EXPECT_EQ(Error::Write, res.error());
  9696. }
  9697. }
  9698. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9699. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9700. // including extension methods.
  9701. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9702. for (const auto &method : good_methods) {
  9703. detail::BufferStream strm;
  9704. auto n = detail::write_request_line(strm, method, "/");
  9705. EXPECT_GT(n, 0);
  9706. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9707. }
  9708. // A method carrying CR/LF would split the request line and smuggle a whole
  9709. // request ahead of the real one. A space or an empty method corrupts the
  9710. // request line. All must be rejected before anything reaches the wire.
  9711. const std::string evil_methods[] = {
  9712. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9713. "GET\r\nInjected: pwned",
  9714. "GET\r",
  9715. "GET\n",
  9716. "GE T",
  9717. "",
  9718. };
  9719. for (const auto &evil : evil_methods) {
  9720. detail::BufferStream strm;
  9721. auto n = detail::write_request_line(strm, evil, "/");
  9722. EXPECT_LT(n, 0);
  9723. EXPECT_TRUE(strm.get_buffer().empty());
  9724. }
  9725. }
  9726. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9727. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9728. // through Client::send must fail with Error::Write and no request, neither
  9729. // the smuggled one nor the real one, may reach the server.
  9730. Server svr;
  9731. std::atomic<int> request_count(0);
  9732. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9733. request_count++;
  9734. res.status = StatusCode::OK_200;
  9735. return Server::HandlerResponse::Handled;
  9736. });
  9737. auto port = svr.bind_to_any_port(HOST);
  9738. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9739. auto se = detail::scope_exit([&] {
  9740. svr.stop();
  9741. thread.join();
  9742. ASSERT_FALSE(svr.is_running());
  9743. });
  9744. svr.wait_until_ready();
  9745. {
  9746. Client cli(HOST, port);
  9747. const std::string evil_methods[] = {
  9748. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9749. "GE T",
  9750. "",
  9751. };
  9752. for (const auto &evil : evil_methods) {
  9753. Request req;
  9754. req.method = evil;
  9755. req.path = "/";
  9756. auto res = cli.send(req);
  9757. EXPECT_FALSE(res);
  9758. EXPECT_EQ(Error::Write, res.error());
  9759. }
  9760. auto handle =
  9761. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9762. EXPECT_FALSE(handle.is_valid());
  9763. EXPECT_EQ(Error::Write, handle.error);
  9764. // A valid request on the same client still goes through.
  9765. auto res = cli.Get("/");
  9766. ASSERT_TRUE(res);
  9767. EXPECT_EQ(StatusCode::OK_200, res->status);
  9768. }
  9769. EXPECT_EQ(1, request_count.load());
  9770. }
  9771. // Sends a raw request and verifies that there isn't a crash or exception.
  9772. static void test_raw_request(const std::string &req,
  9773. std::string *out = nullptr) {
  9774. Server svr;
  9775. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9776. res.set_content("ok", "text/plain");
  9777. });
  9778. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9779. res.set_content("ok", "text/plain");
  9780. });
  9781. svr.Get("/header_field_value_check",
  9782. [&](const Request & /*req*/, Response &res) {
  9783. res.set_content("ok", "text/plain");
  9784. });
  9785. svr.CustomRoute("PROPFIND", "/dav",
  9786. [&](const Request & /*req*/, Response &res) {
  9787. res.status = StatusCode::MultiStatus_207;
  9788. });
  9789. // Server read timeout must be longer than the client read timeout for the
  9790. // bug to reproduce, probably to force the server to process a request
  9791. // without a trailing blank line.
  9792. const time_t client_read_timeout_sec = 1;
  9793. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9794. bool listen_thread_ok = false;
  9795. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9796. auto se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. t.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. EXPECT_TRUE(listen_thread_ok);
  9801. });
  9802. svr.wait_until_ready();
  9803. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9804. }
  9805. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9806. // A certain header line causes an exception if the header property is parsed
  9807. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9808. test_raw_request(
  9809. "GET /hi HTTP/1.1\r\n"
  9810. " : "
  9811. " "
  9812. " ");
  9813. }
  9814. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9815. // A certain header line causes an exception if the header property *name* is
  9816. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9817. // greedy matcher and requires backtracking when there are a lot of ":"
  9818. // characters.
  9819. // This occurs with libc++ but not libstdc++.
  9820. test_raw_request(
  9821. "GET /hi HTTP/1.1\r\n"
  9822. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9823. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9824. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9825. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9826. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9827. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9828. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9829. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9830. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9831. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9832. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9833. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9834. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9835. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9836. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9837. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9838. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9839. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9840. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9841. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9842. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9843. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9844. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9845. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9846. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9847. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9848. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9849. "&&&%%%");
  9850. }
  9851. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9852. // Make sure this doesn't crash the server.
  9853. // In a previous version of the header line regex, the "\r" rendered the line
  9854. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9855. // a new position where the leading white space ended and the field value
  9856. // began.
  9857. // The crash occurs with libc++ but not libstdc++.
  9858. test_raw_request("GET /hi HTTP/1.1\r\n"
  9859. "a:" +
  9860. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9861. "\r\n"
  9862. "\r\n");
  9863. }
  9864. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9865. const char *rejected[] = {
  9866. // RFC 9112 §3: one SP between the parts, and nothing else
  9867. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9868. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9869. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9870. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9871. // A request-target has no fragment
  9872. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9873. // An HTTP/1.1 request needs a Host
  9874. "GET /hi HTTP/1.1\r\n\r\n",
  9875. };
  9876. for (auto request : rejected) {
  9877. std::string out;
  9878. test_raw_request(request, &out);
  9879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9880. }
  9881. std::string out;
  9882. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9883. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9884. }
  9885. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9886. // RFC 9112 §6.1
  9887. const char *requests[] = {
  9888. "PUT /put_hi HTTP/1.1\r\n"
  9889. "Host: localhost\r\n"
  9890. "Content-Length: 0\r\n"
  9891. "Transfer-Encoding: chunked\r\n"
  9892. "\r\n"
  9893. "0\r\n\r\n",
  9894. "PUT /put_hi HTTP/1.0\r\n"
  9895. "Connection: keep-alive\r\n"
  9896. "Transfer-Encoding: chunked\r\n"
  9897. "\r\n"
  9898. "0\r\n\r\n",
  9899. };
  9900. for (auto request : requests) {
  9901. std::string out;
  9902. test_raw_request(request, &out);
  9903. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9904. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9905. }
  9906. }
  9907. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9908. std::string out;
  9909. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9910. "Content-Type: text/plain\r\n"
  9911. "Transfer-Encoding: chunked\r\n"
  9912. "\r\n"
  9913. "nothex\r\n",
  9914. &out);
  9915. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9916. }
  9917. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9918. std::string out;
  9919. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9920. "Content-Type: text/plain\r\n"
  9921. "Transfer-Encoding: chunked\r\n"
  9922. "\r\n"
  9923. "3\r\n"
  9924. "xyz\r\n"
  9925. "NaN\r\n",
  9926. &out);
  9927. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9928. }
  9929. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9930. std::string out;
  9931. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9932. "Content-Type: text/plain\r\n"
  9933. "Transfer-Encoding: chunked\r\n"
  9934. "\r\n"
  9935. // Length is too large for 64 bits.
  9936. "1ffffffffffffffff\r\n"
  9937. "xyz\r\n",
  9938. &out);
  9939. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9940. }
  9941. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9942. test_raw_request("GET /hi HTTP/1.1\r\n"
  9943. "Content-Type: text/plain\r\n\r");
  9944. }
  9945. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9946. std::string out;
  9947. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9948. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9949. }
  9950. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9951. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9952. std::string out;
  9953. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9954. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9955. }
  9956. }
  9957. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9958. std::string out;
  9959. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9960. "Host: localhost\r\n"
  9961. "Connection: close\r\n\r\n",
  9962. &out);
  9963. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9964. }
  9965. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9966. Server svr;
  9967. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9968. EXPECT_TRUE(!req.remote_addr.empty());
  9969. });
  9970. thread t = thread([&] { svr.listen(HOST, PORT); });
  9971. auto se = detail::scope_exit([&] {
  9972. svr.stop();
  9973. t.join();
  9974. ASSERT_FALSE(svr.is_running());
  9975. });
  9976. svr.wait_until_ready();
  9977. // Send an invalid request line to trigger Bad Request
  9978. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9979. std::string out;
  9980. ASSERT_TRUE(send_request(5, bad_req, &out));
  9981. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9982. }
  9983. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9984. // answered right away rather than blocking on a read that waits for EOF.
  9985. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9986. std::string out;
  9987. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9988. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9989. }
  9990. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9991. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9992. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9993. for (const auto *method : methods) {
  9994. Server svr;
  9995. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9996. EXPECT_FALSE(svr.is_valid()) << method;
  9997. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9998. }
  9999. }
  10000. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10001. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10002. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10003. for (const auto *method : methods) {
  10004. Server svr;
  10005. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10006. EXPECT_FALSE(svr.is_valid()) << method;
  10007. }
  10008. }
  10009. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10010. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10011. "COPY", "MOVE", "LOCK",
  10012. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10013. Server svr;
  10014. for (const auto *method : methods) {
  10015. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10016. }
  10017. EXPECT_TRUE(svr.is_valid());
  10018. }
  10019. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10020. Server svr;
  10021. svr.CustomRoute("POST", "/x",
  10022. [](const Request &, Response &, const ContentReader &) {});
  10023. EXPECT_FALSE(svr.is_valid());
  10024. }
  10025. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10026. Server svr;
  10027. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10028. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10029. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10030. EXPECT_FALSE(svr.is_valid());
  10031. }
  10032. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10033. Server svr;
  10034. auto captured = Error::Success;
  10035. svr.set_error_logger(
  10036. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10037. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10038. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10039. }
  10040. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10041. std::string out;
  10042. std::string request(
  10043. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10044. test_raw_request(request, &out);
  10045. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10046. }
  10047. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10048. std::string out;
  10049. std::string request(
  10050. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10051. test_raw_request(request, &out);
  10052. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10053. }
  10054. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10055. std::string out;
  10056. std::string request(
  10057. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10058. test_raw_request(request, &out);
  10059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10060. }
  10061. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10062. std::string out;
  10063. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10064. "Host: localhost\r\n"
  10065. "Test: \r\n\r\n",
  10066. &out);
  10067. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10068. }
  10069. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10070. Server svr;
  10071. std::string x_custom;
  10072. std::string cookie;
  10073. std::string xff;
  10074. std::string x_unicode;
  10075. std::string x_iis;
  10076. svr.Get("/check", [&](const Request &req, Response &res) {
  10077. x_custom = req.get_header_value("X-Custom");
  10078. cookie = req.get_header_value("Cookie");
  10079. xff = req.get_header_value("X-Forwarded-For");
  10080. x_unicode = req.get_header_value("X-Unicode");
  10081. x_iis = req.get_header_value("X-IIS");
  10082. res.set_content("ok", "text/plain");
  10083. });
  10084. thread t = thread([&] { svr.listen(HOST, PORT); });
  10085. auto se = detail::scope_exit([&] {
  10086. svr.stop();
  10087. t.join();
  10088. ASSERT_FALSE(svr.is_running());
  10089. });
  10090. svr.wait_until_ready();
  10091. const std::string req = "GET /check HTTP/1.1\r\n"
  10092. "Host: localhost\r\n"
  10093. "X-Custom: a%0D%0AInjected: b\r\n"
  10094. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10095. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10096. "X-Unicode: %E3%81%82\r\n"
  10097. "X-IIS: %u00E9\r\n"
  10098. "Connection: close\r\n"
  10099. "\r\n";
  10100. std::string res;
  10101. ASSERT_TRUE(send_request(5, req, &res));
  10102. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10103. // Every value must be returned verbatim (wire form), with no decoding.
  10104. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10105. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10106. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10107. EXPECT_EQ("%E3%81%82", x_unicode);
  10108. EXPECT_EQ("%u00E9", x_iis);
  10109. }
  10110. // Applications that previously relied on automatic percent-decoding can
  10111. // reproduce the old behavior by explicitly calling decode_path_component()
  10112. // or, for RFC 3986 conformance, decode_uri_component().
  10113. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10114. Server svr;
  10115. std::string decoded;
  10116. svr.Get("/check", [&](const Request &req, Response &res) {
  10117. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10118. res.set_content("ok", "text/plain");
  10119. });
  10120. thread t = thread([&] { svr.listen(HOST, PORT); });
  10121. auto se = detail::scope_exit([&] {
  10122. svr.stop();
  10123. t.join();
  10124. ASSERT_FALSE(svr.is_running());
  10125. });
  10126. svr.wait_until_ready();
  10127. const std::string req = "GET /check HTTP/1.1\r\n"
  10128. "Host: localhost\r\n"
  10129. "X-Custom: hello%20world\r\n"
  10130. "Connection: close\r\n"
  10131. "\r\n";
  10132. std::string res;
  10133. ASSERT_TRUE(send_request(5, req, &res));
  10134. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10135. EXPECT_EQ("hello world", decoded);
  10136. }
  10137. // Regression test for #2033. Browsers send Referer values that include
  10138. // percent-encoded characters such as %0A inside the URL. Decoding the
  10139. // header value would either trip the post-decode CR/LF/NUL guard (the
  10140. // original bug, returning 400) or, after that guard was relaxed, silently
  10141. // store a literal LF — both unacceptable. The wire form must round-trip.
  10142. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10143. Server svr;
  10144. std::string referer;
  10145. svr.Get("/check", [&](const Request &req, Response &res) {
  10146. referer = req.get_header_value("Referer");
  10147. res.set_content("ok", "text/plain");
  10148. });
  10149. thread t = thread([&] { svr.listen(HOST, PORT); });
  10150. auto se = detail::scope_exit([&] {
  10151. svr.stop();
  10152. t.join();
  10153. ASSERT_FALSE(svr.is_running());
  10154. });
  10155. svr.wait_until_ready();
  10156. const std::string req = "GET /check HTTP/1.1\r\n"
  10157. "Host: localhost\r\n"
  10158. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10159. "Connection: close\r\n"
  10160. "\r\n";
  10161. std::string res;
  10162. ASSERT_TRUE(send_request(5, req, &res));
  10163. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10164. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10165. }
  10166. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10167. Server svr;
  10168. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10169. res.set_header("Cache-Control", "no-cache");
  10170. res.set_chunked_content_provider(
  10171. "text/event-stream", [](size_t offset, DataSink &sink) {
  10172. std::string s = "data:";
  10173. s += std::to_string(offset);
  10174. s += "\n\n";
  10175. auto ret = sink.write(s.data(), s.size());
  10176. EXPECT_TRUE(ret);
  10177. std::this_thread::sleep_for(std::chrono::seconds(1));
  10178. return true;
  10179. });
  10180. });
  10181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10182. svr.wait_until_ready();
  10183. Client client(HOST, PORT);
  10184. const Headers headers = {{"Accept", "text/event-stream"}};
  10185. auto get_thread = std::thread([&client, &headers]() {
  10186. auto res = client.Get(
  10187. "/events", headers,
  10188. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10189. });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. get_thread.join();
  10193. listen_thread.join();
  10194. ASSERT_FALSE(svr.is_running());
  10195. });
  10196. // Give GET time to get a few messages.
  10197. std::this_thread::sleep_for(std::chrono::seconds(2));
  10198. }
  10199. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10200. httplib::Server svr;
  10201. svr.Post("/hi",
  10202. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10203. res.status = StatusCode::OK_200;
  10204. });
  10205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10206. svr.wait_until_ready();
  10207. Client cli(HOST, PORT);
  10208. auto res = cli.Post("/hi", "data", "text/plain");
  10209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. svr.stop();
  10212. thread.join();
  10213. ASSERT_FALSE(svr.is_running());
  10214. res = cli.Post("/hi", "data", "text/plain");
  10215. ASSERT_FALSE(res);
  10216. }
  10217. TEST(ServerStopTest, ListenFailure) {
  10218. Server svr;
  10219. auto t = thread([&]() {
  10220. auto ret = svr.listen("????", PORT);
  10221. EXPECT_FALSE(ret);
  10222. });
  10223. svr.wait_until_ready();
  10224. svr.stop();
  10225. t.join();
  10226. }
  10227. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10228. TEST(ServerStopTest, Decommision) {
  10229. Server svr;
  10230. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10231. for (int i = 0; i < 4; i++) {
  10232. auto is_even = !(i % 2);
  10233. std::thread t{[&] {
  10234. try {
  10235. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10236. if (is_even) {
  10237. throw std::runtime_error("Some thing that happens to go wrong.");
  10238. }
  10239. svr.listen(HOST, PORT);
  10240. } catch (...) { svr.decommission(); }
  10241. }};
  10242. svr.wait_until_ready();
  10243. // Server is up
  10244. {
  10245. Client cli(HOST, PORT);
  10246. auto res = cli.Get("/hi");
  10247. if (is_even) {
  10248. EXPECT_FALSE(res);
  10249. } else {
  10250. EXPECT_TRUE(res);
  10251. EXPECT_EQ("hi...", res->body);
  10252. }
  10253. }
  10254. svr.stop();
  10255. t.join();
  10256. // Server is down...
  10257. {
  10258. Client cli(HOST, PORT);
  10259. auto res = cli.Get("/hi");
  10260. EXPECT_FALSE(res);
  10261. }
  10262. }
  10263. }
  10264. #endif
  10265. // Helper function for string body upload progress tests
  10266. template <typename SetupHandler, typename ClientCall>
  10267. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10268. ClientCall &&client_call,
  10269. const string &body) {
  10270. Server svr;
  10271. setup_handler(svr);
  10272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10273. auto se = detail::scope_exit([&] {
  10274. svr.stop();
  10275. t.join();
  10276. });
  10277. svr.wait_until_ready();
  10278. Client cli(HOST, PORT);
  10279. vector<uint64_t> progress_values;
  10280. bool progress_called = false;
  10281. auto res =
  10282. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10283. progress_values.push_back(current);
  10284. progress_called = true;
  10285. return true;
  10286. });
  10287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10288. EXPECT_EQ(200, res->status);
  10289. EXPECT_TRUE(progress_called);
  10290. }
  10291. TEST(UploadProgressTest, PostStringBodyBasic) {
  10292. TestStringBodyUploadProgress(
  10293. [](Server &svr) {
  10294. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10295. res.set_content("received", "text/plain");
  10296. });
  10297. },
  10298. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10299. return cli.Post("/test", body, "text/plain", progress_callback);
  10300. },
  10301. "test data for upload progress");
  10302. }
  10303. TEST(UploadProgressTest, PutStringBodyBasic) {
  10304. TestStringBodyUploadProgress(
  10305. [](Server &svr) {
  10306. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10307. res.set_content("put received", "text/plain");
  10308. });
  10309. },
  10310. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10311. return cli.Put("/test", body, "text/plain", progress_callback);
  10312. },
  10313. "put test data for upload progress");
  10314. }
  10315. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10316. TestStringBodyUploadProgress(
  10317. [](Server &svr) {
  10318. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10319. res.set_content("patch received", "text/plain");
  10320. });
  10321. },
  10322. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10323. return cli.Patch("/test", body, "text/plain", progress_callback);
  10324. },
  10325. "patch test data for upload progress");
  10326. }
  10327. // Helper function for content provider upload progress tests
  10328. template <typename SetupHandler, typename ClientCall>
  10329. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10330. ClientCall &&client_call) {
  10331. Server svr;
  10332. setup_handler(svr);
  10333. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. });
  10338. svr.wait_until_ready();
  10339. Client cli(HOST, PORT);
  10340. vector<uint64_t> progress_values;
  10341. auto res =
  10342. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10343. progress_values.push_back(current);
  10344. return true;
  10345. });
  10346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10347. EXPECT_EQ(200, res->status);
  10348. EXPECT_FALSE(progress_values.empty());
  10349. }
  10350. TEST(UploadProgressTest, PostContentProviderProgress) {
  10351. TestContentProviderUploadProgress(
  10352. [](Server &svr) {
  10353. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10354. res.set_content("provider received", "text/plain");
  10355. });
  10356. },
  10357. [](Client &cli, UploadProgress progress_callback) {
  10358. return cli.Post(
  10359. "/test", 9,
  10360. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10361. sink.os << "test data";
  10362. return true;
  10363. },
  10364. "text/plain", progress_callback);
  10365. });
  10366. }
  10367. // Helper function for multipart upload progress tests
  10368. template <typename SetupHandler, typename ClientCall>
  10369. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10370. ClientCall &&client_call,
  10371. const string &endpoint) {
  10372. Server svr;
  10373. setup_handler(svr);
  10374. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10375. auto se = detail::scope_exit([&] {
  10376. svr.stop();
  10377. t.join();
  10378. });
  10379. svr.wait_until_ready();
  10380. Client cli(HOST, PORT);
  10381. vector<uint64_t> progress_values;
  10382. UploadFormDataItems items = {
  10383. {"field1", "value1", "", ""},
  10384. {"field2", "longer value for progress tracking test", "", ""},
  10385. {"file1", "file content data for upload progress", "test.txt",
  10386. "text/plain"}};
  10387. auto res = client_call(cli, endpoint, items,
  10388. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10389. progress_values.push_back(current);
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(200, res->status);
  10394. EXPECT_FALSE(progress_values.empty());
  10395. }
  10396. TEST(UploadProgressTest, PostMultipartProgress) {
  10397. TestMultipartUploadProgress(
  10398. [](Server &svr) {
  10399. svr.Post("/multipart", [](const Request &req, Response &res) {
  10400. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10401. res.set_content("multipart received", "text/plain");
  10402. });
  10403. },
  10404. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10405. UploadProgress progress_callback) {
  10406. return cli.Post(endpoint, items, progress_callback);
  10407. },
  10408. "/multipart");
  10409. }
  10410. // Helper function for basic download progress tests
  10411. template <typename SetupHandler, typename ClientCall>
  10412. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10413. ClientCall &&client_call, const string &endpoint,
  10414. size_t expected_content_size) {
  10415. Server svr;
  10416. setup_handler(svr);
  10417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10418. auto se = detail::scope_exit([&] {
  10419. svr.stop();
  10420. t.join();
  10421. });
  10422. svr.wait_until_ready();
  10423. Client cli(HOST, PORT);
  10424. vector<uint64_t> progress_values;
  10425. auto res = client_call(cli, endpoint,
  10426. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10427. progress_values.push_back(current);
  10428. return true;
  10429. });
  10430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10431. EXPECT_EQ(200, res->status);
  10432. EXPECT_FALSE(progress_values.empty());
  10433. EXPECT_EQ(expected_content_size, res->body.size());
  10434. }
  10435. TEST(DownloadProgressTest, GetBasic) {
  10436. TestBasicDownloadProgress(
  10437. [](Server &svr) {
  10438. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10439. string content(1000, 'D');
  10440. res.set_content(content, "text/plain");
  10441. });
  10442. },
  10443. [](Client &cli, const string &endpoint,
  10444. DownloadProgress progress_callback) {
  10445. return cli.Get(endpoint, progress_callback);
  10446. },
  10447. "/download", 1000u);
  10448. }
  10449. // Helper function for content receiver download progress tests
  10450. template <typename SetupHandler, typename ClientCall>
  10451. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10452. ClientCall &&client_call,
  10453. const string &endpoint,
  10454. size_t expected_content_size) {
  10455. Server svr;
  10456. setup_handler(svr);
  10457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10458. auto se = detail::scope_exit([&] {
  10459. svr.stop();
  10460. t.join();
  10461. });
  10462. svr.wait_until_ready();
  10463. Client cli(HOST, PORT);
  10464. vector<uint64_t> progress_values;
  10465. string received_body;
  10466. auto res = client_call(
  10467. cli, endpoint,
  10468. [&](const char *data, size_t data_length) -> bool {
  10469. received_body.append(data, data_length);
  10470. return true;
  10471. },
  10472. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10473. progress_values.push_back(current);
  10474. return true;
  10475. });
  10476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10477. EXPECT_EQ(200, res->status);
  10478. EXPECT_FALSE(progress_values.empty());
  10479. EXPECT_EQ(expected_content_size, received_body.size());
  10480. EXPECT_TRUE(res->body.empty());
  10481. }
  10482. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10483. TestContentReceiverDownloadProgress(
  10484. [](Server &svr) {
  10485. svr.Get("/download-receiver",
  10486. [](const Request & /*req*/, Response &res) {
  10487. string content(2000, 'R');
  10488. res.set_content(content, "text/plain");
  10489. });
  10490. },
  10491. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10492. DownloadProgress progress_callback) {
  10493. return cli.Get(endpoint, content_receiver, progress_callback);
  10494. },
  10495. "/download-receiver", 2000u);
  10496. }
  10497. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10498. // A provider reaching a pass with nothing to hand over - an empty buffer
  10499. // popped off a queue, say - must not be taken to mean the body is finished.
  10500. // It used to end the loop with the terminating chunk unwritten while the
  10501. // server still considered the response complete, so the peer waited for an
  10502. // end that never arrived.
  10503. Server svr;
  10504. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10505. auto step = std::make_shared<int>(0);
  10506. res.set_chunked_content_provider("text/plain",
  10507. [step](size_t /*offset*/, DataSink &sink) {
  10508. switch ((*step)++) {
  10509. case 0: sink.write("", 0); break;
  10510. case 1: sink.write("hello", 5); break;
  10511. default: sink.done(); break;
  10512. }
  10513. return true;
  10514. });
  10515. });
  10516. auto port = svr.bind_to_any_port(HOST);
  10517. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10518. auto listen_se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client cli(HOST, port);
  10525. // Without the fix the body is never terminated, so bound the wait rather
  10526. // than letting the test hang on the default read timeout.
  10527. cli.set_read_timeout(5, 0);
  10528. auto res = cli.Get("/stream");
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(StatusCode::OK_200, res->status);
  10531. EXPECT_EQ("hello", res->body);
  10532. }
  10533. TEST(StreamingTest, NoContentLengthStreaming) {
  10534. Server svr;
  10535. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10536. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10537. if (offset < 6) {
  10538. sink.os << (offset < 3 ? "a" : "b");
  10539. } else {
  10540. sink.done();
  10541. }
  10542. return true;
  10543. });
  10544. });
  10545. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10546. auto listen_se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. listen_thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client client(HOST, PORT);
  10553. auto get_thread = std::thread([&client]() {
  10554. std::string s;
  10555. auto res =
  10556. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10557. s += std::string(data, len);
  10558. return true;
  10559. });
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. EXPECT_EQ("aaabbb", s);
  10563. });
  10564. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10565. // Give GET time to get a few messages.
  10566. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10567. }
  10568. TEST(MountTest, Unmount) {
  10569. Server svr;
  10570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10571. auto se = detail::scope_exit([&] {
  10572. svr.stop();
  10573. listen_thread.join();
  10574. ASSERT_FALSE(svr.is_running());
  10575. });
  10576. svr.wait_until_ready();
  10577. Client cli("localhost", PORT);
  10578. svr.set_mount_point("/mount2", "./www2");
  10579. auto res = cli.Get("/");
  10580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10581. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10582. res = cli.Get("/mount2/dir/test.html");
  10583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10584. EXPECT_EQ(StatusCode::OK_200, res->status);
  10585. svr.set_mount_point("/", "./www");
  10586. res = cli.Get("/dir/");
  10587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10588. EXPECT_EQ(StatusCode::OK_200, res->status);
  10589. svr.remove_mount_point("/");
  10590. res = cli.Get("/dir/");
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10593. svr.remove_mount_point("/mount2");
  10594. res = cli.Get("/mount2/dir/test.html");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10597. }
  10598. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10599. Server svr;
  10600. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10601. svr.Get("/api/hello", [](const Request &, Response &res) {
  10602. res.set_content("api", "text/plain");
  10603. });
  10604. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10605. auto se = detail::scope_exit([&] {
  10606. svr.stop();
  10607. listen_thread.join();
  10608. ASSERT_FALSE(svr.is_running());
  10609. });
  10610. svr.wait_until_ready();
  10611. Client cli(HOST, PORT);
  10612. auto res = cli.Get("/dir/test.html");
  10613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10614. EXPECT_EQ(StatusCode::OK_200, res->status);
  10615. res = cli.Get("/api/hello");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::OK_200, res->status);
  10618. EXPECT_EQ("api", res->body);
  10619. }
  10620. TEST(MountTest, PathSegmentBoundary) {
  10621. Server svr;
  10622. svr.set_mount_point("/mount2", "./www2");
  10623. svr.set_mount_point("/", "./www");
  10624. auto port = svr.bind_to_any_port(HOST);
  10625. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.wait_until_ready();
  10632. Client cli(HOST, port);
  10633. auto res = cli.Get("/mount2/dir/test.html");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. // "/mount2" must not match part-way through a path segment.
  10637. res = cli.Get("/mount2dir/test.html");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10640. // A mount point ending in '/' keeps matching every path below it.
  10641. res = cli.Get("/dir/test.html");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MountTest, Redicect) {
  10646. Server svr;
  10647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. listen_thread.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.set_mount_point("/", "./www");
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. auto res = cli.Get("/dir/");
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. res = cli.Get("/dir");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10662. res = cli.Get("/file");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::OK_200, res->status);
  10665. res = cli.Get("/file/");
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10668. cli.set_follow_location(true);
  10669. res = cli.Get("/dir");
  10670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10671. EXPECT_EQ(StatusCode::OK_200, res->status);
  10672. }
  10673. TEST(MountTest, MultibytesPathName) {
  10674. Server svr;
  10675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.set_mount_point("/", "./www");
  10682. svr.wait_until_ready();
  10683. Client cli("localhost", PORT);
  10684. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::OK_200, res->status);
  10687. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10688. }
  10689. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10690. // in the pre-routing handler sees the path of every file that is served
  10691. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10692. Server svr;
  10693. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10694. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10695. if (req.path == "/dir/test.html") {
  10696. res.status = StatusCode::Unauthorized_401;
  10697. return Server::HandlerResponse::Handled;
  10698. }
  10699. return Server::HandlerResponse::Unhandled;
  10700. });
  10701. auto port = svr.bind_to_any_port(HOST);
  10702. ASSERT_LT(0, port);
  10703. thread t = thread([&] { svr.listen_after_bind(); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. t.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli(HOST, port);
  10711. for (auto path :
  10712. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10713. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10714. SCOPED_TRACE(path);
  10715. auto res = cli.Get(path);
  10716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10718. }
  10719. }
  10720. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10721. Server svr;
  10722. svr.set_mount_point("/", "./www");
  10723. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10724. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10725. auto port = svr.bind_to_any_port(HOST);
  10726. ASSERT_GT(port, 0);
  10727. thread t = thread([&] { svr.listen_after_bind(); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, port);
  10735. auto res = cli.Get("/dir/test.abcde");
  10736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10737. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10738. res = cli.Get("/dir/test.html");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10741. }
  10742. #ifdef _WIN32
  10743. // Issue #2435: mmap::open() must succeed even when another handle holds
  10744. // the file open for writing (e.g. an active log file).
  10745. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10746. const char *path = "mmap_concurrent_writer_test.txt";
  10747. const char *content = "hello";
  10748. {
  10749. std::ofstream f(path, std::ios::binary);
  10750. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10751. }
  10752. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10753. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10754. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10755. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10756. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10757. detail::mmap m(path);
  10758. ASSERT_TRUE(m.is_open());
  10759. EXPECT_EQ(strlen(content), m.size());
  10760. char buf[8];
  10761. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10762. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10763. }
  10764. #endif
  10765. #ifndef _WIN32
  10766. // A directory or a device has no size to serve.
  10767. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10768. const char *path = "./mmap_not_regular_test_dir";
  10769. ASSERT_EQ(0, ::mkdir(path, 0755));
  10770. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10771. for (auto p : {path, "/dev/null"}) {
  10772. detail::mmap m(p);
  10773. EXPECT_FALSE(m.is_open()) << p;
  10774. EXPECT_EQ(0U, m.size()) << p;
  10775. }
  10776. Server svr;
  10777. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10778. res.set_file_content("/dev/null");
  10779. });
  10780. auto port = svr.bind_to_any_port(HOST);
  10781. thread t = thread([&] { svr.listen_after_bind(); });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. t.join();
  10785. });
  10786. svr.wait_until_ready();
  10787. auto res = Client(HOST, port).Get("/null");
  10788. ASSERT_TRUE(res);
  10789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10790. }
  10791. #endif
  10792. #ifdef __linux__
  10793. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10794. TEST(MmapTest, FileIsNotMapped) {
  10795. const char *path = "mmap_not_mapped_test.txt";
  10796. {
  10797. std::ofstream f(path, std::ios::binary);
  10798. f << "hello";
  10799. }
  10800. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10801. detail::mmap m(path);
  10802. ASSERT_TRUE(m.is_open());
  10803. std::ifstream maps("/proc/self/maps");
  10804. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10805. std::istreambuf_iterator<char>());
  10806. EXPECT_EQ(std::string::npos, mappings.find(path));
  10807. }
  10808. #endif
  10809. TEST(KeepAliveTest, ReadTimeout) {
  10810. Server svr;
  10811. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10812. std::this_thread::sleep_for(std::chrono::seconds(2));
  10813. res.set_content("a", "text/plain");
  10814. });
  10815. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10816. res.set_content("b", "text/plain");
  10817. });
  10818. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10819. auto se = detail::scope_exit([&] {
  10820. svr.stop();
  10821. listen_thread.join();
  10822. ASSERT_FALSE(svr.is_running());
  10823. });
  10824. svr.wait_until_ready();
  10825. Client cli("localhost", PORT);
  10826. cli.set_keep_alive(true);
  10827. cli.set_read_timeout(std::chrono::seconds(1));
  10828. auto resa = cli.Get("/a");
  10829. ASSERT_FALSE(resa);
  10830. EXPECT_EQ(Error::Read, resa.error());
  10831. auto resb = cli.Get("/b");
  10832. ASSERT_TRUE(resb);
  10833. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10834. EXPECT_EQ("b", resb->body);
  10835. }
  10836. TEST(KeepAliveTest, MaxCount) {
  10837. size_t keep_alive_max_count = 3;
  10838. Server svr;
  10839. svr.set_keep_alive_max_count(keep_alive_max_count);
  10840. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10841. res.set_content("Hello World!", "text/plain");
  10842. });
  10843. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10844. auto se = detail::scope_exit([&] {
  10845. svr.stop();
  10846. listen_thread.join();
  10847. ASSERT_FALSE(svr.is_running());
  10848. });
  10849. svr.wait_until_ready();
  10850. Client cli(HOST, PORT);
  10851. cli.set_keep_alive(true);
  10852. for (size_t i = 0; i < 5; i++) {
  10853. auto result = cli.Get("/hi");
  10854. ASSERT_TRUE(result);
  10855. EXPECT_EQ(StatusCode::OK_200, result->status);
  10856. if (i == keep_alive_max_count - 1) {
  10857. EXPECT_EQ("close", result->get_header_value("Connection"));
  10858. } else {
  10859. EXPECT_FALSE(result->has_header("Connection"));
  10860. }
  10861. }
  10862. }
  10863. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10864. // can pull the next one into the server's buffer. The server must serve it
  10865. // without waiting for the socket to become readable again. The keep-alive
  10866. // timeout outlasts the client's read timeout, so a request left waiting for it
  10867. // shows up as a missing response.
  10868. static void serve_pipelining_routes(Server &svr,
  10869. const std::function<void(int)> &client) {
  10870. svr.set_keep_alive_timeout(5);
  10871. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10872. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10873. });
  10874. svr.Post("/echo", [](const Request &req, Response &res) {
  10875. res.set_content("echo " + req.body, "text/plain");
  10876. });
  10877. auto port = svr.bind_to_any_port(HOST);
  10878. thread t = thread([&] { svr.listen_after_bind(); });
  10879. auto se = detail::scope_exit([&] {
  10880. svr.stop();
  10881. t.join();
  10882. });
  10883. svr.wait_until_ready();
  10884. client(port);
  10885. }
  10886. static std::string
  10887. send_pipelined_requests(const std::vector<std::string> &parts) {
  10888. Server svr;
  10889. std::string res;
  10890. serve_pipelining_routes(svr, [&](int port) {
  10891. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10892. });
  10893. return res;
  10894. }
  10895. static void expect_in_order(const std::string &res,
  10896. const std::vector<std::string> &bodies) {
  10897. size_t pos = 0;
  10898. for (const auto &body : bodies) {
  10899. pos = res.find(body, pos);
  10900. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10901. pos += body.size();
  10902. }
  10903. }
  10904. TEST(KeepAliveTest, PipelinedRequests) {
  10905. auto res = send_pipelined_requests(
  10906. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10907. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10908. "Content-Length: 4\r\n\r\nbody"
  10909. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10910. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10911. }
  10912. // The second request starts in the server's buffer and ends on the socket.
  10913. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10914. auto res =
  10915. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10916. "GET /hi/2 HTTP/1.1\r\nHo",
  10917. "st: localhost\r\nConnection: close\r\n\r\n"});
  10918. expect_in_order(res, {"hi 1", "hi 2"});
  10919. }
  10920. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10921. // CRLF after a body does not turn into a 400 for the next request.
  10922. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10923. auto res = send_pipelined_requests(
  10924. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10925. "Content-Length: 4\r\n\r\nbody\r\n"
  10926. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10927. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10928. expect_in_order(res, {"echo body", "hi 2"});
  10929. }
  10930. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10931. // must not be served as the next request.
  10932. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10933. auto res = send_pipelined_requests(
  10934. {"INVALID REQUEST LINE\r\n\r\n"
  10935. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10936. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10937. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10938. }
  10939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10940. // Over TLS, the next request is held by the TLS library as already decrypted
  10941. // data rather than on the socket.
  10942. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10944. std::string res;
  10945. serve_pipelining_routes(svr, [&](int port) {
  10946. // One part, so all three requests arrive in one TLS record
  10947. EXPECT_TRUE(send_ssl_request_in_parts(
  10948. 2,
  10949. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10950. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10951. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10952. &res, port));
  10953. });
  10954. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10955. }
  10956. #endif
  10957. TEST(KeepAliveTest, Issue1041) {
  10958. Server svr;
  10959. svr.set_keep_alive_timeout(3);
  10960. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10961. res.set_content("Hello World!", "text/plain");
  10962. });
  10963. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. listen_thread.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. });
  10969. svr.wait_until_ready();
  10970. Client cli(HOST, PORT);
  10971. cli.set_keep_alive(true);
  10972. auto result = cli.Get("/hi");
  10973. ASSERT_TRUE(result);
  10974. EXPECT_EQ(StatusCode::OK_200, result->status);
  10975. std::this_thread::sleep_for(std::chrono::seconds(5));
  10976. result = cli.Get("/hi");
  10977. ASSERT_TRUE(result);
  10978. EXPECT_EQ(StatusCode::OK_200, result->status);
  10979. }
  10980. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10981. Server svr;
  10982. svr.set_keep_alive_max_count(0);
  10983. std::set<int> remote_ports;
  10984. svr.Get("/hi", [&](const Request &req, Response &res) {
  10985. remote_ports.insert(req.remote_port);
  10986. res.set_content("hi", "text/plain");
  10987. });
  10988. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. Client cli(HOST, PORT);
  10996. cli.set_keep_alive(true);
  10997. for (int i = 0; i < 3; i++) {
  10998. auto res = cli.Get("/hi");
  10999. ASSERT_TRUE(res);
  11000. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11001. }
  11002. // All three over one connection
  11003. EXPECT_EQ(1u, remote_ports.size());
  11004. }
  11005. TEST(KeepAliveTest, Issue1959) {
  11006. Server svr;
  11007. svr.set_keep_alive_timeout(5);
  11008. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11009. res.set_content("a", "text/plain");
  11010. });
  11011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11012. auto se = detail::scope_exit([&] {
  11013. if (!svr.is_running()) return;
  11014. svr.stop();
  11015. listen_thread.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. });
  11018. svr.wait_until_ready();
  11019. Client cli("localhost", PORT);
  11020. cli.set_keep_alive(true);
  11021. using namespace std::chrono;
  11022. auto start = steady_clock::now();
  11023. cli.Get("/a");
  11024. svr.stop();
  11025. listen_thread.join();
  11026. auto end = steady_clock::now();
  11027. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11028. EXPECT_LT(elapsed, 5000);
  11029. }
  11030. #ifdef CPPHTTPLIB_SSL_ENABLED
  11031. TEST(KeepAliveTest, SSLClientReconnection) {
  11032. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11033. ASSERT_TRUE(svr.is_valid());
  11034. svr.set_keep_alive_timeout(1);
  11035. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11036. res.set_content("Hello World!", "text/plain");
  11037. });
  11038. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11039. auto se = detail::scope_exit([&] {
  11040. svr.stop();
  11041. listen_thread.join();
  11042. ASSERT_FALSE(svr.is_running());
  11043. });
  11044. svr.wait_until_ready();
  11045. SSLClient cli(HOST, PORT);
  11046. cli.enable_server_certificate_verification(false);
  11047. cli.set_keep_alive(true);
  11048. auto result = cli.Get("/hi");
  11049. ASSERT_TRUE(result);
  11050. EXPECT_EQ(StatusCode::OK_200, result->status);
  11051. result = cli.Get("/hi");
  11052. ASSERT_TRUE(result);
  11053. EXPECT_EQ(StatusCode::OK_200, result->status);
  11054. std::this_thread::sleep_for(std::chrono::seconds(2));
  11055. // Recoonect
  11056. result = cli.Get("/hi");
  11057. ASSERT_TRUE(result);
  11058. EXPECT_EQ(StatusCode::OK_200, result->status);
  11059. result = cli.Get("/hi");
  11060. ASSERT_TRUE(result);
  11061. EXPECT_EQ(StatusCode::OK_200, result->status);
  11062. }
  11063. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.set_keep_alive_timeout(1);
  11067. std::string content = "reconnect";
  11068. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11069. res.set_content("Hello World!", "text/plain");
  11070. });
  11071. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. SSLClient cli(HOST, PORT);
  11079. cli.enable_server_certificate_verification(false);
  11080. cli.set_keep_alive(true);
  11081. auto result = cli.Post(
  11082. "/hi", content.size(),
  11083. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11084. sink.write(content.c_str(), content.size());
  11085. return true;
  11086. },
  11087. "text/plain");
  11088. ASSERT_TRUE(result);
  11089. EXPECT_EQ(200, result->status);
  11090. std::this_thread::sleep_for(std::chrono::seconds(2));
  11091. // Recoonect
  11092. result = cli.Post(
  11093. "/hi", content.size(),
  11094. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11095. sink.write(content.c_str(), content.size());
  11096. return true;
  11097. },
  11098. "text/plain");
  11099. ASSERT_TRUE(result);
  11100. EXPECT_EQ(200, result->status);
  11101. result = cli.Post(
  11102. "/hi", content.size(),
  11103. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11104. sink.write(content.c_str(), content.size());
  11105. return true;
  11106. },
  11107. "text/plain");
  11108. ASSERT_TRUE(result);
  11109. EXPECT_EQ(200, result->status);
  11110. }
  11111. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11112. using namespace httplib::tls;
  11113. {
  11114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11115. ASSERT_TRUE(svr.is_valid());
  11116. svr.Get("/sni", [&](const Request &req, Response &res) {
  11117. std::string expected = req.sni();
  11118. EXPECT_EQ(expected, req.get_param_value("expected"));
  11119. res.set_content("ok", "text/plain");
  11120. });
  11121. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11122. auto se = detail::scope_exit([&] {
  11123. svr.stop();
  11124. listen_thread.join();
  11125. ASSERT_FALSE(svr.is_running());
  11126. });
  11127. svr.wait_until_ready();
  11128. {
  11129. SSLClient cli("localhost", PORT);
  11130. cli.enable_server_certificate_verification(false);
  11131. auto res = cli.Get("/sni?expected=localhost");
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. }
  11134. {
  11135. SSLClient cli("::1", PORT);
  11136. cli.enable_server_certificate_verification(false);
  11137. auto res = cli.Get("/sni?expected=");
  11138. // NOTE: This may fail if the server is listening on IPv4 only
  11139. // (e.g., when localhost resolves to 127.0.0.1 only)
  11140. if (res) {
  11141. EXPECT_EQ(StatusCode::OK_200, res->status);
  11142. } else {
  11143. EXPECT_EQ(Error::Connection, res.error());
  11144. }
  11145. }
  11146. }
  11147. }
  11148. // The SNI of a failed handshake does not reach the next connection that the
  11149. // same worker thread serves
  11150. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11152. ASSERT_TRUE(svr.is_valid());
  11153. svr.new_task_queue = [] { return new ThreadPool(1); };
  11154. svr.Get("/sni", [](const Request &req, Response &res) {
  11155. res.set_content(req.sni(), "text/plain");
  11156. });
  11157. auto port = svr.bind_to_any_port("127.0.0.1");
  11158. ASSERT_LT(0, port);
  11159. thread t = thread([&] { svr.listen_after_bind(); });
  11160. auto se = detail::scope_exit([&] {
  11161. svr.stop();
  11162. t.join();
  11163. ASSERT_FALSE(svr.is_running());
  11164. });
  11165. svr.wait_until_ready();
  11166. {
  11167. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11168. SSLClient cli("localhost", port);
  11169. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11170. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11171. auto res = cli.Get("/sni");
  11172. ASSERT_FALSE(res);
  11173. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11174. }
  11175. // An IP host sends no SNI (RFC 6066)
  11176. SSLClient cli("127.0.0.1", port);
  11177. cli.enable_server_certificate_verification(false);
  11178. auto res = cli.Get("/sni");
  11179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11180. EXPECT_EQ("", res->body);
  11181. }
  11182. #endif
  11183. TEST(ClientProblemDetectionTest, ContentProvider) {
  11184. Server svr;
  11185. size_t content_length = 1024 * 1024;
  11186. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11187. res.set_content_provider(
  11188. content_length, "text/plain",
  11189. [&](size_t offset, size_t length, DataSink &sink) {
  11190. auto out_len = std::min(length, static_cast<size_t>(1024));
  11191. std::string out(out_len, '@');
  11192. sink.write(out.data(), out_len);
  11193. return offset < 4096;
  11194. },
  11195. [](bool success) { ASSERT_FALSE(success); });
  11196. });
  11197. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11198. res.set_content_provider(
  11199. 0, "text/plain",
  11200. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11201. EXPECT_TRUE(false);
  11202. return true;
  11203. },
  11204. [](bool success) { ASSERT_FALSE(success); });
  11205. });
  11206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11207. auto se = detail::scope_exit([&] {
  11208. svr.stop();
  11209. listen_thread.join();
  11210. ASSERT_FALSE(svr.is_running());
  11211. });
  11212. svr.wait_until_ready();
  11213. Client cli("localhost", PORT);
  11214. {
  11215. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11216. size_t /*data_length*/) { return false; });
  11217. ASSERT_FALSE(res);
  11218. }
  11219. {
  11220. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11221. size_t /*data_length*/) { return false; });
  11222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11223. }
  11224. }
  11225. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11226. // A provider that reports success without writing anything and without
  11227. // calling done() used to be handed the same offset and length again on every
  11228. // pass, so it spun for as long as the peer stayed connected.
  11229. Server svr;
  11230. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11231. res.set_content("ok", "text/plain");
  11232. });
  11233. auto port = svr.bind_to_any_port(HOST);
  11234. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11235. auto se = detail::scope_exit([&] {
  11236. svr.stop();
  11237. listen_thread.join();
  11238. ASSERT_FALSE(svr.is_running());
  11239. });
  11240. svr.wait_until_ready();
  11241. std::atomic<int> call_count{0};
  11242. Client cli(HOST, port);
  11243. auto res = cli.Post(
  11244. "/", 1024,
  11245. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11246. // Give up after enough passes to show the spin, so that losing the
  11247. // check below fails this test instead of hanging it.
  11248. return ++call_count < 100;
  11249. },
  11250. "text/plain");
  11251. ASSERT_FALSE(res);
  11252. EXPECT_EQ(Error::Write, res.error());
  11253. EXPECT_EQ(1, call_count.load());
  11254. }
  11255. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11256. // A writer only has to assign `write`. The other three used to be left as
  11257. // empty std::functions, so a provider calling one threw
  11258. // std::bad_function_call out of the thread running it and took the whole
  11259. // process down.
  11260. DataSink sink;
  11261. std::string written;
  11262. sink.write = [&](const char *data, size_t data_len) {
  11263. written.append(data, data_len);
  11264. return true;
  11265. };
  11266. EXPECT_TRUE(sink.is_writable());
  11267. sink.done();
  11268. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11269. EXPECT_TRUE(written.empty());
  11270. }
  11271. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11272. // A sink that cannot carry trailers still has to finish.
  11273. DataSink sink;
  11274. auto done_count = 0;
  11275. sink.done = [&]() { done_count++; };
  11276. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11277. EXPECT_EQ(1, done_count);
  11278. }
  11279. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11280. Server svr;
  11281. const std::string body(4096, 'x');
  11282. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11283. res.set_content_provider(body.size(), "text/plain",
  11284. [&](size_t offset, size_t length, DataSink &sink) {
  11285. sink.write(body.data() + offset, length);
  11286. sink.done();
  11287. return true;
  11288. });
  11289. });
  11290. auto port = svr.bind_to_any_port(HOST);
  11291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11292. auto se = detail::scope_exit([&] {
  11293. svr.stop();
  11294. listen_thread.join();
  11295. ASSERT_FALSE(svr.is_running());
  11296. });
  11297. svr.wait_until_ready();
  11298. Client cli(HOST, port);
  11299. auto res = cli.Get("/");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ(body, res->body);
  11303. }
  11304. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11305. Server svr;
  11306. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11307. res.set_content_provider(
  11308. 1024, "text/plain",
  11309. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11310. sink.write("hello", 5);
  11311. sink.done(); // short of the 1024 bytes the response promised
  11312. return true;
  11313. });
  11314. });
  11315. auto port = svr.bind_to_any_port(HOST);
  11316. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11317. auto se = detail::scope_exit([&] {
  11318. svr.stop();
  11319. listen_thread.join();
  11320. ASSERT_FALSE(svr.is_running());
  11321. });
  11322. svr.wait_until_ready();
  11323. Client cli(HOST, port);
  11324. cli.set_read_timeout(5, 0);
  11325. // The response is short of its Content-Length, so the client cannot read a
  11326. // complete body. What matters is that this returns at all: a no-op done()
  11327. // would leave the writer looping over a provider that never makes progress.
  11328. auto res = cli.Get("/");
  11329. EXPECT_FALSE(res);
  11330. }
  11331. // Read as the next response by a peer that sees it after a framed body.
  11332. static const std::string smuggled_response =
  11333. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11334. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11335. Server svr;
  11336. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11337. res.set_content_provider(
  11338. 5, "text/plain",
  11339. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11340. auto data = "AAAAA" + smuggled_response;
  11341. sink.write(data.data(), data.size());
  11342. return true;
  11343. });
  11344. });
  11345. thread t = thread([&] { svr.listen(HOST, PORT); });
  11346. auto se = detail::scope_exit([&] {
  11347. svr.stop();
  11348. t.join();
  11349. ASSERT_FALSE(svr.is_running());
  11350. });
  11351. svr.wait_until_ready();
  11352. std::string resp;
  11353. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11354. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11355. resp.clear();
  11356. ASSERT_TRUE(send_request(
  11357. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11358. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11359. }
  11360. TEST(NoContentTest, BodyIsNotSent) {
  11361. Server svr;
  11362. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11363. res.status = StatusCode::NoContent_204;
  11364. res.set_content(smuggled_response, "text/plain");
  11365. });
  11366. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11367. res.status = StatusCode::NotModified_304;
  11368. res.set_chunked_content_provider(
  11369. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11370. sink.write(smuggled_response.data(), smuggled_response.size());
  11371. sink.done();
  11372. return true;
  11373. });
  11374. });
  11375. thread t = thread([&] { svr.listen(HOST, PORT); });
  11376. auto se = detail::scope_exit([&] {
  11377. svr.stop();
  11378. t.join();
  11379. ASSERT_FALSE(svr.is_running());
  11380. });
  11381. svr.wait_until_ready();
  11382. for (auto path : {"/204", "/304"}) {
  11383. std::string resp;
  11384. ASSERT_TRUE(send_request(
  11385. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11386. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11387. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11388. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11389. }
  11390. }
  11391. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11392. Server svr;
  11393. std::atomic<bool> smuggled(false);
  11394. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11395. res.set_content("ok", "text/plain");
  11396. });
  11397. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11398. smuggled = true;
  11399. });
  11400. auto port = svr.bind_to_any_port(HOST);
  11401. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. // What follows the body would be read as the next request.
  11409. Client cli(HOST, port);
  11410. auto res = cli.Post(
  11411. "/", 5,
  11412. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11413. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11414. sink.write(data.data(), data.size());
  11415. return true;
  11416. },
  11417. "text/plain");
  11418. ASSERT_FALSE(res);
  11419. EXPECT_EQ(Error::Write, res.error());
  11420. EXPECT_FALSE(smuggled);
  11421. }
  11422. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11423. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11424. // The compressed path builds the whole body before connecting, so this
  11425. // fails client-side and never reaches a server.
  11426. Client cli(HOST, PORT);
  11427. cli.set_compress(true);
  11428. auto res = cli.Post(
  11429. "/", 1024,
  11430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11431. sink.write("hello", 5);
  11432. sink.done(); // short of the 1024 bytes the request announced
  11433. return true;
  11434. },
  11435. "text/plain");
  11436. ASSERT_FALSE(res);
  11437. EXPECT_EQ(Error::Write, res.error());
  11438. }
  11439. #endif
  11440. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11441. Server svr;
  11442. svr.set_error_handler([](Request const &, Response &res) -> void {
  11443. res.set_chunked_content_provider(
  11444. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11445. sink.os << "hello";
  11446. sink.os << "world";
  11447. sink.done();
  11448. return true;
  11449. });
  11450. });
  11451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11452. auto se = detail::scope_exit([&] {
  11453. svr.stop();
  11454. listen_thread.join();
  11455. ASSERT_FALSE(svr.is_running());
  11456. });
  11457. svr.wait_until_ready();
  11458. Client cli("localhost", PORT);
  11459. auto res = cli.Get("/");
  11460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11462. EXPECT_EQ("helloworld", res->body);
  11463. }
  11464. // A body set after a content provider must replace it, not be sent through it.
  11465. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11466. Server svr;
  11467. svr.set_mount_point("/", "./www");
  11468. svr.set_file_request_handler([](const Request &req, Response &res) {
  11469. if (req.path == "/dir/test.html") {
  11470. res.status = StatusCode::Forbidden_403;
  11471. res.set_content(std::string(5000, 'D'), "text/plain");
  11472. } else if (req.path == "/file") {
  11473. res.status = StatusCode::Forbidden_403;
  11474. res.body = "Denied";
  11475. }
  11476. });
  11477. auto port = svr.bind_to_any_port(HOST);
  11478. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11479. auto se = detail::scope_exit([&] {
  11480. svr.stop();
  11481. t.join();
  11482. ASSERT_FALSE(svr.is_running());
  11483. });
  11484. svr.wait_until_ready();
  11485. Client cli(HOST, port);
  11486. {
  11487. auto res = cli.Get("/dir/test.html");
  11488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11490. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11491. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11492. }
  11493. {
  11494. auto res = cli.Get("/file");
  11495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11496. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11497. EXPECT_EQ("Denied", res->body);
  11498. }
  11499. {
  11500. auto res = cli.Get("/dir/index.html");
  11501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11502. EXPECT_EQ(StatusCode::OK_200, res->status);
  11503. EXPECT_EQ(0U, res->body.find("<html>"));
  11504. }
  11505. }
  11506. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11507. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11508. Server svr;
  11509. std::vector<bool> released;
  11510. std::mutex released_mutex;
  11511. auto releaser = [&](bool success) {
  11512. std::lock_guard<std::mutex> guard(released_mutex);
  11513. released.push_back(success);
  11514. };
  11515. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11516. return sink.write(&"hello"[offset], length);
  11517. };
  11518. svr.Get("/sized", [&](const Request &, Response &res) {
  11519. res.status = StatusCode::NotFound_404;
  11520. res.set_content_provider(5, "text/plain", provider, releaser);
  11521. });
  11522. svr.Get("/chunked", [&](const Request &, Response &res) {
  11523. res.status = StatusCode::ServiceUnavailable_503;
  11524. res.set_chunked_content_provider(
  11525. "text/plain",
  11526. [](size_t, DataSink &sink) {
  11527. sink.os << "chunk";
  11528. sink.done();
  11529. return true;
  11530. },
  11531. releaser);
  11532. });
  11533. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11534. res.set_content_provider(5, "text/plain", provider, releaser);
  11535. throw std::runtime_error("after the provider");
  11536. });
  11537. svr.set_error_handler([](const Request &req, Response &res) {
  11538. // Leave the exception handler's content to it.
  11539. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11540. res.set_content(std::string(1000, 'E'), "text/html");
  11541. return Server::HandlerResponse::Handled;
  11542. });
  11543. svr.set_exception_handler(
  11544. [](const Request &, Response &res, std::exception_ptr) {
  11545. res.status = StatusCode::InternalServerError_500;
  11546. res.set_content(std::string(1000, 'X'), "text/html");
  11547. });
  11548. auto port = svr.bind_to_any_port(HOST);
  11549. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11550. auto se = detail::scope_exit([&] {
  11551. svr.stop();
  11552. t.join();
  11553. ASSERT_FALSE(svr.is_running());
  11554. });
  11555. svr.wait_until_ready();
  11556. Client cli(HOST, port);
  11557. {
  11558. auto res = cli.Get("/sized");
  11559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11561. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11562. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11563. }
  11564. {
  11565. auto res = cli.Get("/chunked");
  11566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11567. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11568. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11569. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11570. }
  11571. {
  11572. auto res = cli.Get("/throw");
  11573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11574. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11575. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11576. }
  11577. std::lock_guard<std::mutex> guard(released_mutex);
  11578. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11579. }
  11580. #endif
  11581. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11582. Server svr;
  11583. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11584. return sink.write(&"abc"[offset], length);
  11585. };
  11586. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11587. res.set_file_content("./www/dir/test.html");
  11588. res.set_content("body", "text/plain");
  11589. });
  11590. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11591. res.set_content(std::string(100, 'B'), "text/plain");
  11592. res.set_file_content("./www/dir/test.html");
  11593. });
  11594. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11595. res.set_content(std::string(100, 'B'), "text/plain");
  11596. res.set_content_provider(3, "text/x-provider", abc);
  11597. });
  11598. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11599. res.set_content_provider(3, "text/x-provider", abc);
  11600. res.set_content(std::string(100, 'B'), "text/plain");
  11601. });
  11602. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11603. res.set_content_provider(3, "text/x-provider", abc);
  11604. res.set_file_content("./www/dir/test.html", "text/x-file");
  11605. });
  11606. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11607. res.set_file_content("./www/dir/test.html");
  11608. res.set_header("Content-Type", "text/x-handler");
  11609. });
  11610. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11611. res.set_content_provider(3, "text/plain", abc);
  11612. res.body = "direct";
  11613. });
  11614. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11615. res.set_file_content("./www/dir/test.html");
  11616. res.body = "direct";
  11617. });
  11618. auto port = svr.bind_to_any_port(HOST);
  11619. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. t.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. Client cli(HOST, port);
  11627. auto expect_body = [&](const char *path, const std::string &body,
  11628. const std::string &type) {
  11629. // Uncompressed, so Content-Length can be compared with the body.
  11630. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11631. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11632. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11633. EXPECT_EQ(body, res->body) << path;
  11634. EXPECT_EQ(std::to_string(body.size()),
  11635. res->get_header_value("Content-Length"))
  11636. << path;
  11637. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11638. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11639. };
  11640. expect_body("/file-then-body", "body", "text/plain");
  11641. expect_body("/body-then-file", "test.html", "text/html");
  11642. expect_body("/body-then-provider", "abc", "text/x-provider");
  11643. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11644. expect_body("/provider-then-file", "test.html", "text/x-file");
  11645. expect_body("/file-then-header", "test.html", "text/x-handler");
  11646. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11647. expect_body("/file-then-direct-body", "direct", "text/plain");
  11648. // Ranges are checked against the body, not the dropped provider.
  11649. {
  11650. auto res = cli.Get("/provider-then-direct-body",
  11651. Headers{{make_range_header({{1, 2}})}});
  11652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11653. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11654. EXPECT_EQ("ir", res->body);
  11655. }
  11656. {
  11657. auto res = cli.Get("/file-then-direct-body",
  11658. Headers{{make_range_header({{7, 8}})}});
  11659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11660. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11661. }
  11662. }
  11663. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11664. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11665. const char *path = "./truncated_while_served.txt";
  11666. const size_t size = 32 * 1024 * 1024;
  11667. {
  11668. std::ofstream f(path, std::ios::binary);
  11669. f << std::string(size, 'x');
  11670. }
  11671. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11672. // Over TLS, where the bytes are encrypted in this process rather than
  11673. // copied by send().
  11674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11675. svr.Get("/file", [&](const Request &, Response &res) {
  11676. res.set_file_content(path, "text/plain");
  11677. });
  11678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. thread.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. // The file shrinks once the first bytes are in, as a rewrite in place
  11686. // would, and reading the mapping past its new end used to raise SIGBUS.
  11687. SSLClient cli(HOST, PORT);
  11688. cli.enable_server_certificate_verification(false);
  11689. size_t received = 0;
  11690. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11691. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11692. received += len;
  11693. return true;
  11694. });
  11695. EXPECT_FALSE(res);
  11696. EXPECT_LT(received, size);
  11697. }
  11698. #endif
  11699. // Forward declaration (see the base64_encode note).
  11700. namespace httplib {
  11701. namespace detail {
  11702. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11703. const std::string &content_type,
  11704. EncodingType encoding);
  11705. } // namespace detail
  11706. } // namespace httplib
  11707. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11708. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11709. ASSERT_TRUE(mm->is_open());
  11710. Response res;
  11711. detail::set_file_content_provider(res, mm, "text/html",
  11712. detail::EncodingType::None);
  11713. std::string out;
  11714. DataSink sink;
  11715. sink.write = [&](const char *d, size_t l) {
  11716. out.append(d, l);
  11717. return true;
  11718. };
  11719. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11720. EXPECT_EQ("test.html", out);
  11721. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11722. EXPECT_EQ("test.html", out);
  11723. }
  11724. TEST(LongPollingTest, ClientCloseDetection) {
  11725. Server svr;
  11726. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11727. res.set_chunked_content_provider(
  11728. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11729. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11730. sink.os << "hello";
  11731. auto count = 10;
  11732. while (count > 0 && sink.is_writable()) {
  11733. this_thread::sleep_for(chrono::milliseconds(10));
  11734. count--;
  11735. }
  11736. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11737. return true;
  11738. });
  11739. });
  11740. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11741. auto se = detail::scope_exit([&] {
  11742. svr.stop();
  11743. listen_thread.join();
  11744. ASSERT_FALSE(svr.is_running());
  11745. });
  11746. svr.wait_until_ready();
  11747. Client cli("localhost", PORT);
  11748. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11749. EXPECT_EQ("hello", string(data, data_length));
  11750. return false; // close the socket immediately.
  11751. });
  11752. ASSERT_FALSE(res);
  11753. }
  11754. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11755. Server svr;
  11756. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11757. res.set_chunked_content_provider(
  11758. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11759. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11760. sink.os << "hello";
  11761. EXPECT_TRUE(sink.os.good());
  11762. // Wait for the client to close the connection
  11763. auto count = 10;
  11764. while (count > 0 && sink.is_writable()) {
  11765. this_thread::sleep_for(chrono::milliseconds(10));
  11766. count--;
  11767. }
  11768. // After client disconnect, write repeatedly until the socket
  11769. // write actually fails (small writes may be absorbed by the
  11770. // kernel buffer)
  11771. std::string chunk(1024, 'x');
  11772. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11773. sink.os << chunk;
  11774. }
  11775. EXPECT_TRUE(sink.os.fail());
  11776. return true;
  11777. });
  11778. });
  11779. auto port = svr.bind_to_any_port("localhost");
  11780. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. listen_thread.join();
  11784. ASSERT_FALSE(svr.is_running());
  11785. });
  11786. svr.wait_until_ready();
  11787. Client cli("localhost", port);
  11788. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11789. EXPECT_EQ("hello", string(data, data_length));
  11790. return false; // close the socket immediately.
  11791. });
  11792. ASSERT_FALSE(res);
  11793. }
  11794. TEST(GetWithParametersTest, GetWithParameters) {
  11795. Server svr;
  11796. svr.Get("/", [&](const Request &req, Response &) {
  11797. EXPECT_EQ("world", req.get_param_value("hello"));
  11798. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11799. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11800. });
  11801. svr.Get("/params", [&](const Request &req, Response &) {
  11802. EXPECT_EQ("world", req.get_param_value("hello"));
  11803. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11804. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11805. });
  11806. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11807. EXPECT_EQ("resource-id", req.matches[1]);
  11808. EXPECT_EQ("foo", req.get_param_value("param1"));
  11809. EXPECT_EQ("bar", req.get_param_value("param2"));
  11810. });
  11811. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11812. EXPECT_EQ("user-id", req.path_params.at("id"));
  11813. EXPECT_EQ("foo", req.get_param_value("param1"));
  11814. EXPECT_EQ("bar", req.get_param_value("param2"));
  11815. });
  11816. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11817. auto se = detail::scope_exit([&] {
  11818. svr.stop();
  11819. listen_thread.join();
  11820. ASSERT_FALSE(svr.is_running());
  11821. });
  11822. svr.wait_until_ready();
  11823. {
  11824. Client cli(HOST, PORT);
  11825. Params params;
  11826. params.emplace("hello", "world");
  11827. params.emplace("hello2", "world2");
  11828. params.emplace("hello3", "world3");
  11829. auto res = cli.Get("/", params, Headers{});
  11830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11831. EXPECT_EQ(StatusCode::OK_200, res->status);
  11832. }
  11833. {
  11834. Client cli(HOST, PORT);
  11835. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. EXPECT_EQ(StatusCode::OK_200, res->status);
  11838. }
  11839. {
  11840. Client cli(HOST, PORT);
  11841. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ(StatusCode::OK_200, res->status);
  11844. }
  11845. {
  11846. Client cli(HOST, PORT);
  11847. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. }
  11851. }
  11852. TEST(GetWithParametersTest, GetWithParameters2) {
  11853. Server svr;
  11854. svr.Get("/", [&](const Request &req, Response &res) {
  11855. auto text = req.get_param_value("hello");
  11856. res.set_content(text, "text/plain");
  11857. });
  11858. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11859. auto se = detail::scope_exit([&] {
  11860. svr.stop();
  11861. listen_thread.join();
  11862. ASSERT_FALSE(svr.is_running());
  11863. });
  11864. svr.wait_until_ready();
  11865. Client cli("localhost", PORT);
  11866. Params params;
  11867. params.emplace("hello", "world");
  11868. std::string body;
  11869. auto res = cli.Get("/", params, Headers{},
  11870. [&](const char *data, size_t data_length) {
  11871. body.append(data, data_length);
  11872. return true;
  11873. });
  11874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11875. EXPECT_EQ(StatusCode::OK_200, res->status);
  11876. EXPECT_EQ("world", body);
  11877. }
  11878. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11879. Server svr;
  11880. svr.Get("/search", [&](const Request &req, Response &res) {
  11881. auto q = req.get_param_value("q");
  11882. res.set_content(q, "text/plain");
  11883. });
  11884. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11885. auto se = detail::scope_exit([&] {
  11886. svr.stop();
  11887. listen_thread.join();
  11888. ASSERT_FALSE(svr.is_running());
  11889. });
  11890. svr.wait_until_ready();
  11891. Client cli("localhost", PORT);
  11892. // Verify that Get(path, params) works without requiring Headers argument
  11893. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11895. EXPECT_EQ(StatusCode::OK_200, res->status);
  11896. EXPECT_EQ("cpp-httplib", res->body);
  11897. }
  11898. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11899. auto host = "httpbingo.org";
  11900. auto path = std::string{"/range/32"};
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli(host);
  11903. #else
  11904. Client cli(host);
  11905. #endif
  11906. cli.set_default_headers({make_range_header({{1, 10}})});
  11907. cli.set_connection_timeout(5);
  11908. {
  11909. auto res = cli.Get(path);
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ("bcdefghijk", res->body);
  11912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11913. }
  11914. {
  11915. auto res = cli.Get(path);
  11916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11917. EXPECT_EQ("bcdefghijk", res->body);
  11918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11919. }
  11920. }
  11921. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11922. Server svr;
  11923. svr.set_default_headers({{"Hello", "World"}});
  11924. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11925. res.set_content("ok", "text/plain");
  11926. });
  11927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. listen_thread.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. Client cli("localhost", PORT);
  11935. auto res = cli.Get("/");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. EXPECT_EQ(StatusCode::OK_200, res->status);
  11938. EXPECT_EQ("ok", res->body);
  11939. EXPECT_EQ("World", res->get_header_value("Hello"));
  11940. }
  11941. #ifdef CPPHTTPLIB_SSL_ENABLED
  11942. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11944. ASSERT_TRUE(svr.is_valid());
  11945. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11946. std::this_thread::sleep_for(std::chrono::seconds(2));
  11947. res.set_content("a", "text/plain");
  11948. });
  11949. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11950. res.set_content("b", "text/plain");
  11951. });
  11952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. listen_thread.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. SSLClient cli("localhost", PORT);
  11960. cli.enable_server_certificate_verification(false);
  11961. cli.set_keep_alive(true);
  11962. cli.set_read_timeout(std::chrono::seconds(1));
  11963. auto resa = cli.Get("/a");
  11964. ASSERT_TRUE(!resa);
  11965. EXPECT_EQ(Error::Read, resa.error());
  11966. auto resb = cli.Get("/b");
  11967. ASSERT_TRUE(resb);
  11968. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11969. EXPECT_EQ("b", resb->body);
  11970. }
  11971. // Closing an idle keep-alive connection sends close_notify and returns. The
  11972. // server must not wait for the client's close_notify: an idle client never
  11973. // sends one, so the worker would be held until the read timeout expires, and
  11974. // stop() would wait for it.
  11975. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11977. ASSERT_TRUE(svr.is_valid());
  11978. svr.set_keep_alive_timeout(1);
  11979. svr.set_read_timeout(10, 0);
  11980. svr.Get("/", [](const Request &, Response &res) {
  11981. res.set_content("ok", "text/plain");
  11982. });
  11983. auto port = svr.bind_to_any_port(HOST);
  11984. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11985. auto se = detail::scope_exit([&] {
  11986. if (listen_thread.joinable()) {
  11987. svr.stop();
  11988. listen_thread.join();
  11989. }
  11990. });
  11991. svr.wait_until_ready();
  11992. SSLClient cli(HOST, port);
  11993. cli.enable_server_certificate_verification(false);
  11994. cli.set_keep_alive(true);
  11995. auto res = cli.Get("/");
  11996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11997. EXPECT_EQ(StatusCode::OK_200, res->status);
  11998. // Stay idle past the keep-alive timeout so the server closes the connection.
  11999. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12000. auto start = std::chrono::steady_clock::now();
  12001. svr.stop();
  12002. listen_thread.join();
  12003. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12004. std::chrono::steady_clock::now() - start)
  12005. .count();
  12006. EXPECT_LT(elapsed, 3000);
  12007. }
  12008. #endif
  12009. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12010. protected:
  12011. ServerTestWithAI_PASSIVE()
  12012. : cli_(HOST, PORT)
  12013. #ifdef CPPHTTPLIB_SSL_ENABLED
  12014. ,
  12015. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12016. #endif
  12017. {
  12018. #ifdef CPPHTTPLIB_SSL_ENABLED
  12019. cli_.enable_server_certificate_verification(false);
  12020. #endif
  12021. }
  12022. virtual void SetUp() {
  12023. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12024. res.set_content("Hello World!", "text/plain");
  12025. });
  12026. t_ = thread(
  12027. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12028. svr_.wait_until_ready();
  12029. }
  12030. virtual void TearDown() {
  12031. svr_.stop();
  12032. t_.join();
  12033. }
  12034. #ifdef CPPHTTPLIB_SSL_ENABLED
  12035. SSLClient cli_;
  12036. SSLServer svr_;
  12037. #else
  12038. Client cli_;
  12039. Server svr_;
  12040. #endif
  12041. thread t_;
  12042. };
  12043. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12044. auto res = cli_.Get("/hi");
  12045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12046. EXPECT_EQ(StatusCode::OK_200, res->status);
  12047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12048. EXPECT_EQ("Hello World!", res->body);
  12049. }
  12050. class ServerUpDownTest : public ::testing::Test {
  12051. protected:
  12052. ServerUpDownTest() : cli_(HOST, PORT) {}
  12053. virtual void SetUp() {
  12054. t_ = thread([&]() {
  12055. svr_.bind_to_any_port(HOST);
  12056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12057. ASSERT_TRUE(svr_.listen_after_bind());
  12058. });
  12059. svr_.wait_until_ready();
  12060. }
  12061. virtual void TearDown() {
  12062. svr_.stop();
  12063. t_.join();
  12064. }
  12065. Client cli_;
  12066. Server svr_;
  12067. thread t_;
  12068. };
  12069. TEST_F(ServerUpDownTest, QuickStartStop) {
  12070. // Should not crash, especially when run with
  12071. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12072. }
  12073. class PayloadMaxLengthTest : public ::testing::Test {
  12074. protected:
  12075. PayloadMaxLengthTest()
  12076. : cli_(HOST, PORT)
  12077. #ifdef CPPHTTPLIB_SSL_ENABLED
  12078. ,
  12079. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12080. #endif
  12081. {
  12082. #ifdef CPPHTTPLIB_SSL_ENABLED
  12083. cli_.enable_server_certificate_verification(false);
  12084. #endif
  12085. }
  12086. virtual void SetUp() {
  12087. svr_.set_payload_max_length(8);
  12088. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12089. res.set_content("test", "text/plain");
  12090. });
  12091. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12092. svr_.wait_until_ready();
  12093. }
  12094. virtual void TearDown() {
  12095. svr_.stop();
  12096. t_.join();
  12097. }
  12098. #ifdef CPPHTTPLIB_SSL_ENABLED
  12099. SSLClient cli_;
  12100. SSLServer svr_;
  12101. #else
  12102. Client cli_;
  12103. Server svr_;
  12104. #endif
  12105. thread t_;
  12106. };
  12107. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12108. auto res = cli_.Post("/test", "123456789", "text/plain");
  12109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12110. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12111. res = cli_.Post("/test", "12345678", "text/plain");
  12112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12113. EXPECT_EQ(StatusCode::OK_200, res->status);
  12114. }
  12115. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12116. // Test chunked encoding with payload exceeding the 8-byte limit
  12117. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12118. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12120. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12121. }
  12122. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12123. // Test chunked encoding with payload within the 8-byte limit
  12124. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12125. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12127. EXPECT_EQ(StatusCode::OK_200, res->status);
  12128. }
  12129. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12130. // Test using send_request to send chunked data exceeding payload limit
  12131. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12132. "Host: " +
  12133. std::string(HOST) + ":" + std::to_string(PORT) +
  12134. "\r\n"
  12135. "Transfer-Encoding: chunked\r\n"
  12136. "Connection: close\r\n"
  12137. "\r\n"
  12138. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12139. "0123456789\r\n"
  12140. "0\r\n" // End chunk
  12141. "\r\n";
  12142. std::string response;
  12143. bool result = send_request(1, chunked_request, &response);
  12144. if (!result) {
  12145. // If send_request fails, it might be because the server closed the
  12146. // connection due to payload limit enforcement, which is acceptable
  12147. SUCCEED()
  12148. << "Server rejected oversized chunked request (connection closed)";
  12149. } else {
  12150. // If we got a response, check if it's an error response or connection was
  12151. // closed early Short response length indicates connection was closed due to
  12152. // payload limit
  12153. if (response.length() <= 10) {
  12154. SUCCEED() << "Server closed connection for oversized chunked request";
  12155. } else {
  12156. // Check for error status codes
  12157. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12158. response.find("Payload Too Large") != std::string::npos ||
  12159. response.find("400") != std::string::npos);
  12160. }
  12161. }
  12162. }
  12163. class LargePayloadMaxLengthTest : public ::testing::Test {
  12164. protected:
  12165. LargePayloadMaxLengthTest()
  12166. : cli_(HOST, PORT)
  12167. #ifdef CPPHTTPLIB_SSL_ENABLED
  12168. ,
  12169. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12170. #endif
  12171. {
  12172. #ifdef CPPHTTPLIB_SSL_ENABLED
  12173. cli_.enable_server_certificate_verification(false);
  12174. #endif
  12175. }
  12176. virtual void SetUp() {
  12177. // Set 10MB payload limit
  12178. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12179. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12180. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12181. res.set_content("Large payload test", "text/plain");
  12182. });
  12183. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12184. svr_.wait_until_ready();
  12185. }
  12186. virtual void TearDown() {
  12187. svr_.stop();
  12188. t_.join();
  12189. }
  12190. #ifdef CPPHTTPLIB_SSL_ENABLED
  12191. SSLClient cli_;
  12192. SSLServer svr_;
  12193. #else
  12194. Client cli_;
  12195. Server svr_;
  12196. #endif
  12197. thread t_;
  12198. };
  12199. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12200. // Test chunked encoding with payload within 10MB limit
  12201. std::string medium_payload(5 * 1024 * 1024,
  12202. 'A'); // 5MB payload, within 10MB limit
  12203. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. EXPECT_EQ(StatusCode::OK_200, res->status);
  12206. }
  12207. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12208. // Test chunked encoding with payload exceeding 10MB limit
  12209. std::string large_payload(12 * 1024 * 1024,
  12210. 'B'); // 12MB payload, exceeds 10MB limit
  12211. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12212. // Server may either return 413 or close the connection
  12213. if (res) {
  12214. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12215. } else {
  12216. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12217. }
  12218. }
  12219. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12220. Server svr;
  12221. svr.Get("/", [](const Request &, Response &res) {
  12222. // Claims the most the client accepts, far more than it sends, then drops
  12223. // the connection.
  12224. res.set_content_provider(std::string().max_size(), "text/plain",
  12225. [](size_t, size_t, DataSink &sink) {
  12226. sink.write("abc", 3);
  12227. return false;
  12228. });
  12229. });
  12230. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12231. auto se = detail::scope_exit([&] {
  12232. svr.stop();
  12233. thread.join();
  12234. ASSERT_FALSE(svr.is_running());
  12235. });
  12236. svr.wait_until_ready();
  12237. Client cli(HOST, PORT);
  12238. cli.set_payload_max_length(0);
  12239. EXPECT_FALSE(cli.Get("/"));
  12240. }
  12241. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12242. // Stream API does, not as a plain read failure
  12243. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12244. Server svr;
  12245. svr.Get("/big", [](const Request &, Response &res) {
  12246. res.set_content(std::string(100000, 'b'), "text/plain");
  12247. });
  12248. auto port = svr.bind_to_any_port(HOST);
  12249. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12250. auto se = detail::scope_exit([&] {
  12251. svr.stop();
  12252. thread.join();
  12253. });
  12254. svr.wait_until_ready();
  12255. Client cli(HOST, port);
  12256. cli.set_payload_max_length(1000);
  12257. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12258. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12259. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12260. [](const char *, size_t) { return true; });
  12261. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12263. // Small on the wire, over the limit once decompressed
  12264. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12265. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12266. #endif
  12267. }
  12268. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12269. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12270. // path.
  12271. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12272. Server svr;
  12273. const size_t LIMIT = 64 * 1024; // 64KB
  12274. svr.set_payload_max_length(LIMIT);
  12275. size_t total = 0;
  12276. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12277. const ContentReader &content_reader) {
  12278. content_reader([&](const char * /*data*/, size_t len) {
  12279. total += len;
  12280. return true;
  12281. });
  12282. res.status = 200;
  12283. res.set_content("stream_ok", "text/plain");
  12284. });
  12285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12286. auto se = detail::scope_exit([&] {
  12287. svr.stop();
  12288. thread.join();
  12289. ASSERT_FALSE(svr.is_running());
  12290. });
  12291. svr.wait_until_ready();
  12292. // Prepare 256KB raw data and gzip-compress it
  12293. std::string raw(256 * 1024, 'A');
  12294. std::string gz;
  12295. {
  12296. z_stream zs{};
  12297. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12298. Z_DEFAULT_STRATEGY);
  12299. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12300. zs.avail_in = static_cast<uInt>(raw.size());
  12301. char outbuf[4096];
  12302. int ret;
  12303. do {
  12304. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12305. zs.avail_out = sizeof(outbuf);
  12306. ret = deflate(&zs, Z_FINISH);
  12307. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12308. } while (ret != Z_STREAM_END);
  12309. deflateEnd(&zs);
  12310. }
  12311. Client cli(HOST, PORT);
  12312. cli.set_connection_timeout(std::chrono::seconds(5));
  12313. Headers headers = {{"Content-Encoding", "gzip"}};
  12314. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12315. "application/octet-stream");
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. // Server must reject oversized decompressed payloads with 413.
  12318. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12319. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12320. EXPECT_LE(total, LIMIT);
  12321. }
  12322. #endif
  12323. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12324. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12325. // the payload must be passed through untouched instead of being rejected.
  12326. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12327. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12328. Server svr;
  12329. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12330. res.set_content(body, "image/jpeg");
  12331. res.set_header("Content-Encoding", "UTF-8");
  12332. });
  12333. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12334. res.set_content(body, "image/jpeg");
  12335. res.set_header("Content-Encoding", "identity");
  12336. });
  12337. svr.Post("/echo", [](const Request &req, Response &res) {
  12338. res.set_content(req.body, "image/jpeg");
  12339. });
  12340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12341. auto se = detail::scope_exit([&] {
  12342. svr.stop();
  12343. t.join();
  12344. ASSERT_FALSE(svr.is_running());
  12345. });
  12346. svr.wait_until_ready();
  12347. Client cli(HOST, PORT);
  12348. {
  12349. auto res = cli.Get("/image");
  12350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12351. EXPECT_EQ(StatusCode::OK_200, res->status);
  12352. EXPECT_EQ(body, res->body);
  12353. }
  12354. {
  12355. auto res = cli.Get("/identity");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. EXPECT_EQ(StatusCode::OK_200, res->status);
  12358. EXPECT_EQ(body, res->body);
  12359. }
  12360. {
  12361. // The same applies to a request body reaching the server.
  12362. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12363. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::OK_200, res->status);
  12366. EXPECT_EQ(body, res->body);
  12367. }
  12368. }
  12369. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12370. // gzip-encoded response even when the build has no zlib support.
  12371. static const char GZIPPED_HELLO_WORLD[] = {
  12372. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12373. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12374. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12375. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12376. // A content coding is a whole token, not something the field value merely
  12377. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12378. // as "fibre" look like Brotli, and turned a multi-coding value like
  12379. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12380. // it was never meant to see.
  12381. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12382. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12383. Server svr;
  12384. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12385. res.set_content(body, "image/jpeg");
  12386. res.set_header("Content-Encoding", "fibre");
  12387. });
  12388. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12389. res.set_content(body, "image/jpeg");
  12390. res.set_header("Content-Encoding", "gzip, br");
  12391. });
  12392. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(body, "image/jpeg");
  12394. res.set_header("Content-Encoding", "x-zstd-ish");
  12395. });
  12396. auto port = svr.bind_to_any_port(HOST);
  12397. thread t = thread([&]() { svr.listen_after_bind(); });
  12398. auto se = detail::scope_exit([&] {
  12399. svr.stop();
  12400. t.join();
  12401. ASSERT_FALSE(svr.is_running());
  12402. });
  12403. svr.wait_until_ready();
  12404. Client cli(HOST, port);
  12405. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12406. auto res = cli.Get(path);
  12407. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12408. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12409. // Not a coding we recognize, so the payload comes back untouched
  12410. EXPECT_EQ(body, res->body) << path;
  12411. }
  12412. }
  12413. // A content coding cpp-httplib recognizes but was not built with must be
  12414. // reported as such. Handing the still-compressed payload back to the caller
  12415. // would silently corrupt it.
  12416. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12417. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12418. Server svr;
  12419. // "image/jpeg" keeps the server from applying a content coding of its own,
  12420. // so the hand-crafted Content-Encoding below survives.
  12421. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12422. res.set_content(gzipped, "image/jpeg");
  12423. res.set_header("Content-Encoding", "gzip");
  12424. });
  12425. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12426. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12427. res.set_content(gzipped, "image/jpeg");
  12428. res.set_header("Content-Encoding", "GZIP");
  12429. });
  12430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12431. auto se = detail::scope_exit([&] {
  12432. svr.stop();
  12433. t.join();
  12434. ASSERT_FALSE(svr.is_running());
  12435. });
  12436. svr.wait_until_ready();
  12437. Client cli(HOST, PORT);
  12438. {
  12439. auto res = cli.Get("/gzipped");
  12440. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12442. EXPECT_EQ("Hello World!", res->body);
  12443. #else
  12444. ASSERT_FALSE(res);
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12446. #endif
  12447. }
  12448. {
  12449. // open_stream() must behave the same way.
  12450. auto handle = cli.open_stream("GET", "/gzipped");
  12451. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12452. ASSERT_TRUE(handle.is_valid());
  12453. std::string received;
  12454. char buf[256];
  12455. ssize_t n;
  12456. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12457. received.append(buf, static_cast<size_t>(n));
  12458. }
  12459. EXPECT_EQ("Hello World!", received);
  12460. #else
  12461. EXPECT_FALSE(handle.is_valid());
  12462. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12463. #endif
  12464. }
  12465. {
  12466. // A differently-cased coding must not be mistaken for an unknown one, or
  12467. // the body would be handed back still compressed.
  12468. auto res = cli.Get("/gzipped-uppercase");
  12469. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ("Hello World!", res->body);
  12472. #else
  12473. ASSERT_FALSE(res);
  12474. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12475. #endif
  12476. }
  12477. }
  12478. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12479. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12480. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12481. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12482. // body a second time and appending a second Content-Encoding field line, so
  12483. // clients that decode one coding per listed value handed back raw gzip bytes.
  12484. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12485. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12486. Server svr;
  12487. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12488. // keeps the server from applying a coding of its own.
  12489. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content(gzipped, "text/plain");
  12491. res.set_header("Content-Encoding", "gzip");
  12492. });
  12493. auto port = svr.bind_to_any_port(HOST);
  12494. thread t = thread([&]() { svr.listen_after_bind(); });
  12495. auto se = detail::scope_exit([&] {
  12496. svr.stop();
  12497. t.join();
  12498. ASSERT_FALSE(svr.is_running());
  12499. });
  12500. svr.wait_until_ready();
  12501. Client cli(HOST, port);
  12502. Headers headers = {{"Accept-Encoding", "gzip"}};
  12503. auto res = cli.Get("/pre-gzipped", headers);
  12504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12505. EXPECT_EQ(StatusCode::OK_200, res->status);
  12506. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12507. EXPECT_EQ("Hello World!", res->body);
  12508. }
  12509. // set_compress(false) sends every handler response as it is, buffered or
  12510. // streamed
  12511. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12512. const std::string text(1000, 'a');
  12513. Server svr;
  12514. svr.set_compress(false);
  12515. svr.Get("/buffered", [&](const Request &, Response &res) {
  12516. res.set_content(text, "text/plain");
  12517. });
  12518. svr.Get("/streamed", [&](const Request &, Response &res) {
  12519. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12520. sink.write(text.data(), text.size());
  12521. sink.done();
  12522. return true;
  12523. });
  12524. });
  12525. auto port = svr.bind_to_any_port(HOST);
  12526. ASSERT_LT(0, port);
  12527. thread t = thread([&] { svr.listen_after_bind(); });
  12528. auto se = detail::scope_exit([&] {
  12529. svr.stop();
  12530. t.join();
  12531. ASSERT_FALSE(svr.is_running());
  12532. });
  12533. svr.wait_until_ready();
  12534. Client cli(HOST, port);
  12535. cli.set_decompress(false);
  12536. for (auto path : {"/buffered", "/streamed"}) {
  12537. SCOPED_TRACE(path);
  12538. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12540. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12541. EXPECT_EQ(text, res->body);
  12542. }
  12543. }
  12544. // A chunked provider settles its coding where the headers are written and
  12545. // reuses it at write time. Both ends of that have to hold: a handler's own
  12546. // Content-Encoding suppresses the coding, and a response without one is still
  12547. // compressed as it always was.
  12548. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12549. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12550. const std::string plain = "Hello World! Hello World! Hello World!";
  12551. Server svr;
  12552. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12553. res.set_header("Content-Encoding", "gzip");
  12554. res.set_chunked_content_provider(
  12555. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12556. sink.write(gzipped.data(), gzipped.size());
  12557. sink.done();
  12558. return true;
  12559. });
  12560. });
  12561. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12562. res.set_chunked_content_provider(
  12563. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12564. sink.write(plain.data(), plain.size());
  12565. sink.done();
  12566. return true;
  12567. });
  12568. });
  12569. auto port = svr.bind_to_any_port(HOST);
  12570. thread t = thread([&]() { svr.listen_after_bind(); });
  12571. auto se = detail::scope_exit([&] {
  12572. svr.stop();
  12573. t.join();
  12574. ASSERT_FALSE(svr.is_running());
  12575. });
  12576. svr.wait_until_ready();
  12577. Client cli(HOST, port);
  12578. Headers headers = {{"Accept-Encoding", "gzip"}};
  12579. {
  12580. auto res = cli.Get("/pre-gzipped", headers);
  12581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12582. EXPECT_EQ(StatusCode::OK_200, res->status);
  12583. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12584. EXPECT_EQ("Hello World!", res->body);
  12585. }
  12586. {
  12587. auto res = cli.Get("/negotiated", headers);
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. EXPECT_EQ(StatusCode::OK_200, res->status);
  12590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12591. EXPECT_EQ(plain, res->body);
  12592. }
  12593. }
  12594. #endif
  12595. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12596. // the same message as the comma-joined one, so both have to be read the same
  12597. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12598. // single gzip coding, and a body the sender says was encoded twice was handed
  12599. // back after one pass, still compressed but presented as decoded.
  12600. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12601. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12602. Server svr;
  12603. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12604. res.set_content(body, "image/jpeg");
  12605. res.headers.emplace("Content-Encoding", "gzip");
  12606. res.headers.emplace("Content-Encoding", "gzip");
  12607. });
  12608. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12609. res.set_content(body, "image/jpeg");
  12610. res.set_header("Content-Encoding", "gzip, gzip");
  12611. });
  12612. auto port = svr.bind_to_any_port(HOST);
  12613. thread t = thread([&]() { svr.listen_after_bind(); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. t.join();
  12617. ASSERT_FALSE(svr.is_running());
  12618. });
  12619. svr.wait_until_ready();
  12620. Client cli(HOST, port);
  12621. // Two codings is not something cpp-httplib decodes, so both representations
  12622. // take the pass-through path rather than one of them being gunzipped once.
  12623. for (const char *path : {"/split", "/joined"}) {
  12624. auto res = cli.Get(path);
  12625. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12626. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12627. EXPECT_EQ(body, res->body) << path;
  12628. }
  12629. }
  12630. // Regression test for DoS vulnerability: a malicious server sending a response
  12631. // without Content-Length header must not cause unbounded memory consumption on
  12632. // the client side. The client should stop reading after a reasonable limit,
  12633. // similar to the server-side set_payload_max_length protection.
  12634. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12635. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12636. #ifndef _WIN32
  12637. signal(SIGPIPE, SIG_IGN);
  12638. #endif
  12639. auto server_thread = std::thread([] {
  12640. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12642. default_socket_options(srv);
  12643. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12645. sockaddr_in addr{};
  12646. addr.sin_family = AF_INET;
  12647. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12648. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12649. int opt = 1;
  12650. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12651. #ifdef _WIN32
  12652. reinterpret_cast<const char *>(&opt),
  12653. #else
  12654. &opt,
  12655. #endif
  12656. sizeof(opt));
  12657. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12658. ::listen(srv, 1);
  12659. sockaddr_in cli_addr{};
  12660. socklen_t cli_len = sizeof(cli_addr);
  12661. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12662. if (cli != INVALID_SOCKET) {
  12663. char buf[4096];
  12664. ::recv(cli, buf, sizeof(buf), 0);
  12665. // Malicious response: no Content-Length, no chunked encoding
  12666. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12667. "Connection: close\r\n"
  12668. "\r\n";
  12669. ::send(cli,
  12670. #ifdef _WIN32
  12671. static_cast<const char *>(response_header.c_str()),
  12672. static_cast<int>(response_header.size()),
  12673. #else
  12674. response_header.c_str(), response_header.size(),
  12675. #endif
  12676. 0);
  12677. // Send 10MB of data
  12678. std::string chunk(64 * 1024, 'A');
  12679. size_t total_sent = 0;
  12680. while (total_sent < MALICIOUS_DATA_SIZE) {
  12681. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12682. auto sent = ::send(cli,
  12683. #ifdef _WIN32
  12684. static_cast<const char *>(chunk.c_str()),
  12685. static_cast<int>(to_send),
  12686. #else
  12687. chunk.c_str(), to_send,
  12688. #endif
  12689. 0);
  12690. if (sent <= 0) break;
  12691. total_sent += static_cast<size_t>(sent);
  12692. }
  12693. detail::close_socket(cli);
  12694. }
  12695. detail::close_socket(srv);
  12696. });
  12697. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12698. size_t total_read = 0;
  12699. {
  12700. Client cli("127.0.0.1", PORT + 2);
  12701. cli.set_read_timeout(5, 0);
  12702. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12703. auto stream = cli.open_stream("GET", "/malicious");
  12704. ASSERT_TRUE(stream.is_valid());
  12705. char buffer[64 * 1024];
  12706. ssize_t n;
  12707. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12708. total_read += static_cast<size_t>(n);
  12709. }
  12710. } // StreamHandle and Client destroyed here, closing the socket
  12711. server_thread.join();
  12712. // With set_payload_max_length, the client must stop reading before consuming
  12713. // all 10MB. The read loop should be cut off at or near the configured limit.
  12714. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12715. << "Client read " << total_read << " bytes, exceeding the configured "
  12716. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12717. }
  12718. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12719. // the entire response body without truncation.
  12720. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12721. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12722. #ifndef _WIN32
  12723. signal(SIGPIPE, SIG_IGN);
  12724. #endif
  12725. auto server_thread = std::thread([] {
  12726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12727. default_socket_options(srv);
  12728. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12730. sockaddr_in addr{};
  12731. addr.sin_family = AF_INET;
  12732. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12734. int opt = 1;
  12735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12736. #ifdef _WIN32
  12737. reinterpret_cast<const char *>(&opt),
  12738. #else
  12739. &opt,
  12740. #endif
  12741. sizeof(opt));
  12742. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12743. ::listen(srv, 1);
  12744. sockaddr_in cli_addr{};
  12745. socklen_t cli_len = sizeof(cli_addr);
  12746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12747. if (cli != INVALID_SOCKET) {
  12748. char buf[4096];
  12749. ::recv(cli, buf, sizeof(buf), 0);
  12750. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12751. "Connection: close\r\n"
  12752. "\r\n";
  12753. ::send(cli,
  12754. #ifdef _WIN32
  12755. static_cast<const char *>(response_header.c_str()),
  12756. static_cast<int>(response_header.size()),
  12757. #else
  12758. response_header.c_str(), response_header.size(),
  12759. #endif
  12760. 0);
  12761. std::string chunk(64 * 1024, 'A');
  12762. size_t total_sent = 0;
  12763. while (total_sent < DATA_SIZE) {
  12764. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12765. auto sent = ::send(cli,
  12766. #ifdef _WIN32
  12767. static_cast<const char *>(chunk.c_str()),
  12768. static_cast<int>(to_send),
  12769. #else
  12770. chunk.c_str(), to_send,
  12771. #endif
  12772. 0);
  12773. if (sent <= 0) break;
  12774. total_sent += static_cast<size_t>(sent);
  12775. }
  12776. #ifdef _WIN32
  12777. ::shutdown(cli, SD_SEND);
  12778. #else
  12779. ::shutdown(cli, SHUT_WR);
  12780. #endif
  12781. // Drain until the client closes its end, ensuring all data is delivered
  12782. char drain[1024];
  12783. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12784. detail::close_socket(cli);
  12785. }
  12786. detail::close_socket(srv);
  12787. });
  12788. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12789. size_t total_read = 0;
  12790. {
  12791. Client cli("127.0.0.1", PORT + 2);
  12792. cli.set_read_timeout(5, 0);
  12793. cli.set_payload_max_length(0); // 0 means no limit
  12794. auto stream = cli.open_stream("GET", "/data");
  12795. ASSERT_TRUE(stream.is_valid());
  12796. char buffer[64 * 1024];
  12797. ssize_t n;
  12798. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12799. total_read += static_cast<size_t>(n);
  12800. }
  12801. }
  12802. server_thread.join();
  12803. EXPECT_EQ(total_read, DATA_SIZE)
  12804. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12805. << " bytes without truncation, but only read " << total_read << " bytes.";
  12806. }
  12807. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12808. // enormous Content-Length must not cause the client to pre-allocate a huge
  12809. // response body buffer. The reservation is capped at payload_max_length_, and
  12810. // the read itself fails when the body exceeds the limit.
  12811. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12812. #ifndef _WIN32
  12813. signal(SIGPIPE, SIG_IGN);
  12814. #endif
  12815. auto server_thread = std::thread([] {
  12816. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12817. default_socket_options(srv);
  12818. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12819. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12820. sockaddr_in addr{};
  12821. addr.sin_family = AF_INET;
  12822. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12823. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12824. int opt = 1;
  12825. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12826. #ifdef _WIN32
  12827. reinterpret_cast<const char *>(&opt),
  12828. #else
  12829. &opt,
  12830. #endif
  12831. sizeof(opt));
  12832. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12833. ::listen(srv, 1);
  12834. sockaddr_in cli_addr{};
  12835. socklen_t cli_len = sizeof(cli_addr);
  12836. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12837. if (cli != INVALID_SOCKET) {
  12838. char buf[4096];
  12839. ::recv(cli, buf, sizeof(buf), 0);
  12840. // Malicious response: claim a 20GB body but send only a tiny payload.
  12841. std::string response = "HTTP/1.1 200 OK\r\n"
  12842. "Content-Length: 20000000000\r\n"
  12843. "\r\n"
  12844. "abc";
  12845. ::send(cli,
  12846. #ifdef _WIN32
  12847. static_cast<const char *>(response.c_str()),
  12848. static_cast<int>(response.size()),
  12849. #else
  12850. response.c_str(), response.size(),
  12851. #endif
  12852. 0);
  12853. detail::close_socket(cli);
  12854. }
  12855. detail::close_socket(srv);
  12856. });
  12857. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12858. {
  12859. Client cli("127.0.0.1", PORT + 2);
  12860. cli.set_read_timeout(5, 0);
  12861. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12862. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12863. // (server claims more bytes than payload_max_length permits), but it must
  12864. // not exhaust memory before getting there.
  12865. auto res = cli.Get("/malicious");
  12866. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12867. }
  12868. server_thread.join();
  12869. }
  12870. // Verify that content_receiver bypasses the default payload_max_length,
  12871. // allowing streaming downloads larger than 100MB without requiring an explicit
  12872. // set_payload_max_length call.
  12873. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12874. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12875. #ifndef _WIN32
  12876. signal(SIGPIPE, SIG_IGN);
  12877. #endif
  12878. auto server_thread = std::thread([] {
  12879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12880. default_socket_options(srv);
  12881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12883. sockaddr_in addr{};
  12884. addr.sin_family = AF_INET;
  12885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12887. int opt = 1;
  12888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12889. #ifdef _WIN32
  12890. reinterpret_cast<const char *>(&opt),
  12891. #else
  12892. &opt,
  12893. #endif
  12894. sizeof(opt));
  12895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12896. ::listen(srv, 1);
  12897. sockaddr_in cli_addr{};
  12898. socklen_t cli_len = sizeof(cli_addr);
  12899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12900. if (cli != INVALID_SOCKET) {
  12901. char buf[4096];
  12902. ::recv(cli, buf, sizeof(buf), 0);
  12903. // Response with Content-Length larger than default 100MB limit
  12904. auto content_length = std::to_string(DATA_SIZE);
  12905. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12906. "Content-Length: " +
  12907. content_length +
  12908. "\r\n"
  12909. "Connection: close\r\n"
  12910. "\r\n";
  12911. ::send(cli,
  12912. #ifdef _WIN32
  12913. static_cast<const char *>(response_header.c_str()),
  12914. static_cast<int>(response_header.size()),
  12915. #else
  12916. response_header.c_str(), response_header.size(),
  12917. #endif
  12918. 0);
  12919. std::string chunk(64 * 1024, 'A');
  12920. size_t total_sent = 0;
  12921. while (total_sent < DATA_SIZE) {
  12922. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12923. auto sent = ::send(cli,
  12924. #ifdef _WIN32
  12925. static_cast<const char *>(chunk.c_str()),
  12926. static_cast<int>(to_send),
  12927. #else
  12928. chunk.c_str(), to_send,
  12929. #endif
  12930. 0);
  12931. if (sent <= 0) break;
  12932. total_sent += static_cast<size_t>(sent);
  12933. }
  12934. detail::close_socket(cli);
  12935. }
  12936. detail::close_socket(srv);
  12937. });
  12938. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12939. size_t total_received = 0;
  12940. {
  12941. Client cli("127.0.0.1", PORT + 2);
  12942. cli.set_read_timeout(10, 0);
  12943. // Do NOT call set_payload_max_length — use the default 100MB limit
  12944. auto res =
  12945. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12946. total_received += data_length;
  12947. return true;
  12948. });
  12949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12950. EXPECT_EQ(StatusCode::OK_200, res->status);
  12951. }
  12952. server_thread.join();
  12953. EXPECT_EQ(total_received, DATA_SIZE)
  12954. << "With content_receiver, the client should read all " << DATA_SIZE
  12955. << " bytes despite the default 100MB payload_max_length, but only read "
  12956. << total_received << " bytes.";
  12957. }
  12958. // Verify that an explicit set_payload_max_length smaller than the response is
  12959. // enforced even when a content_receiver is used.
  12960. TEST(ClientVulnerabilityTest,
  12961. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12962. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12963. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12964. #ifndef _WIN32
  12965. signal(SIGPIPE, SIG_IGN);
  12966. #endif
  12967. auto server_thread = std::thread([] {
  12968. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12969. default_socket_options(srv);
  12970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12971. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12972. sockaddr_in addr{};
  12973. addr.sin_family = AF_INET;
  12974. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12975. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12976. int opt = 1;
  12977. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12978. #ifdef _WIN32
  12979. reinterpret_cast<const char *>(&opt),
  12980. #else
  12981. &opt,
  12982. #endif
  12983. sizeof(opt));
  12984. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12985. ::listen(srv, 1);
  12986. sockaddr_in cli_addr{};
  12987. socklen_t cli_len = sizeof(cli_addr);
  12988. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12989. if (cli != INVALID_SOCKET) {
  12990. char buf[4096];
  12991. ::recv(cli, buf, sizeof(buf), 0);
  12992. auto content_length = std::to_string(DATA_SIZE);
  12993. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12994. "Content-Length: " +
  12995. content_length +
  12996. "\r\n"
  12997. "Connection: close\r\n"
  12998. "\r\n";
  12999. ::send(cli,
  13000. #ifdef _WIN32
  13001. static_cast<const char *>(response_header.c_str()),
  13002. static_cast<int>(response_header.size()),
  13003. #else
  13004. response_header.c_str(), response_header.size(),
  13005. #endif
  13006. 0);
  13007. std::string chunk(64 * 1024, 'A');
  13008. size_t total_sent = 0;
  13009. while (total_sent < DATA_SIZE) {
  13010. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13011. auto sent = ::send(cli,
  13012. #ifdef _WIN32
  13013. static_cast<const char *>(chunk.c_str()),
  13014. static_cast<int>(to_send),
  13015. #else
  13016. chunk.c_str(), to_send,
  13017. #endif
  13018. 0);
  13019. if (sent <= 0) break;
  13020. total_sent += static_cast<size_t>(sent);
  13021. }
  13022. detail::close_socket(cli);
  13023. }
  13024. detail::close_socket(srv);
  13025. });
  13026. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13027. size_t total_received = 0;
  13028. {
  13029. Client cli("127.0.0.1", PORT + 2);
  13030. cli.set_read_timeout(10, 0);
  13031. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13032. auto res =
  13033. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13034. total_received += data_length;
  13035. return true;
  13036. });
  13037. // Should fail because 200MB exceeds the explicit 150MB limit
  13038. EXPECT_FALSE(res);
  13039. }
  13040. server_thread.join();
  13041. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13042. << "Client with content_receiver should respect the explicit "
  13043. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13044. << total_received << " bytes.";
  13045. }
  13046. // Verify that an explicit set_payload_max_length larger than the response
  13047. // allows the content_receiver to read all data successfully.
  13048. TEST(ClientVulnerabilityTest,
  13049. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13050. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13051. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13052. #ifndef _WIN32
  13053. signal(SIGPIPE, SIG_IGN);
  13054. #endif
  13055. auto server_thread = std::thread([] {
  13056. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13057. default_socket_options(srv);
  13058. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13059. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13060. sockaddr_in addr{};
  13061. addr.sin_family = AF_INET;
  13062. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13063. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13064. int opt = 1;
  13065. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13066. #ifdef _WIN32
  13067. reinterpret_cast<const char *>(&opt),
  13068. #else
  13069. &opt,
  13070. #endif
  13071. sizeof(opt));
  13072. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13073. ::listen(srv, 1);
  13074. sockaddr_in cli_addr{};
  13075. socklen_t cli_len = sizeof(cli_addr);
  13076. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13077. if (cli != INVALID_SOCKET) {
  13078. char buf[4096];
  13079. ::recv(cli, buf, sizeof(buf), 0);
  13080. auto content_length = std::to_string(DATA_SIZE);
  13081. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13082. "Content-Length: " +
  13083. content_length +
  13084. "\r\n"
  13085. "Connection: close\r\n"
  13086. "\r\n";
  13087. ::send(cli,
  13088. #ifdef _WIN32
  13089. static_cast<const char *>(response_header.c_str()),
  13090. static_cast<int>(response_header.size()),
  13091. #else
  13092. response_header.c_str(), response_header.size(),
  13093. #endif
  13094. 0);
  13095. std::string chunk(64 * 1024, 'A');
  13096. size_t total_sent = 0;
  13097. while (total_sent < DATA_SIZE) {
  13098. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13099. auto sent = ::send(cli,
  13100. #ifdef _WIN32
  13101. static_cast<const char *>(chunk.c_str()),
  13102. static_cast<int>(to_send),
  13103. #else
  13104. chunk.c_str(), to_send,
  13105. #endif
  13106. 0);
  13107. if (sent <= 0) break;
  13108. total_sent += static_cast<size_t>(sent);
  13109. }
  13110. #ifdef _WIN32
  13111. ::shutdown(cli, SD_SEND);
  13112. #else
  13113. ::shutdown(cli, SHUT_WR);
  13114. #endif
  13115. char drain[1024];
  13116. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13117. detail::close_socket(cli);
  13118. }
  13119. detail::close_socket(srv);
  13120. });
  13121. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13122. size_t total_received = 0;
  13123. {
  13124. Client cli("127.0.0.1", PORT + 2);
  13125. cli.set_read_timeout(10, 0);
  13126. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13127. auto res =
  13128. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13129. total_received += data_length;
  13130. return true;
  13131. });
  13132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13133. EXPECT_EQ(StatusCode::OK_200, res->status);
  13134. }
  13135. server_thread.join();
  13136. EXPECT_EQ(total_received, DATA_SIZE)
  13137. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13138. << " bytes (larger than " << DATA_SIZE
  13139. << " bytes response), content_receiver should read all data, but only "
  13140. "read "
  13141. << total_received << " bytes.";
  13142. }
  13143. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13144. // Regression test for "zip bomb" attack on the client side: a malicious server
  13145. // sends a small gzip-compressed response that decompresses to a huge payload.
  13146. // The client must enforce payload_max_length on the decompressed size.
  13147. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13148. constexpr size_t DECOMPRESSED_SIZE =
  13149. 10 * 1024 * 1024; // 10MB after decompression
  13150. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13151. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13152. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13153. std::string compressed;
  13154. {
  13155. httplib::detail::gzip_compressor compressor;
  13156. bool ok =
  13157. compressor.compress(uncompressed.data(), uncompressed.size(),
  13158. /*last=*/true, [&](const char *buf, size_t len) {
  13159. compressed.append(buf, len);
  13160. return true;
  13161. });
  13162. ASSERT_TRUE(ok);
  13163. }
  13164. // Sanity: compressed data should be much smaller than the decompressed size
  13165. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13166. #ifndef _WIN32
  13167. signal(SIGPIPE, SIG_IGN);
  13168. #endif
  13169. // Set up the listening socket in the main thread so the server is guaranteed
  13170. // to be ready before the client connects (eliminates race condition).
  13171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13172. default_socket_options(srv);
  13173. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13175. sockaddr_in addr{};
  13176. addr.sin_family = AF_INET;
  13177. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13178. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13179. int opt = 1;
  13180. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13181. #ifdef _WIN32
  13182. reinterpret_cast<const char *>(&opt),
  13183. #else
  13184. &opt,
  13185. #endif
  13186. sizeof(opt));
  13187. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13188. ASSERT_EQ(0, ::listen(srv, 1));
  13189. auto server_thread = std::thread([&compressed, srv] {
  13190. sockaddr_in cli_addr{};
  13191. socklen_t cli_len = sizeof(cli_addr);
  13192. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13193. if (cli != INVALID_SOCKET) {
  13194. // Read the full HTTP request (until \r\n\r\n)
  13195. char buf[4096];
  13196. size_t total = 0;
  13197. while (total < sizeof(buf)) {
  13198. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13199. if (n <= 0) break;
  13200. total += static_cast<size_t>(n);
  13201. // Check for end of headers
  13202. if (total >= 4) {
  13203. std::string req(buf, total);
  13204. if (req.find("\r\n\r\n") != std::string::npos) break;
  13205. }
  13206. }
  13207. // Malicious response: gzip-compressed body, no Content-Length
  13208. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13209. "Content-Encoding: gzip\r\n"
  13210. "Connection: close\r\n"
  13211. "\r\n";
  13212. ::send(cli,
  13213. #ifdef _WIN32
  13214. static_cast<const char *>(response_header.c_str()),
  13215. static_cast<int>(response_header.size()),
  13216. #else
  13217. response_header.c_str(), response_header.size(),
  13218. #endif
  13219. 0);
  13220. // Send the compressed payload (small on the wire, huge when decompressed)
  13221. size_t total_sent = 0;
  13222. while (total_sent < compressed.size()) {
  13223. auto to_send = std::min(compressed.size() - total_sent,
  13224. static_cast<size_t>(64 * 1024));
  13225. auto sent =
  13226. ::send(cli,
  13227. #ifdef _WIN32
  13228. static_cast<const char *>(compressed.c_str() + total_sent),
  13229. static_cast<int>(to_send),
  13230. #else
  13231. compressed.c_str() + total_sent, to_send,
  13232. #endif
  13233. 0);
  13234. if (sent <= 0) break;
  13235. total_sent += static_cast<size_t>(sent);
  13236. }
  13237. detail::close_socket(cli);
  13238. }
  13239. });
  13240. auto se = detail::scope_exit([&] {
  13241. detail::close_socket(srv);
  13242. server_thread.join();
  13243. });
  13244. size_t total_decompressed = 0;
  13245. {
  13246. Client cli("127.0.0.1", PORT + 3);
  13247. cli.set_read_timeout(5, 0);
  13248. cli.set_decompress(true);
  13249. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13250. auto stream = cli.open_stream("GET", "/zipbomb");
  13251. ASSERT_TRUE(stream.is_valid());
  13252. char buffer[64 * 1024];
  13253. ssize_t n;
  13254. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13255. total_decompressed += static_cast<size_t>(n);
  13256. }
  13257. }
  13258. // The decompressed size must be capped by payload_max_length. Without
  13259. // protection, the client would decompress the full 10MB from a tiny
  13260. // compressed payload, enabling a zip bomb DoS attack.
  13261. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13262. << "Client decompressed " << total_decompressed
  13263. << " bytes from a gzip response. The decompressed size should be "
  13264. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13265. }
  13266. #endif
  13267. TEST(HostAndPortPropertiesTest, NoSSL) {
  13268. httplib::Client cli("www.google.com", 1234);
  13269. ASSERT_EQ("www.google.com", cli.host());
  13270. ASSERT_EQ(1234, cli.port());
  13271. }
  13272. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13273. httplib::Client cli("www.google.com:1234");
  13274. ASSERT_EQ("www.google.com", cli.host());
  13275. ASSERT_EQ(1234, cli.port());
  13276. }
  13277. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13278. // Port number that overflows int — should not crash, client becomes invalid
  13279. httplib::Client cli("http://www.google.com:99999999999999999999");
  13280. ASSERT_FALSE(cli.is_valid());
  13281. }
  13282. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13283. // Port 99999 exceeds valid range (1-65535) — should not crash
  13284. httplib::Client cli("http://www.google.com:99999");
  13285. ASSERT_FALSE(cli.is_valid());
  13286. auto res = cli.Get("/");
  13287. EXPECT_FALSE(res);
  13288. EXPECT_EQ(Error::Connection, res.error());
  13289. }
  13290. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13291. httplib::Client cli("http://user:pass@localhost:1234");
  13292. ASSERT_FALSE(cli.is_valid());
  13293. EXPECT_FALSE(cli.Get("/"));
  13294. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13295. }
  13296. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13297. httplib::Client cli("http://www.google.com:80abc");
  13298. ASSERT_FALSE(cli.is_valid());
  13299. }
  13300. #ifdef CPPHTTPLIB_SSL_ENABLED
  13301. TEST(HostAndPortPropertiesTest, SSL) {
  13302. httplib::SSLClient cli("www.google.com");
  13303. ASSERT_EQ("www.google.com", cli.host());
  13304. ASSERT_EQ(443, cli.port());
  13305. }
  13306. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13307. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13308. std::string cert;
  13309. read_file(CA_CERT_FILE, cert);
  13310. httplib::SSLClient httplib_client("www.google.com");
  13311. // Load CA store first time
  13312. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13313. // Load CA store second time (update)
  13314. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13315. // Verify client is still valid and can make connections
  13316. httplib_client.enable_server_certificate_verification(true);
  13317. auto res = httplib_client.Get("/");
  13318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13319. // Google may return 200 or 301 depending on various factors
  13320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13321. res->status == StatusCode::MovedPermanently_301);
  13322. }
  13323. TEST(SSLClientTest, ServerNameIndication_Online) {
  13324. auto host = "httpbingo.org";
  13325. auto path = std::string{"/get"};
  13326. SSLClient cli(host, 443);
  13327. auto res = cli.Get(path);
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. ASSERT_EQ(StatusCode::OK_200, res->status);
  13330. }
  13331. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13332. // Use a site that will cause SSL verification failure due to self-signed cert
  13333. SSLClient cli("self-signed.badssl.com", 443);
  13334. cli.enable_server_certificate_verification(true);
  13335. auto res = cli.Get("/");
  13336. ASSERT_TRUE(!res);
  13337. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13338. // Verify backend error is captured for SSLServerVerification
  13339. // This occurs when certificate verification fails
  13340. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13341. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13342. EXPECT_NE(0UL, res.ssl_backend_error());
  13343. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13344. res.ssl_error());
  13345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13346. #if !defined(_WIN32) || \
  13347. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13348. // On non-Windows or when Windows Schannel is disabled, the error comes
  13349. // from OpenSSL's verification
  13350. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13351. res.ssl_backend_error());
  13352. #endif
  13353. #endif
  13354. }
  13355. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13356. // Use a site where hostname doesn't match the certificate
  13357. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13358. SSLClient cli("wrong.host.badssl.com", 443);
  13359. cli.enable_server_certificate_verification(true);
  13360. cli.enable_server_hostname_verification(true);
  13361. auto res = cli.Get("/");
  13362. ASSERT_TRUE(!res);
  13363. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13364. // Verify backend error is captured for hostname verification failure
  13365. EXPECT_NE(0UL, res.ssl_backend_error());
  13366. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13367. res.ssl_error());
  13368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13369. #if !defined(_WIN32) || \
  13370. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13371. // On non-Windows or when Windows Schannel is disabled, the error comes
  13372. // from OpenSSL's hostname verification
  13373. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13374. res.ssl_backend_error());
  13375. #endif
  13376. #endif
  13377. }
  13378. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13379. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13380. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13381. SSLClient cli("www.google.com", 443);
  13382. cli.enable_server_certificate_verification(true);
  13383. auto res = cli.Get("/");
  13384. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13385. }
  13386. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13387. SSLClient cli("www.google.com", 443);
  13388. cli.enable_server_certificate_verification(true);
  13389. cli.enable_windows_certificate_verification(false);
  13390. auto res = cli.Get("/");
  13391. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13392. }
  13393. // The server sends an intermediate cross-signed by a root Windows trusts,
  13394. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13395. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13396. SSLClient cli("accounts.spotify.com", 443);
  13397. auto res = cli.Get("/");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13399. << " ssl_backend_error=" << res.ssl_backend_error();
  13400. }
  13401. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13402. // policy status, which no backend reports for a self-signed certificate.
  13403. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13404. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13405. ASSERT_TRUE(svr.is_valid());
  13406. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", 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. SSLClient cli("127.0.0.1", PORT);
  13414. cli.set_connection_timeout(30);
  13415. auto res = cli.Get("/");
  13416. ASSERT_FALSE(res);
  13417. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13418. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13419. }
  13420. #endif
  13421. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13422. Client cli("https://google.com");
  13423. auto res = cli.Get("/");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13426. }
  13427. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13428. SSLClient cli("google.com");
  13429. cli.set_ca_cert_path(CA_CERT_FILE);
  13430. auto res = cli.Get("/");
  13431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13432. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13433. }
  13434. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13435. SSLClient cli("google.com");
  13436. cli.enable_server_certificate_verification(true);
  13437. cli.set_ca_cert_path("hello");
  13438. auto res = cli.Get("/");
  13439. ASSERT_TRUE(!res);
  13440. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13441. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13442. // should be set
  13443. EXPECT_EQ(0, res.ssl_error());
  13444. // Verify backend error is captured for SSLLoadingCerts
  13445. // This error occurs when loading CA certificates fails
  13446. EXPECT_NE(0UL, res.ssl_backend_error());
  13447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13448. // OpenSSL specific error codes:
  13449. // > openssl errstr 0x80000002
  13450. // error:80000002:system library::No such file or directory
  13451. // > openssl errstr 0xA000126
  13452. // error:0A000126:SSL routines::unexpected eof while reading
  13453. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13454. res.ssl_backend_error() == 0xA000126);
  13455. #endif
  13456. }
  13457. TEST(SSLClientTest, ServerCertificateVerification4) {
  13458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. ASSERT_TRUE(svr.is_valid());
  13460. svr.Get("/test", [&](const Request &, Response &res) {
  13461. res.set_content("test", "text/plain");
  13462. svr.stop();
  13463. ASSERT_TRUE(true);
  13464. });
  13465. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13466. auto se = detail::scope_exit([&] {
  13467. t.join();
  13468. ASSERT_FALSE(svr.is_running());
  13469. });
  13470. svr.wait_until_ready();
  13471. SSLClient cli("127.0.0.1", PORT);
  13472. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13473. cli.enable_server_certificate_verification(true);
  13474. cli.set_connection_timeout(30);
  13475. auto res = cli.Get("/test");
  13476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13477. ASSERT_EQ(StatusCode::OK_200, res->status);
  13478. }
  13479. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13480. std::string cert;
  13481. read_file(CA_CERT_FILE, cert);
  13482. SSLClient cli("google.com");
  13483. cli.load_ca_cert_store(cert.data(), cert.size());
  13484. const auto res = cli.Get("/");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13487. }
  13488. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13489. // clang-format off
  13490. static constexpr char cert[] =
  13491. "GlobalSign Root CA\n"
  13492. "==================\n"
  13493. "-----BEGIN CERTIFICATE-----\n"
  13494. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13495. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13496. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13497. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13498. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13499. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13500. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13501. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13502. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13503. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13504. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13505. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13506. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13507. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13508. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13509. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13510. "-----END CERTIFICATE-----\n";
  13511. // clang-format on
  13512. SSLClient cli("google.com");
  13513. cli.load_ca_cert_store(cert, sizeof(cert));
  13514. const auto res = cli.Get("/");
  13515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13516. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13517. }
  13518. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13519. SSLClient cli("www.youtube.com");
  13520. cli.set_ca_cert_path(CA_CERT_FILE);
  13521. cli.enable_server_certificate_verification(true);
  13522. cli.set_follow_location(true);
  13523. auto res = cli.Get("/");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. ASSERT_EQ(StatusCode::OK_200, res->status);
  13526. }
  13527. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13528. SSLClient cli("wWw.YouTube.Com");
  13529. cli.set_ca_cert_path(CA_CERT_FILE);
  13530. cli.enable_server_certificate_verification(true);
  13531. cli.enable_server_hostname_verification(true);
  13532. cli.set_follow_location(true);
  13533. auto res = cli.Get("/");
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. ASSERT_EQ(StatusCode::OK_200, res->status);
  13536. }
  13537. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13538. SSLClient cli("gOoGlE.COm");
  13539. cli.enable_server_certificate_verification(true);
  13540. cli.enable_server_hostname_verification(true);
  13541. cli.set_follow_location(true);
  13542. auto res = cli.Get("/");
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. ASSERT_EQ(StatusCode::OK_200, res->status);
  13545. }
  13546. TEST(SSLClientTest, Issue2004_Online) {
  13547. Client client("https://google.com");
  13548. client.set_follow_location(true);
  13549. auto res = client.Get("/");
  13550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13551. ASSERT_EQ(StatusCode::OK_200, res->status);
  13552. auto body = res->body;
  13553. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13554. }
  13555. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13556. // Create SSLClient with invalid cert/key to make is_valid() return false
  13557. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13558. "nonexistent_key.pem");
  13559. // is_valid() should be false due to cert loading failure
  13560. ASSERT_FALSE(cli.is_valid());
  13561. auto res = cli.Get("/");
  13562. ASSERT_FALSE(res);
  13563. EXPECT_EQ(Error::SSLConnection, res.error());
  13564. }
  13565. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13566. // Test for Issue #2251: SSL error not properly reported when client cert
  13567. // and key paths are swapped or mismatched
  13568. // This simulates the scenario where user accidentally swaps the cert and key
  13569. // files
  13570. // Using client cert file as private key and vice versa (completely wrong)
  13571. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13572. // Should fail validation due to cert/key mismatch
  13573. ASSERT_FALSE(cli.is_valid());
  13574. // Attempt to make a request should fail with proper error
  13575. auto res = cli.Get("/");
  13576. ASSERT_FALSE(res);
  13577. EXPECT_EQ(Error::SSLConnection, res.error());
  13578. // SSL error should be recorded in the Result object (this is the key fix for
  13579. // Issue #2251)
  13580. auto backend_error = res.ssl_backend_error();
  13581. EXPECT_NE(0u, backend_error);
  13582. }
  13583. // Tests cert/key mismatch detection at the TLS context level
  13584. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13585. // Test that using mismatched cert/key causes connection failure.
  13586. // We verify this at the SSLClient level rather than through internal
  13587. // TLS API functions.
  13588. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13589. cli.enable_server_certificate_verification(false);
  13590. cli.set_connection_timeout(2);
  13591. // The mismatch should cause a connection or handshake error
  13592. auto res = cli.Get("/test");
  13593. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13594. // Either way, the request should fail
  13595. EXPECT_FALSE(res);
  13596. }
  13597. #endif
  13598. #if 0
  13599. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13600. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13601. ASSERT_TRUE(cli != nullptr);
  13602. cli->set_address_family(AF_INET6);
  13603. cli->set_interface("en0");
  13604. auto res = cli->Get("/get");
  13605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13606. ASSERT_EQ(StatusCode::OK_200, res->status);
  13607. }
  13608. #endif
  13609. // Client certificate tests - work with all TLS backends
  13610. #ifdef CPPHTTPLIB_SSL_ENABLED
  13611. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13612. void ClientCertPresent(
  13613. const std::string &client_cert_file,
  13614. const std::string &client_private_key_file,
  13615. const std::string &client_encrypted_private_key_pass = std::string(),
  13616. const ClientCertServerSetup &setup = nullptr) {
  13617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13618. ASSERT_TRUE(svr.is_valid());
  13619. if (setup) { setup(svr); }
  13620. svr.Get("/test", [&](const Request &req, Response &res) {
  13621. res.set_content("test", "text/plain");
  13622. auto cert = req.peer_cert();
  13623. ASSERT_TRUE(static_cast<bool>(cert));
  13624. std::string common_name = cert.subject_cn();
  13625. EXPECT_EQ("Common Name", common_name);
  13626. });
  13627. auto port = svr.bind_to_any_port(HOST);
  13628. ASSERT_LT(0, port);
  13629. thread t = thread([&]() { svr.listen_after_bind(); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. t.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13637. client_encrypted_private_key_pass);
  13638. cli.enable_server_certificate_verification(false);
  13639. cli.set_connection_timeout(30);
  13640. auto res = cli.Get("/test");
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. ASSERT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(SSLClientServerTest, ClientCertPresent) {
  13645. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13646. }
  13647. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13648. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13649. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13650. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13651. }
  13652. // Expects svr, which must require client certificates, to reject a client
  13653. // that has none
  13654. void RejectsClientWithoutCert(SSLServer &svr) {
  13655. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13656. auto port = svr.bind_to_any_port(HOST);
  13657. ASSERT_LT(0, port);
  13658. thread t = thread([&]() { svr.listen_after_bind(); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. t.join();
  13662. ASSERT_FALSE(svr.is_running());
  13663. });
  13664. svr.wait_until_ready();
  13665. SSLClient cli(HOST, port);
  13666. cli.set_connection_timeout(30);
  13667. // Skip the server certificate check, so that the request fails because the
  13668. // client certificate is missing rather than because cert.pem is not trusted
  13669. cli.enable_server_certificate_verification(false);
  13670. auto res = cli.Get("/test");
  13671. ASSERT_FALSE(res);
  13672. // The server rejects the client during the handshake, or on TLS 1.3 right
  13673. // after it, which the client notices on its first write or read
  13674. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13675. res.error() == Error::Write || res.error() == Error::Read)
  13676. << to_string(res.error());
  13677. if (res.error() == Error::SSLConnection) {
  13678. EXPECT_NE(0UL, res.ssl_backend_error());
  13679. }
  13680. // A rejection noticed on the write keeps the TLS error the write hit
  13681. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13682. }
  13683. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13685. ASSERT_TRUE(svr.is_valid());
  13686. if (setup) { setup(svr); }
  13687. RejectsClientWithoutCert(svr);
  13688. }
  13689. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13690. // A server that requires client certificates must keep requiring them after
  13691. // setup changes it, and keep accepting a client that has one
  13692. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13693. ClientCertMissing(setup);
  13694. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13695. setup);
  13696. }
  13697. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13698. ClientCertStillRequired([](SSLServer &svr) {
  13699. ASSERT_TRUE(tls::set_verify_callback(
  13700. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13701. });
  13702. }
  13703. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13704. ClientCertStillRequired([](SSLServer &svr) {
  13705. ASSERT_TRUE(tls::set_verify_callback(
  13706. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13707. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13708. });
  13709. }
  13710. // The client verifies the server certificate during the handshake, so a
  13711. // server that fails the check never gets the client certificate, even when a
  13712. // verifier of the client's own accepts it
  13713. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13714. struct Case {
  13715. const char *trusted_ca;
  13716. const char *host;
  13717. Error error;
  13718. };
  13719. // cert2.pem names localhost: the first client does not trust it, and the
  13720. // second trusts it but asks for another name
  13721. for (const auto &c :
  13722. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13723. Case{SERVER_CERT2_FILE, "example.com",
  13724. Error::SSLServerHostnameVerification}}) {
  13725. for (auto with_verifier : {false, true}) {
  13726. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13727. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13728. CLIENT_CA_CERT_FILE);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. std::atomic<bool> got_client_cert{false};
  13731. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13732. [&](const tls::VerifyContext &) {
  13733. got_client_cert = true;
  13734. return true;
  13735. }));
  13736. auto port = svr.bind_to_any_port("127.0.0.1");
  13737. ASSERT_LT(0, port);
  13738. thread t = thread([&] { svr.listen_after_bind(); });
  13739. svr.wait_until_ready();
  13740. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13741. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13742. cli.set_ca_cert_path(c.trusted_ca);
  13743. if (with_verifier) {
  13744. cli.set_server_certificate_verifier(
  13745. [](const tls::VerifyContext &) { return true; });
  13746. }
  13747. auto res = cli.Get("/");
  13748. EXPECT_FALSE(res);
  13749. EXPECT_EQ(c.error, res.error());
  13750. svr.stop();
  13751. t.join();
  13752. EXPECT_FALSE(got_client_cert);
  13753. }
  13754. }
  13755. }
  13756. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13757. std::string cert_pem, key_pem, ca_pem;
  13758. read_file(SERVER_CERT_FILE, cert_pem);
  13759. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13760. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13761. ASSERT_TRUE(
  13762. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13763. }
  13764. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13766. ASSERT_TRUE(svr.is_valid());
  13767. UpdateCertsPemWithClientCA(svr);
  13768. RejectsClientWithoutCert(svr);
  13769. }
  13770. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13771. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13772. }
  13773. // A TLS error from one request must not show up in a later request's Result
  13774. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13776. ASSERT_TRUE(svr.is_valid());
  13777. svr.Get("/test", [](const Request &, Response &res) {
  13778. res.set_content("test", "text/plain");
  13779. });
  13780. auto port = svr.bind_to_any_port(HOST);
  13781. ASSERT_LT(0, port);
  13782. thread t = thread([&]() { svr.listen_after_bind(); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. ASSERT_FALSE(svr.is_running());
  13787. });
  13788. svr.wait_until_ready();
  13789. SSLClient cli(HOST, port);
  13790. cli.set_connection_timeout(30);
  13791. cli.enable_server_hostname_verification(false);
  13792. // cert.pem is not trusted, so the handshake fails
  13793. ASSERT_FALSE(cli.Get("/test"));
  13794. cli.enable_server_certificate_verification(false);
  13795. auto res = cli.Get("/test");
  13796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13797. EXPECT_EQ(0, res.ssl_error());
  13798. EXPECT_EQ(0UL, res.ssl_backend_error());
  13799. }
  13800. // PEM memory-based constructor tests (works with all TLS backends).
  13801. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13802. // terminator after it.
  13803. void PemMemoryClientCertPresent(
  13804. const std::string &client_cert_file,
  13805. const std::string &client_private_key_file,
  13806. const std::string &client_encrypted_private_key_pass = std::string(),
  13807. bool exact_size = false) {
  13808. // Read PEM files into memory
  13809. std::string server_cert_pem, server_key_pem;
  13810. std::string client_ca_pem;
  13811. std::string client_cert_pem, client_key_pem;
  13812. read_file(SERVER_CERT_FILE, server_cert_pem);
  13813. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13814. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13815. read_file(client_cert_file, client_cert_pem);
  13816. read_file(client_private_key_file, client_key_pem);
  13817. std::list<std::vector<char>> exact_copies;
  13818. auto data = [&](const std::string &pem) -> const char * {
  13819. if (!exact_size) { return pem.c_str(); }
  13820. exact_copies.emplace_back(pem.begin(), pem.end());
  13821. return exact_copies.back().data();
  13822. };
  13823. // Create server with PEM memory
  13824. SSLServer::PemMemory server_pem = {
  13825. data(server_cert_pem),
  13826. server_cert_pem.size(),
  13827. data(server_key_pem),
  13828. server_key_pem.size(),
  13829. data(client_ca_pem),
  13830. client_ca_pem.size(),
  13831. nullptr // no password for server key
  13832. };
  13833. SSLServer svr(server_pem);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. svr.Get("/test", [&](const Request &req, Response &res) {
  13836. res.set_content("test", "text/plain");
  13837. auto cert = req.peer_cert();
  13838. ASSERT_TRUE(static_cast<bool>(cert));
  13839. EXPECT_EQ("Common Name", cert.subject_cn());
  13840. });
  13841. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13842. auto se = detail::scope_exit([&] {
  13843. svr.stop();
  13844. t.join();
  13845. ASSERT_FALSE(svr.is_running());
  13846. });
  13847. svr.wait_until_ready();
  13848. // Create client with PEM memory
  13849. const char *password = client_encrypted_private_key_pass.empty()
  13850. ? nullptr
  13851. : client_encrypted_private_key_pass.c_str();
  13852. SSLClient::PemMemory client_pem = {
  13853. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13854. client_key_pem.size(), password};
  13855. SSLClient cli(HOST, PORT, client_pem);
  13856. cli.enable_server_certificate_verification(false);
  13857. cli.set_connection_timeout(30);
  13858. auto res = cli.Get("/test");
  13859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13860. ASSERT_EQ(StatusCode::OK_200, res->status);
  13861. }
  13862. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13863. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13864. }
  13865. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13866. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13867. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13868. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13869. }
  13870. // A server built from PEM memory with a client CA requires client certificates,
  13871. // also when the CA is a NUL-terminated string passed with a length of 0
  13872. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13873. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13874. read_file(SERVER_CERT_FILE, server_cert_pem);
  13875. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13876. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13877. SSLServer::PemMemory server_pem = {
  13878. server_cert_pem.c_str(),
  13879. server_cert_pem.size(),
  13880. server_key_pem.c_str(),
  13881. server_key_pem.size(),
  13882. client_ca_pem.c_str(),
  13883. client_ca_pem.size(),
  13884. nullptr // no password for server key
  13885. };
  13886. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13887. SCOPED_TRACE(client_ca_pem_len);
  13888. server_pem.client_ca_pem_len = client_ca_pem_len;
  13889. SSLServer svr(server_pem);
  13890. ASSERT_TRUE(svr.is_valid());
  13891. RejectsClientWithoutCert(svr);
  13892. }
  13893. // An empty CA fails to load instead of turning the check off
  13894. server_pem.client_ca_pem = "";
  13895. server_pem.client_ca_pem_len = 0;
  13896. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13897. }
  13898. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13899. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13900. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13901. true);
  13902. }
  13903. // A length shorter than the PEM cuts it short, so it no longer loads
  13904. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13905. std::string cert, key;
  13906. read_file(SERVER_CERT_FILE, cert);
  13907. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13908. for (auto cut_cert : {true, false}) {
  13909. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13910. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13911. SSLServer::PemMemory server_pem = {
  13912. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13913. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13914. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13915. key_len, nullptr};
  13916. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13917. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13918. key.c_str(), key_len, nullptr};
  13919. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13920. }
  13921. }
  13922. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13923. class NoListenSSLServer : public SSLServer {
  13924. public:
  13925. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13926. const char *client_ca_cert_file_path,
  13927. const char *client_ca_cert_dir_path = nullptr)
  13928. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13929. client_ca_cert_dir_path),
  13930. stop_(false) {}
  13931. std::atomic_bool stop_;
  13932. private:
  13933. bool process_and_close_socket(socket_t /*sock*/) override {
  13934. // Don't create SSL context
  13935. while (!stop_.load()) {
  13936. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13937. }
  13938. return true;
  13939. }
  13940. };
  13941. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13942. CLIENT_CA_CERT_FILE);
  13943. ASSERT_TRUE(svr.is_valid());
  13944. svr.Get("/test", [&](const Request &, Response &res) {
  13945. res.set_content("test", "text/plain");
  13946. });
  13947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop_ = true;
  13950. svr.stop();
  13951. t.join();
  13952. ASSERT_FALSE(svr.is_running());
  13953. });
  13954. svr.wait_until_ready();
  13955. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13956. cli.enable_server_certificate_verification(false);
  13957. cli.set_connection_timeout(1);
  13958. auto res = cli.Get("/test");
  13959. ASSERT_TRUE(!res);
  13960. EXPECT_EQ(Error::SSLConnection, res.error());
  13961. // Timeout results in WantRead error code (maps to backend-specific value)
  13962. EXPECT_NE(0, res.ssl_error());
  13963. }
  13964. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13965. // Test SSLServer with client certificate verification using the standard
  13966. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13968. CLIENT_CA_CERT_DIR);
  13969. ASSERT_TRUE(svr.is_valid());
  13970. svr.Get("/test", [&](const Request &req, Response &res) {
  13971. res.set_content("test", "text/plain");
  13972. auto cert = req.peer_cert();
  13973. ASSERT_TRUE(static_cast<bool>(cert));
  13974. auto common_name = cert.subject_cn();
  13975. EXPECT_EQ("Common Name", common_name);
  13976. });
  13977. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13978. auto se = detail::scope_exit([&] {
  13979. svr.stop();
  13980. t.join();
  13981. ASSERT_FALSE(svr.is_running());
  13982. });
  13983. svr.wait_until_ready();
  13984. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13985. cli.enable_server_certificate_verification(false);
  13986. cli.set_connection_timeout(30);
  13987. auto res = cli.Get("/test");
  13988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13989. ASSERT_EQ(StatusCode::OK_200, res->status);
  13990. }
  13991. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13992. // Verifies that wildcard matching and exact matching work consistently
  13993. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13994. using namespace httplib::tls;
  13995. // We need a running server to test against
  13996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. svr.Get("/test", [](const Request &, Response &res) {
  13999. res.set_content("ok", "text/plain");
  14000. });
  14001. thread t([&]() { svr.listen(HOST, PORT); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. });
  14006. svr.wait_until_ready();
  14007. bool verify_callback_called = false;
  14008. bool verify_result_wrong = false;
  14009. SSLClient cli(HOST, PORT);
  14010. cli.enable_server_certificate_verification(true);
  14011. cli.set_ca_cert_path(CA_CERT_FILE);
  14012. cli.set_connection_timeout(5);
  14013. // Note: Test certificate has CN="Common Name", not "localhost"
  14014. bool verify_result_cn = false;
  14015. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14016. verify_callback_called = true;
  14017. if (!ctx.cert) return false;
  14018. // Test 1: "Common Name" should match (our test server cert CN)
  14019. verify_result_cn = ctx.check_hostname("Common Name");
  14020. // Test 2: wrong hostname should not match
  14021. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14022. return true; // Accept for the purpose of this test
  14023. });
  14024. auto res = cli.Get("/test");
  14025. // The request may succeed or fail depending on cert configuration
  14026. // but the callback should have been called
  14027. ASSERT_TRUE(verify_callback_called)
  14028. << "Verify callback should have been called";
  14029. // CN="Common Name" should match our test certificate
  14030. //
  14031. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14032. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14033. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14034. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14035. // <openssl/base.h>, which is included transitively when
  14036. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14037. #if defined(OPENSSL_IS_BORINGSSL)
  14038. EXPECT_FALSE(verify_result_cn)
  14039. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14040. #else
  14041. EXPECT_TRUE(verify_result_cn)
  14042. << "verify_hostname should match 'Common Name' (certificate CN)";
  14043. #endif
  14044. // Wrong hostname should not match
  14045. EXPECT_FALSE(verify_result_wrong)
  14046. << "verify_hostname should not match 'wronghost.example.com'";
  14047. }
  14048. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14049. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14050. // X509_check_ip behavior and must hold for every backend.
  14051. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14052. using namespace httplib::tls;
  14053. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14054. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14055. ASSERT_TRUE(svr.is_valid());
  14056. svr.Get("/test", [](const Request &, Response &res) {
  14057. res.set_content("ok", "text/plain");
  14058. });
  14059. thread t([&]() { svr.listen(HOST, PORT); });
  14060. auto se = detail::scope_exit([&] {
  14061. svr.stop();
  14062. t.join();
  14063. });
  14064. svr.wait_until_ready();
  14065. bool verify_callback_called = false;
  14066. bool ip_matched_via_cn = true;
  14067. SSLClient cli(HOST, PORT);
  14068. cli.enable_server_certificate_verification(true);
  14069. cli.set_ca_cert_path(CA_CERT_FILE);
  14070. cli.set_connection_timeout(5);
  14071. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14072. verify_callback_called = true;
  14073. if (!ctx.cert) return false;
  14074. // The IP appears only in the CN, so it must NOT be accepted.
  14075. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14076. return true; // Accept for the purpose of this test
  14077. });
  14078. cli.Get("/test");
  14079. ASSERT_TRUE(verify_callback_called)
  14080. << "Verify callback should have been called";
  14081. EXPECT_FALSE(ip_matched_via_cn)
  14082. << "An IP host must not be authenticated via the certificate CN";
  14083. }
  14084. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14085. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14086. using namespace httplib::tls;
  14087. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14088. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14089. ASSERT_TRUE(svr.is_valid());
  14090. svr.Get("/test", [](const Request &, Response &res) {
  14091. res.set_content("ok", "text/plain");
  14092. });
  14093. thread t([&]() { svr.listen(HOST, PORT); });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. t.join();
  14097. });
  14098. svr.wait_until_ready();
  14099. bool verify_callback_called = false;
  14100. bool san_matched = false;
  14101. bool wrong_ipv6_matched = true;
  14102. bool cn_ipv6_matched = true;
  14103. SSLClient cli(HOST, PORT);
  14104. cli.enable_server_certificate_verification(true);
  14105. cli.set_ca_cert_path(CA_CERT_FILE);
  14106. cli.set_connection_timeout(5);
  14107. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14108. verify_callback_called = true;
  14109. if (!ctx.cert) return false;
  14110. // Matches the IPv6 iPAddress SAN.
  14111. san_matched = ctx.check_hostname("2001:db8::1");
  14112. // A different IPv6 address must not match.
  14113. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14114. // "::1" lives only in the CN, so it must not be accepted.
  14115. cn_ipv6_matched = ctx.check_hostname("::1");
  14116. return true; // Accept for the purpose of this test
  14117. });
  14118. cli.Get("/test");
  14119. ASSERT_TRUE(verify_callback_called)
  14120. << "Verify callback should have been called";
  14121. EXPECT_TRUE(san_matched)
  14122. << "verify_hostname should match an IPv6 iPAddress SAN";
  14123. EXPECT_FALSE(wrong_ipv6_matched)
  14124. << "verify_hostname should not match a non-matching IPv6 address";
  14125. EXPECT_FALSE(cn_ipv6_matched)
  14126. << "An IPv6 host must not be authenticated via the certificate CN";
  14127. }
  14128. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14129. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14130. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14131. using namespace httplib::tls;
  14132. // SANs: DNS:a.zz, IP:42.46.122.122
  14133. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14134. ASSERT_TRUE(svr.is_valid());
  14135. svr.Get("/test", [](const Request &, Response &res) {
  14136. res.set_content("ok", "text/plain");
  14137. });
  14138. auto port = svr.bind_to_any_port(HOST);
  14139. thread t([&]() { svr.listen_after_bind(); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. });
  14144. svr.wait_until_ready();
  14145. bool verify_callback_called = false;
  14146. bool dns_san_matched = false;
  14147. bool ip_san_matched = false;
  14148. bool ip_matched_via_dns_san = true;
  14149. bool dns_matched_via_ip_san = true;
  14150. bool cn_matched_next_to_dns_san = true;
  14151. SSLClient cli(HOST, port);
  14152. cli.enable_server_certificate_verification(true);
  14153. cli.set_ca_cert_path(CA_CERT_FILE);
  14154. cli.set_connection_timeout(5);
  14155. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14156. verify_callback_called = true;
  14157. if (!ctx.cert) return false;
  14158. dns_san_matched = ctx.check_hostname("a.zz");
  14159. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14160. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14161. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14162. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14163. return true; // Accept for the purpose of this test
  14164. });
  14165. cli.Get("/test");
  14166. ASSERT_TRUE(verify_callback_called)
  14167. << "Verify callback should have been called";
  14168. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14169. EXPECT_TRUE(ip_san_matched)
  14170. << "verify_hostname should match an iPAddress SAN";
  14171. EXPECT_FALSE(ip_matched_via_dns_san)
  14172. << "An IP host must not be authenticated via a dNSName SAN";
  14173. EXPECT_FALSE(dns_matched_via_ip_san)
  14174. << "A DNS host must not be authenticated via an iPAddress SAN";
  14175. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14176. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14177. }
  14178. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14179. // "www.*.example.test" names one host and not every host under example.test.
  14180. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14181. using namespace httplib::tls;
  14182. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14183. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14184. ASSERT_TRUE(svr.is_valid());
  14185. svr.Get("/test", [](const Request &, Response &res) {
  14186. res.set_content("ok", "text/plain");
  14187. });
  14188. auto port = svr.bind_to_any_port(HOST);
  14189. thread t([&]() { svr.listen_after_bind(); });
  14190. auto se = detail::scope_exit([&] {
  14191. svr.stop();
  14192. t.join();
  14193. });
  14194. svr.wait_until_ready();
  14195. bool verify_callback_called = false;
  14196. bool leftmost_wildcard_matched = false;
  14197. bool wildcard_spanned_labels = true;
  14198. bool inner_wildcard_matched = true;
  14199. SSLClient cli(HOST, port);
  14200. cli.enable_server_certificate_verification(true);
  14201. cli.set_ca_cert_path(CA_CERT_FILE);
  14202. cli.set_connection_timeout(5);
  14203. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14204. verify_callback_called = true;
  14205. if (!ctx.cert) return false;
  14206. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14207. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14208. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14209. return true; // Accept for the purpose of this test
  14210. });
  14211. cli.Get("/test");
  14212. ASSERT_TRUE(verify_callback_called)
  14213. << "Verify callback should have been called";
  14214. EXPECT_TRUE(leftmost_wildcard_matched)
  14215. << "A leftmost wildcard should match a single label";
  14216. EXPECT_FALSE(wildcard_spanned_labels)
  14217. << "A wildcard label must not match more than one label";
  14218. EXPECT_FALSE(inner_wildcard_matched)
  14219. << "A wildcard outside the leftmost label must not be honoured";
  14220. }
  14221. // sans() must report each SAN entry under its own type.
  14222. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14223. using namespace httplib::tls;
  14224. // SANs: DNS:a.zz, IP:42.46.122.122
  14225. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14226. ASSERT_TRUE(svr.is_valid());
  14227. svr.Get("/test", [](const Request &, Response &res) {
  14228. res.set_content("ok", "text/plain");
  14229. });
  14230. auto port = svr.bind_to_any_port(HOST);
  14231. thread t([&]() { svr.listen_after_bind(); });
  14232. auto se = detail::scope_exit([&] {
  14233. svr.stop();
  14234. t.join();
  14235. });
  14236. svr.wait_until_ready();
  14237. bool verify_callback_called = false;
  14238. std::vector<SanEntry> sans;
  14239. SSLClient cli(HOST, port);
  14240. cli.enable_server_certificate_verification(true);
  14241. cli.set_ca_cert_path(CA_CERT_FILE);
  14242. cli.set_connection_timeout(5);
  14243. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14244. verify_callback_called = true;
  14245. if (!ctx.cert) return false;
  14246. sans = ctx.sans();
  14247. return true; // Accept for the purpose of this test
  14248. });
  14249. cli.Get("/test");
  14250. ASSERT_TRUE(verify_callback_called)
  14251. << "Verify callback should have been called";
  14252. auto has_san = [&](SanType type, const std::string &value) {
  14253. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14254. return san.type == type && san.value == value;
  14255. });
  14256. };
  14257. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14258. << "sans() should report the dNSName SAN";
  14259. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14260. << "sans() should report the iPAddress SAN";
  14261. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14262. << "sans() must not report the dNSName SAN as an address";
  14263. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14264. << "sans() must not report the iPAddress SAN as a DNS name";
  14265. }
  14266. #endif
  14267. // mbedTLS-specific callback constructor test
  14268. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14269. #ifdef CPPHTTPLIB_SSL_ENABLED
  14270. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14272. ASSERT_TRUE(svr.is_valid());
  14273. // Set up a handler to verify client certificate is present
  14274. bool client_cert_verified = false;
  14275. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14276. // Verify that client certificate was provided
  14277. client_cert_verified = true;
  14278. res.set_content("success", "text/plain");
  14279. });
  14280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14281. auto se = detail::scope_exit([&] {
  14282. svr.stop();
  14283. t.join();
  14284. ASSERT_FALSE(svr.is_running());
  14285. });
  14286. svr.wait_until_ready();
  14287. // Client with certificate
  14288. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14289. cli.enable_server_certificate_verification(false);
  14290. cli.set_connection_timeout(30);
  14291. auto res = cli.Get("/test");
  14292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14293. ASSERT_EQ(StatusCode::OK_200, res->status);
  14294. ASSERT_TRUE(client_cert_verified);
  14295. EXPECT_EQ("success", res->body);
  14296. }
  14297. #endif
  14298. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14299. // backends
  14300. #ifdef CPPHTTPLIB_SSL_ENABLED
  14301. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14302. using namespace httplib::tls;
  14303. // Test that when client CA cert file is provided,
  14304. // the server properly requests and validates client certificates
  14305. // Create a server with client authentication
  14306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. bool handler_called = false;
  14309. svr.Get("/test", [&](const Request &req, Response &res) {
  14310. handler_called = true;
  14311. // Verify that a client certificate was provided
  14312. auto cert = req.peer_cert();
  14313. ASSERT_TRUE(static_cast<bool>(cert));
  14314. // Get the issuer name
  14315. std::string issuer_str = cert.issuer_name();
  14316. ASSERT_FALSE(issuer_str.empty());
  14317. // The client certificate should be issued by our test CA
  14318. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14319. res.set_content("authenticated", "text/plain");
  14320. });
  14321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14322. auto se = detail::scope_exit([&] {
  14323. svr.stop();
  14324. t.join();
  14325. ASSERT_FALSE(svr.is_running());
  14326. });
  14327. svr.wait_until_ready();
  14328. // Connect with a client certificate issued by the CA
  14329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14330. cli.enable_server_certificate_verification(false);
  14331. cli.set_connection_timeout(30);
  14332. auto res = cli.Get("/test");
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. ASSERT_EQ(StatusCode::OK_200, res->status);
  14335. ASSERT_TRUE(handler_called);
  14336. EXPECT_EQ("authenticated", res->body);
  14337. }
  14338. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14339. using namespace httplib::tls;
  14340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14341. ASSERT_TRUE(svr.is_valid());
  14342. svr.Get("/test", [](const Request &, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. });
  14350. svr.wait_until_ready();
  14351. SSLClient cli(HOST, PORT);
  14352. cli.enable_server_certificate_verification(false);
  14353. cli.set_connection_timeout(30);
  14354. bool cert_checked = false;
  14355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14356. if (ctx.cert) {
  14357. auto sans = ctx.sans();
  14358. // Test certificate may or may not have SANs - just verify the API
  14359. // works If SANs exist, verify the types are valid
  14360. for (const auto &san : sans) {
  14361. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14362. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14363. san.type == SanType::OTHER);
  14364. EXPECT_FALSE(san.value.empty());
  14365. }
  14366. cert_checked = true;
  14367. }
  14368. return true;
  14369. });
  14370. auto res = cli.Get("/test");
  14371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14372. EXPECT_TRUE(cert_checked);
  14373. }
  14374. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14375. using namespace httplib::tls;
  14376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14377. ASSERT_TRUE(svr.is_valid());
  14378. svr.Get("/test", [](const Request &, Response &res) {
  14379. res.set_content("ok", "text/plain");
  14380. });
  14381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14382. auto se = detail::scope_exit([&] {
  14383. svr.stop();
  14384. t.join();
  14385. });
  14386. svr.wait_until_ready();
  14387. SSLClient cli(HOST, PORT);
  14388. cli.enable_server_certificate_verification(false);
  14389. cli.set_connection_timeout(30);
  14390. bool validity_checked = false;
  14391. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14392. if (ctx.cert) {
  14393. time_t not_before = 0, not_after = 0;
  14394. bool result = ctx.validity(not_before, not_after);
  14395. EXPECT_TRUE(result);
  14396. // Verify that not_before < now < not_after for a valid cert
  14397. time_t now = time(nullptr);
  14398. EXPECT_LT(not_before, now);
  14399. EXPECT_GT(not_after, now);
  14400. validity_checked = true;
  14401. }
  14402. return true;
  14403. });
  14404. auto res = cli.Get("/test");
  14405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14406. EXPECT_TRUE(validity_checked);
  14407. }
  14408. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14409. using namespace httplib::tls;
  14410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14411. ASSERT_TRUE(svr.is_valid());
  14412. svr.Get("/test", [](const Request &, Response &res) {
  14413. res.set_content("ok", "text/plain");
  14414. });
  14415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. });
  14420. svr.wait_until_ready();
  14421. SSLClient cli(HOST, PORT);
  14422. cli.enable_server_certificate_verification(false);
  14423. cli.set_connection_timeout(30);
  14424. bool serial_checked = false;
  14425. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14426. if (ctx.cert) {
  14427. std::string serial = ctx.serial();
  14428. EXPECT_FALSE(serial.empty());
  14429. // Serial should be a hex string
  14430. for (char c : serial) {
  14431. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14432. (c >= 'a' && c <= 'f'));
  14433. }
  14434. serial_checked = true;
  14435. }
  14436. return true;
  14437. });
  14438. auto res = cli.Get("/test");
  14439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14440. EXPECT_TRUE(serial_checked);
  14441. }
  14442. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14443. // Test 1: Valid CA file - no error should be recorded
  14444. {
  14445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14446. CLIENT_CA_CERT_FILE);
  14447. ASSERT_TRUE(svr.is_valid());
  14448. // With valid setup, last_ssl_error should be 0
  14449. EXPECT_EQ(0, svr.ssl_last_error());
  14450. }
  14451. // Test 2: Invalid CA file content
  14452. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14453. {
  14454. // Create a temporary file with completely invalid content
  14455. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14456. {
  14457. std::ofstream ofs(temp_invalid_ca);
  14458. ofs << "This is not a certificate file at all\n";
  14459. ofs << "Just plain text content\n";
  14460. }
  14461. // Create server with invalid CA file
  14462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14463. // Clean up temporary file
  14464. std::remove(temp_invalid_ca);
  14465. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14466. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14467. // Note: SSL_CTX_load_verify_locations typically fails first,
  14468. // but our error handling code path is still exercised
  14469. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14470. }
  14471. }
  14472. TEST(VerifyCallbackTest, VerifyContextFields) {
  14473. using namespace httplib::tls;
  14474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14475. ASSERT_TRUE(svr.is_valid());
  14476. svr.Get("/test", [](const Request &, Response &res) {
  14477. res.set_content("ok", "text/plain");
  14478. });
  14479. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14480. auto se = detail::scope_exit([&] {
  14481. svr.stop();
  14482. t.join();
  14483. });
  14484. svr.wait_until_ready();
  14485. SSLClient cli(HOST, PORT);
  14486. cli.enable_server_certificate_verification(false);
  14487. cli.set_connection_timeout(30);
  14488. int callback_count = 0;
  14489. bool saw_leaf_cert = false;
  14490. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14491. if (ctx.cert) {
  14492. callback_count++;
  14493. // We should see at least one certificate (the leaf)
  14494. std::string cn = ctx.subject_cn();
  14495. if (!cn.empty()) { saw_leaf_cert = true; }
  14496. // Verify context fields are populated
  14497. EXPECT_NE(ctx.session, nullptr);
  14498. EXPECT_GE(ctx.depth, 0);
  14499. }
  14500. return true;
  14501. });
  14502. auto res = cli.Get("/test");
  14503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14504. EXPECT_GT(callback_count, 0);
  14505. EXPECT_TRUE(saw_leaf_cert);
  14506. }
  14507. // A verifier that accepts runs alongside the built-in verification, and is the
  14508. // only check once that is turned off.
  14509. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14510. using namespace httplib::tls;
  14511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14512. ASSERT_TRUE(svr.is_valid());
  14513. svr.Get("/test", [](const Request &, Response &res) {
  14514. res.set_content("ok", "text/plain");
  14515. });
  14516. auto port = svr.bind_to_any_port(HOST);
  14517. thread t([&]() { svr.listen_after_bind(); });
  14518. auto se = detail::scope_exit([&] {
  14519. svr.stop();
  14520. t.join();
  14521. });
  14522. svr.wait_until_ready();
  14523. SSLClient cli(HOST, port);
  14524. cli.enable_server_hostname_verification(false);
  14525. auto calls = 0;
  14526. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14527. calls++;
  14528. return true;
  14529. });
  14530. // cert.pem is not trusted
  14531. auto res = cli.Get("/test");
  14532. ASSERT_FALSE(res);
  14533. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14534. EXPECT_GT(calls, 0);
  14535. cli.enable_server_certificate_verification(false);
  14536. res = cli.Get("/test");
  14537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14538. EXPECT_EQ("ok", res->body);
  14539. }
  14540. // A verifier belongs to the client that set it, not to the thread that set it.
  14541. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14542. using namespace httplib::tls;
  14543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14544. ASSERT_TRUE(svr.is_valid());
  14545. svr.Get("/test", [](const Request &, Response &res) {
  14546. res.set_content("ok", "text/plain");
  14547. });
  14548. auto port = svr.bind_to_any_port(HOST);
  14549. thread t([&]() { svr.listen_after_bind(); });
  14550. auto se = detail::scope_exit([&] {
  14551. svr.stop();
  14552. t.join();
  14553. });
  14554. svr.wait_until_ready();
  14555. auto rejecting_calls = 0;
  14556. SSLClient rejecting(HOST, port);
  14557. rejecting.enable_server_certificate_verification(false);
  14558. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14559. rejecting_calls++;
  14560. return false;
  14561. });
  14562. auto accepting_calls = 0;
  14563. SSLClient accepting(HOST, port);
  14564. accepting.enable_server_certificate_verification(false);
  14565. // Set on another thread than the requests below.
  14566. thread([&]() {
  14567. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14568. accepting_calls++;
  14569. return true;
  14570. });
  14571. }).join();
  14572. // Requested on another thread than the verifier was set on.
  14573. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14574. EXPECT_GT(rejecting_calls, 0);
  14575. auto res = accepting.Get("/test");
  14576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14577. EXPECT_GT(accepting_calls, 0);
  14578. }
  14579. // A verifier replaced while a handshake runs it lives until it returns.
  14580. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. auto port = svr.bind_to_any_port(HOST);
  14588. thread t([&]() { svr.listen_after_bind(); });
  14589. auto se = detail::scope_exit([&] {
  14590. svr.stop();
  14591. t.join();
  14592. });
  14593. svr.wait_until_ready();
  14594. SSLClient cli(HOST, port);
  14595. cli.enable_server_certificate_verification(false);
  14596. std::promise<void> entered;
  14597. std::promise<void> replaced;
  14598. auto replaced_future = replaced.get_future();
  14599. auto first_call = true;
  14600. // Long enough to live on the heap
  14601. std::string expected(64, 'v');
  14602. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14603. if (first_call) {
  14604. first_call = false;
  14605. entered.set_value();
  14606. replaced_future.wait();
  14607. }
  14608. return expected == std::string(64, 'v');
  14609. });
  14610. thread request([&]() {
  14611. auto res = cli.Get("/test");
  14612. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14613. });
  14614. entered.get_future().wait();
  14615. cli.set_server_certificate_verifier(
  14616. [](const VerifyContext &) { return true; });
  14617. replaced.set_value();
  14618. request.join();
  14619. }
  14620. // VerifyContext::session is the same handle the other tls:: functions take.
  14621. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14622. using namespace httplib::tls;
  14623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14624. ASSERT_TRUE(svr.is_valid());
  14625. svr.Get("/test", [](const Request &, Response &res) {
  14626. res.set_content("ok", "text/plain");
  14627. });
  14628. auto port = svr.bind_to_any_port(HOST);
  14629. thread t([&]() { svr.listen_after_bind(); });
  14630. auto se = detail::scope_exit([&] {
  14631. svr.stop();
  14632. t.join();
  14633. });
  14634. svr.wait_until_ready();
  14635. SSLClient cli(HOST, port);
  14636. cli.enable_server_certificate_verification(false);
  14637. session_t verifier_session = nullptr;
  14638. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14639. verifier_session = ctx.session;
  14640. return true;
  14641. });
  14642. session_t session_verifier_session = nullptr;
  14643. cli.set_session_verifier([&](session_t session) {
  14644. session_verifier_session = session;
  14645. return SSLVerifierResponse::NoDecisionMade;
  14646. });
  14647. auto res = cli.Get("/test");
  14648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14649. EXPECT_NE(nullptr, verifier_session);
  14650. EXPECT_EQ(session_verifier_session, verifier_session);
  14651. }
  14652. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14653. using httplib::tls::TlsError;
  14654. // Test that verify_error_to_string returns empty for success
  14655. std::string success_str = TlsError::verify_error_to_string(0);
  14656. EXPECT_TRUE(success_str.empty());
  14657. // Test that verify_error_to_string returns non-empty for error codes
  14658. // Using a common error code (certificate expired)
  14659. std::string error_str =
  14660. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14661. EXPECT_FALSE(error_str.empty());
  14662. }
  14663. TEST(SessionVerifierTest, CertificateAccepted) {
  14664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14665. ASSERT_TRUE(svr.is_valid());
  14666. svr.Get("/test", [](const Request &, Response &res) {
  14667. res.set_content("ok", "text/plain");
  14668. });
  14669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14670. auto se = detail::scope_exit([&] {
  14671. svr.stop();
  14672. t.join();
  14673. });
  14674. svr.wait_until_ready();
  14675. SSLClient cli(HOST, PORT);
  14676. cli.enable_server_certificate_verification(false);
  14677. cli.set_connection_timeout(30);
  14678. bool callback_called = false;
  14679. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14680. EXPECT_NE(session, nullptr);
  14681. callback_called = true;
  14682. return SSLVerifierResponse::CertificateAccepted;
  14683. });
  14684. auto res = cli.Get("/test");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ(200, res->status);
  14687. EXPECT_TRUE(callback_called);
  14688. }
  14689. TEST(SessionVerifierTest, CertificateRejected) {
  14690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14691. ASSERT_TRUE(svr.is_valid());
  14692. svr.Get("/test", [](const Request &, Response &res) {
  14693. res.set_content("ok", "text/plain");
  14694. });
  14695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14696. auto se = detail::scope_exit([&] {
  14697. svr.stop();
  14698. t.join();
  14699. });
  14700. svr.wait_until_ready();
  14701. SSLClient cli(HOST, PORT);
  14702. cli.enable_server_certificate_verification(false);
  14703. cli.set_connection_timeout(30);
  14704. bool callback_called = false;
  14705. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14706. EXPECT_NE(session, nullptr);
  14707. callback_called = true;
  14708. return SSLVerifierResponse::CertificateRejected;
  14709. });
  14710. auto res = cli.Get("/test");
  14711. EXPECT_FALSE(res);
  14712. EXPECT_TRUE(callback_called);
  14713. }
  14714. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14716. ASSERT_TRUE(svr.is_valid());
  14717. svr.Get("/test", [](const Request &, Response &res) {
  14718. res.set_content("ok", "text/plain");
  14719. });
  14720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14721. auto se = detail::scope_exit([&] {
  14722. svr.stop();
  14723. t.join();
  14724. });
  14725. svr.wait_until_ready();
  14726. // NoDecisionMade with verification disabled should succeed (no default check)
  14727. SSLClient cli(HOST, PORT);
  14728. cli.enable_server_certificate_verification(false);
  14729. cli.set_connection_timeout(30);
  14730. bool callback_called = false;
  14731. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14732. EXPECT_NE(session, nullptr);
  14733. callback_called = true;
  14734. return SSLVerifierResponse::NoDecisionMade;
  14735. });
  14736. auto res = cli.Get("/test");
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(200, res->status);
  14739. EXPECT_TRUE(callback_called);
  14740. }
  14741. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14743. ASSERT_TRUE(svr.is_valid());
  14744. svr.Get("/test", [](const Request &, Response &res) {
  14745. res.set_content("ok", "text/plain");
  14746. });
  14747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14748. auto se = detail::scope_exit([&] {
  14749. svr.stop();
  14750. t.join();
  14751. });
  14752. svr.wait_until_ready();
  14753. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14754. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14755. // so we only check that the request fails, not whether the callback was
  14756. // called.
  14757. SSLClient cli(HOST, PORT);
  14758. cli.enable_server_certificate_verification(true);
  14759. cli.set_connection_timeout(30);
  14760. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14761. EXPECT_NE(session, nullptr);
  14762. return SSLVerifierResponse::NoDecisionMade;
  14763. });
  14764. auto res = cli.Get("/test");
  14765. EXPECT_FALSE(res);
  14766. }
  14767. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14768. // Test SSL server using PemMemory constructor with client CA certificates
  14769. // Read PEM files
  14770. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14771. read_file(SERVER_CERT_FILE, server_cert_pem);
  14772. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14773. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14774. // Create SSLServer with PemMemory constructor including client CA
  14775. SSLServer::PemMemory server_pem = {
  14776. server_cert_pem.c_str(),
  14777. server_cert_pem.size(),
  14778. server_key_pem.c_str(),
  14779. server_key_pem.size(),
  14780. client_ca_pem.c_str(),
  14781. client_ca_pem.size(),
  14782. nullptr // no password for server key
  14783. };
  14784. SSLServer svr(server_pem);
  14785. ASSERT_TRUE(svr.is_valid());
  14786. // No SSL error should be recorded for valid setup
  14787. EXPECT_EQ(0, svr.ssl_last_error());
  14788. // Set up server endpoints
  14789. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. // Start server in a thread
  14793. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14794. svr.wait_until_ready();
  14795. // Connect with client certificate (using constructor with paths)
  14796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14797. cli.enable_server_certificate_verification(false);
  14798. auto res = cli.Get("/test-pem-ca");
  14799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14800. EXPECT_EQ(200, res->status);
  14801. EXPECT_EQ("ok", res->body);
  14802. svr.stop();
  14803. server_thread.join();
  14804. }
  14805. #endif
  14806. #ifdef _WIN32
  14807. TEST(CleanupTest, WSACleanup) {
  14808. int ret = WSACleanup();
  14809. ASSERT_EQ(0, ret);
  14810. }
  14811. #endif
  14812. #ifndef CPPHTTPLIB_SSL_ENABLED
  14813. TEST(NoSSLSupport, SimpleInterface) {
  14814. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14815. }
  14816. #endif
  14817. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14818. TEST(InvalidScheme, SimpleInterface) {
  14819. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14820. }
  14821. #endif
  14822. TEST(NoScheme, SimpleInterface) {
  14823. Client cli("yahoo.com:80");
  14824. ASSERT_TRUE(cli.is_valid());
  14825. }
  14826. TEST(SendAPI, SimpleInterface_Online) {
  14827. Client cli("http://yahoo.com");
  14828. Request req;
  14829. req.method = "GET";
  14830. req.path = "/";
  14831. auto res = cli.send(req);
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14834. }
  14835. TEST(SendAPI, WithParamsInRequest) {
  14836. Server svr;
  14837. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14838. EXPECT_TRUE(req.has_param("test"));
  14839. EXPECT_EQ("test_value", req.get_param_value("test"));
  14840. });
  14841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14842. auto se = detail::scope_exit([&] {
  14843. svr.stop();
  14844. t.join();
  14845. ASSERT_FALSE(svr.is_running());
  14846. });
  14847. svr.wait_until_ready();
  14848. Client cli(HOST, PORT);
  14849. {
  14850. Request req;
  14851. req.method = "GET";
  14852. req.path = "/";
  14853. req.params.emplace("test", "test_value");
  14854. auto res = cli.send(req);
  14855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14856. }
  14857. {
  14858. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. }
  14861. }
  14862. TEST(ClientImplMethods, GetSocketTest) {
  14863. httplib::Server svr;
  14864. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14865. res.status = StatusCode::OK_200;
  14866. });
  14867. auto port = svr.bind_to_any_port("127.0.0.1");
  14868. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. thread.join();
  14872. ASSERT_FALSE(svr.is_running());
  14873. });
  14874. svr.wait_until_ready();
  14875. {
  14876. httplib::Client cli("127.0.0.1", port);
  14877. cli.set_keep_alive(true);
  14878. // Use the behavior of cpp-httplib of opening the connection
  14879. // only when the first request happens. If that changes,
  14880. // this test would be obsolete.
  14881. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14882. // This also implicitly tests the server. But other tests would fail much
  14883. // earlier than this one to be considered.
  14884. auto res = cli.Get("/");
  14885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14886. EXPECT_EQ(StatusCode::OK_200, res->status);
  14887. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14888. }
  14889. }
  14890. #ifdef CPPHTTPLIB_SSL_ENABLED
  14891. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14892. Client cli("http://yahoo.com");
  14893. auto res = cli.Get("/");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14896. cli.set_follow_location(true);
  14897. res = cli.Get("/");
  14898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14899. EXPECT_EQ(StatusCode::OK_200, res->status);
  14900. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14901. }
  14902. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14903. Client cli("https://yahoo.com");
  14904. auto res = cli.Get("/");
  14905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14906. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14907. cli.set_follow_location(true);
  14908. res = cli.Get("/");
  14909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14910. EXPECT_EQ(StatusCode::OK_200, res->status);
  14911. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14912. }
  14913. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14914. Client cli("https://yahoo.com");
  14915. auto res = cli.Get("/");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. ASSERT_FALSE(!res);
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. ASSERT_FALSE(res == nullptr);
  14920. ASSERT_TRUE(res != nullptr);
  14921. EXPECT_EQ(Error::Success, res.error());
  14922. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14923. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14925. cli.set_follow_location(true);
  14926. res = cli.Get("/");
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. EXPECT_EQ(Error::Success, res.error());
  14929. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14930. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14931. EXPECT_EQ(StatusCode::OK_200, res->status);
  14932. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14933. }
  14934. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14935. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14936. Client cli("https://cdnjs.cloudflare.com");
  14937. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14938. Headers{{"Accept-Encoding", "br"}});
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. EXPECT_EQ(287630U, res->body.size());
  14942. EXPECT_EQ("application/javascript; charset=utf-8",
  14943. res->get_header_value("Content-Type"));
  14944. }
  14945. #endif
  14946. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14947. #undef REDIR_HOST // Silence compiler warning
  14948. #define REDIR_HOST "https://httpbingo.org"
  14949. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14950. Client cli(REDIR_HOST);
  14951. cli.set_follow_location(true);
  14952. auto res =
  14953. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14955. EXPECT_EQ(StatusCode::OK_200, res->status);
  14956. }
  14957. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14958. Client cli(REDIR_HOST);
  14959. cli.set_follow_location(true);
  14960. Params params;
  14961. params.emplace("url", "http://example.com");
  14962. params.emplace("status_code", "302");
  14963. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14965. EXPECT_EQ(StatusCode::OK_200, res->status);
  14966. }
  14967. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14968. Client cli(REDIR_HOST);
  14969. cli.set_follow_location(true);
  14970. Params params;
  14971. params.emplace("url", "http://example.com");
  14972. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. TEST(HttpToHttpsRedirectTest, CertFile) {
  14977. auto ssl_port = PORT + 1;
  14978. Server svr;
  14979. ASSERT_TRUE(svr.is_valid());
  14980. svr.Get("/index", [&](const Request &, Response &res) {
  14981. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14982. "/index");
  14983. svr.stop();
  14984. });
  14985. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14986. ASSERT_TRUE(ssl_svr.is_valid());
  14987. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14988. res.set_content("test", "text/plain");
  14989. ssl_svr.stop();
  14990. });
  14991. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14992. thread t2 =
  14993. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14994. auto se = detail::scope_exit([&] {
  14995. t2.join();
  14996. t.join();
  14997. ASSERT_FALSE(svr.is_running());
  14998. });
  14999. svr.wait_until_ready();
  15000. ssl_svr.wait_until_ready();
  15001. Client cli("127.0.0.1", PORT);
  15002. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15003. cli.enable_server_certificate_verification(true);
  15004. cli.set_follow_location(true);
  15005. cli.set_connection_timeout(30);
  15006. auto res = cli.Get("/index");
  15007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15008. ASSERT_EQ(StatusCode::OK_200, res->status);
  15009. }
  15010. TEST(SSLClientRedirectTest, CertFile) {
  15011. auto ssl_port = PORT + 1;
  15012. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15013. ASSERT_TRUE(ssl_svr1.is_valid());
  15014. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15015. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15016. "/index");
  15017. ssl_svr1.stop();
  15018. });
  15019. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15020. ASSERT_TRUE(ssl_svr2.is_valid());
  15021. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15022. res.set_content("test", "text/plain");
  15023. ssl_svr2.stop();
  15024. });
  15025. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15026. thread t2 =
  15027. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15028. auto se = detail::scope_exit([&] {
  15029. t2.join();
  15030. t.join();
  15031. ASSERT_FALSE(ssl_svr1.is_running());
  15032. });
  15033. ssl_svr1.wait_until_ready();
  15034. ssl_svr2.wait_until_ready();
  15035. SSLClient cli("127.0.0.1", PORT);
  15036. std::string cert;
  15037. read_file(SERVER_CERT2_FILE, cert);
  15038. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15039. cli.enable_server_certificate_verification(true);
  15040. cli.set_follow_location(true);
  15041. cli.set_connection_timeout(30);
  15042. auto res = cli.Get("/index");
  15043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15044. ASSERT_EQ(StatusCode::OK_200, res->status);
  15045. }
  15046. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15047. // another port, so the client follows it with a new client.
  15048. static Result GetThroughTlsRedirectToDifferentPort(
  15049. const std::function<void(SSLClient &)> &setup,
  15050. const char *target_cert = SERVER_CERT2_FILE,
  15051. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15052. auto ssl_port = PORT + 1;
  15053. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15054. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15055. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15056. "/index");
  15057. });
  15058. SSLServer ssl_svr2(target_cert, target_key);
  15059. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15060. res.set_content("test", "text/plain");
  15061. });
  15062. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15063. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15064. auto se = detail::scope_exit([&] {
  15065. ssl_svr2.stop();
  15066. ssl_svr1.stop();
  15067. t2.join();
  15068. t.join();
  15069. });
  15070. ssl_svr1.wait_until_ready();
  15071. ssl_svr2.wait_until_ready();
  15072. SSLClient cli("127.0.0.1", PORT);
  15073. cli.set_follow_location(true);
  15074. cli.set_connection_timeout(30);
  15075. setup(cli);
  15076. return cli.Get("/index");
  15077. }
  15078. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15079. auto calls = 0;
  15080. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15081. cli.enable_server_certificate_verification(false);
  15082. // Accept the first server only.
  15083. cli.set_session_verifier([&](tls::session_t) {
  15084. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15085. : SSLVerifierResponse::CertificateRejected;
  15086. });
  15087. });
  15088. ASSERT_FALSE(res);
  15089. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15090. EXPECT_EQ(2, calls);
  15091. }
  15092. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15093. std::string pinned;
  15094. auto res = GetThroughTlsRedirectToDifferentPort(
  15095. [&](SSLClient &cli) {
  15096. cli.enable_server_certificate_verification(false);
  15097. // Pin the first certificate seen.
  15098. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15099. if (pinned.empty()) { pinned = ctx.serial(); }
  15100. return ctx.serial() == pinned;
  15101. });
  15102. },
  15103. // A certificate other than the first server's.
  15104. SERVER_CERT_FILE);
  15105. EXPECT_FALSE(res);
  15106. EXPECT_FALSE(pinned.empty());
  15107. }
  15108. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15109. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15110. std::string cert;
  15111. read_file(SERVER_CERT2_FILE, cert);
  15112. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15113. });
  15114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15115. EXPECT_EQ(StatusCode::OK_200, res->status);
  15116. }
  15117. // The target's certificate is signed by the root CA, which the first server's
  15118. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15119. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15120. auto res = GetThroughTlsRedirectToDifferentPort(
  15121. [](SSLClient &cli) {
  15122. std::string root_ca, cert;
  15123. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15124. read_file(SERVER_CERT2_FILE, cert);
  15125. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15126. cli.load_ca_cert_store(cert.data(), cert.size());
  15127. cli.enable_server_hostname_verification(false);
  15128. },
  15129. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. EXPECT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15134. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15135. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15136. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15137. auto res = GetThroughTlsRedirectToDifferentPort(
  15138. [](SSLClient &cli) {
  15139. std::string root_ca, cert;
  15140. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15141. read_file(SERVER_CERT2_FILE, cert);
  15142. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15143. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15144. cli.enable_server_hostname_verification(false);
  15145. },
  15146. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15147. ASSERT_FALSE(res);
  15148. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15149. }
  15150. #endif
  15151. #endif
  15152. #ifdef CPPHTTPLIB_SSL_ENABLED
  15153. // Test that set_ca_cert_store() skips system certs (consistent with
  15154. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15155. // should be trusted - system certs should NOT be loaded.
  15156. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15157. // Load a specific cert that is NOT a system CA cert
  15158. std::string cert;
  15159. read_file(SERVER_CERT2_FILE, cert);
  15160. SSLClient cli("google.com");
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. // This should FAIL because:
  15164. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15165. // 2. System certs should NOT be loaded when custom store is set
  15166. // If system certs WERE loaded, this would succeed
  15167. auto res = cli.Get("/");
  15168. ASSERT_FALSE(res);
  15169. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15170. }
  15171. // Same as above, but through the native store handle path. Regression test:
  15172. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15173. // merged system certs into the user-provided store.
  15174. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15175. std::string cert;
  15176. read_file(SERVER_CERT2_FILE, cert);
  15177. SSLClient cli("google.com");
  15178. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15179. cli.enable_server_certificate_verification(true);
  15180. auto res = cli.Get("/");
  15181. ASSERT_FALSE(res);
  15182. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15183. }
  15184. // A custom store set via the native handle must still verify a server whose
  15185. // cert it does contain.
  15186. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15187. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15188. ASSERT_TRUE(svr.is_valid());
  15189. svr.Get("/test", [&](const Request &, Response &res) {
  15190. res.set_content("test", "text/plain");
  15191. });
  15192. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15193. auto se = detail::scope_exit([&] {
  15194. svr.stop();
  15195. t.join();
  15196. ASSERT_FALSE(svr.is_running());
  15197. });
  15198. svr.wait_until_ready();
  15199. SSLClient cli("127.0.0.1", PORT);
  15200. std::string cert;
  15201. read_file(SERVER_CERT2_FILE, cert);
  15202. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15203. cli.enable_server_certificate_verification(true);
  15204. cli.set_connection_timeout(30);
  15205. auto res = cli.Get("/test");
  15206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15207. ASSERT_EQ(StatusCode::OK_200, res->status);
  15208. }
  15209. // CA certs loaded through the universal Client must be transferred to the
  15210. // client created internally for following an HTTPS redirect. Regression test:
  15211. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15212. // the CA data for redirect transfer.
  15213. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15214. auto ssl_port = PORT + 1;
  15215. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15216. ASSERT_TRUE(ssl_svr1.is_valid());
  15217. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15218. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15219. "/index");
  15220. });
  15221. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15222. ASSERT_TRUE(ssl_svr2.is_valid());
  15223. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15224. res.set_content("test", "text/plain");
  15225. });
  15226. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15227. thread t2 =
  15228. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15229. auto se = detail::scope_exit([&] {
  15230. ssl_svr2.stop();
  15231. ssl_svr1.stop();
  15232. t2.join();
  15233. t.join();
  15234. ASSERT_FALSE(ssl_svr1.is_running());
  15235. });
  15236. ssl_svr1.wait_until_ready();
  15237. ssl_svr2.wait_until_ready();
  15238. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15239. std::string cert;
  15240. read_file(SERVER_CERT2_FILE, cert);
  15241. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15242. cli.enable_server_certificate_verification(true);
  15243. cli.set_follow_location(true);
  15244. cli.set_connection_timeout(30);
  15245. auto res = cli.Get("/index");
  15246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15247. ASSERT_EQ(StatusCode::OK_200, res->status);
  15248. }
  15249. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15250. // so a host signed by a system CA verifies even though a custom CA is set
  15251. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15252. std::string cert;
  15253. read_file(SERVER_CERT2_FILE, cert);
  15254. SSLClient cli("google.com");
  15255. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15256. cli.enable_system_ca(true);
  15257. cli.enable_server_certificate_verification(true);
  15258. auto res = cli.Get("/");
  15259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15260. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15261. }
  15262. // The custom CA remains effective when combined with the system CA
  15263. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15265. ASSERT_TRUE(svr.is_valid());
  15266. svr.Get("/test", [&](const Request &, Response &res) {
  15267. res.set_content("test", "text/plain");
  15268. });
  15269. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15270. auto se = detail::scope_exit([&] {
  15271. svr.stop();
  15272. t.join();
  15273. ASSERT_FALSE(svr.is_running());
  15274. });
  15275. svr.wait_until_ready();
  15276. SSLClient cli("127.0.0.1", PORT);
  15277. std::string cert;
  15278. read_file(SERVER_CERT2_FILE, cert);
  15279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15280. cli.enable_system_ca(true);
  15281. cli.enable_server_certificate_verification(true);
  15282. cli.set_connection_timeout(30);
  15283. auto res = cli.Get("/test");
  15284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15285. ASSERT_EQ(StatusCode::OK_200, res->status);
  15286. }
  15287. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15288. // skip chain verification entirely (only the certificate identity was
  15289. // checked), so a server presenting an untrusted certificate with a matching
  15290. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15291. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15292. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15293. ASSERT_TRUE(svr.is_valid());
  15294. svr.Get("/test", [&](const Request &, Response &res) {
  15295. res.set_content("test", "text/plain");
  15296. });
  15297. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. t.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. });
  15303. svr.wait_until_ready();
  15304. SSLClient cli("127.0.0.1", PORT);
  15305. std::string cert;
  15306. // A trusted CA that did not sign the server certificate. The server cert
  15307. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15308. // this connection.
  15309. read_file(CLIENT_CA_CERT_FILE, cert);
  15310. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15311. cli.enable_server_certificate_verification(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/test");
  15314. ASSERT_FALSE(res);
  15315. }
  15316. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15317. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15318. // CA that failed to come through fails verification instead of trusting them.
  15319. // (wolfSSL does not list the system CAs it loaded.)
  15320. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15321. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15322. ASSERT_TRUE(svr.is_valid());
  15323. auto port = svr.bind_to_any_port("127.0.0.1");
  15324. ASSERT_LT(0, port);
  15325. thread t = thread([&] { svr.listen_after_bind(); });
  15326. auto se = detail::scope_exit([&] {
  15327. svr.stop();
  15328. t.join();
  15329. ASSERT_FALSE(svr.is_running());
  15330. });
  15331. svr.wait_until_ready();
  15332. // The CAs a client trusts once its first request has loaded them
  15333. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15334. Client cli("https://127.0.0.1:" + std::to_string(port));
  15335. setup(cli);
  15336. cli.Get("/");
  15337. return tls::get_ca_names(cli.tls_context()).size();
  15338. };
  15339. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15340. EXPECT_EQ(0u,
  15341. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15342. }
  15343. #endif
  15344. // A TLS setting changed between requests applies to the next one, not just to
  15345. // the next connection
  15346. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15347. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15348. ASSERT_TRUE(svr.is_valid());
  15349. svr.Get("/", [](const Request &req, Response &res) {
  15350. res.set_content(std::to_string(req.remote_port), "text/plain");
  15351. });
  15352. auto port = svr.bind_to_any_port("127.0.0.1");
  15353. ASSERT_LT(0, port);
  15354. thread t = thread([&] { svr.listen_after_bind(); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. });
  15360. svr.wait_until_ready();
  15361. SSLClient cli("127.0.0.1", port);
  15362. cli.set_keep_alive(true);
  15363. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15364. cli.enable_server_certificate_verification(false);
  15365. // The port the request went out from, so a new one means a new connection
  15366. auto client_port = [&] {
  15367. auto res = cli.Get("/");
  15368. return res ? res->body : std::string();
  15369. };
  15370. auto last = client_port();
  15371. ASSERT_FALSE(last.empty());
  15372. // Setting a value it already has keeps the connection
  15373. cli.enable_server_certificate_verification(false);
  15374. cli.enable_server_hostname_verification(true);
  15375. EXPECT_EQ(last, client_port());
  15376. cli.enable_server_certificate_verification(true);
  15377. auto res = cli.Get("/");
  15378. EXPECT_FALSE(res);
  15379. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15380. std::string ca;
  15381. read_file(SERVER_CERT2_FILE, ca);
  15382. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15383. last = client_port();
  15384. ASSERT_FALSE(last.empty());
  15385. std::vector<std::function<void()>> setters = {
  15386. [&] { cli.enable_server_hostname_verification(false); },
  15387. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15388. [&] {
  15389. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15390. },
  15391. [&] {
  15392. cli.set_server_certificate_verifier(
  15393. [](const tls::VerifyContext &) { return true; });
  15394. },
  15395. [&] {
  15396. cli.set_session_verifier(
  15397. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15398. },
  15399. };
  15400. for (const auto &setter : setters) {
  15401. setter();
  15402. auto next = client_port();
  15403. ASSERT_FALSE(next.empty());
  15404. EXPECT_NE(last, next);
  15405. last = next;
  15406. }
  15407. cli.set_session_verifier(
  15408. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15409. auto handle = cli.open_stream("GET", "/");
  15410. EXPECT_FALSE(handle.is_valid());
  15411. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15412. }
  15413. // A PEM given to create_ca_store() needs no NUL after it
  15414. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15415. std::string pem;
  15416. read_file(SERVER_CERT2_FILE, pem);
  15417. auto buf = pem + "X";
  15418. auto store = tls::create_ca_store(buf.data(), pem.size());
  15419. EXPECT_TRUE(store != nullptr);
  15420. SSLClient cli("localhost");
  15421. cli.set_ca_cert_store(store);
  15422. }
  15423. // enable_system_ca(false) prevents system CA loading entirely
  15424. TEST(SSLClientTest, DisableSystemCa_Online) {
  15425. SSLClient cli("google.com");
  15426. cli.enable_system_ca(false);
  15427. cli.enable_server_certificate_verification(true);
  15428. auto res = cli.Get("/");
  15429. ASSERT_FALSE(res);
  15430. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15431. // itself when the CA chain is empty
  15432. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15433. res.error() == Error::SSLConnection);
  15434. }
  15435. // The universal Client forwards enable_system_ca()
  15436. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15437. std::string cert;
  15438. read_file(SERVER_CERT2_FILE, cert);
  15439. Client cli("https://google.com");
  15440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15441. cli.enable_system_ca(true);
  15442. cli.enable_server_certificate_verification(true);
  15443. auto res = cli.Get("/");
  15444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15445. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15446. }
  15447. // The system CA policy must carry over to the client created internally for
  15448. // following a cross-host HTTPS redirect
  15449. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15450. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15451. ASSERT_TRUE(svr.is_valid());
  15452. svr.Get("/index", [&](const Request &, Response &res) {
  15453. res.set_redirect("https://www.google.com/");
  15454. });
  15455. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15456. auto se = detail::scope_exit([&] {
  15457. svr.stop();
  15458. t.join();
  15459. ASSERT_FALSE(svr.is_running());
  15460. });
  15461. svr.wait_until_ready();
  15462. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15463. std::string cert;
  15464. read_file(SERVER_CERT2_FILE, cert);
  15465. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15466. cli.enable_system_ca(true);
  15467. cli.enable_server_certificate_verification(true);
  15468. cli.set_follow_location(true);
  15469. cli.set_connection_timeout(30);
  15470. // Receiving any response proves the redirect client completed the TLS
  15471. // handshake with a system-CA-signed host
  15472. auto res = cli.Get("/index");
  15473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15474. }
  15475. TEST(MultipartFormDataTest, LargeData) {
  15476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15477. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15478. const ContentReader &content_reader) {
  15479. if (req.is_multipart_form_data()) {
  15480. std::vector<FormData> items;
  15481. content_reader(
  15482. [&](const FormData &file) {
  15483. items.push_back(file);
  15484. return true;
  15485. },
  15486. [&](const char *data, size_t data_length) {
  15487. items.back().content.append(data, data_length);
  15488. return true;
  15489. });
  15490. EXPECT_TRUE(std::string(items[0].name) == "document");
  15491. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15492. EXPECT_TRUE(items[0].filename == "2MB_data");
  15493. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15494. EXPECT_TRUE(items[1].name == "hello");
  15495. EXPECT_TRUE(items[1].content == "world");
  15496. EXPECT_TRUE(items[1].filename == "");
  15497. EXPECT_TRUE(items[1].content_type == "");
  15498. } else {
  15499. std::string body;
  15500. content_reader([&](const char *data, size_t data_length) {
  15501. body.append(data, data_length);
  15502. return true;
  15503. });
  15504. }
  15505. });
  15506. auto port = svr.bind_to_any_port(HOST);
  15507. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15508. auto se = detail::scope_exit([&] {
  15509. svr.stop();
  15510. t.join();
  15511. ASSERT_FALSE(svr.is_running());
  15512. });
  15513. svr.wait_until_ready();
  15514. {
  15515. std::string data(1024 * 1024 * 2, '.');
  15516. std::stringstream buffer;
  15517. buffer << data;
  15518. SSLClient cli(HOST, port);
  15519. cli.enable_server_certificate_verification(false);
  15520. UploadFormDataItems items{
  15521. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15522. {"hello", "world", "", ""},
  15523. };
  15524. auto res = cli.Post("/post", items);
  15525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15526. ASSERT_EQ(StatusCode::OK_200, res->status);
  15527. }
  15528. }
  15529. TEST(MultipartFormDataTest, DataProviderItems) {
  15530. std::random_device seed_gen;
  15531. std::mt19937 random(seed_gen());
  15532. std::string rand1;
  15533. rand1.resize(1000);
  15534. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15535. std::string rand2;
  15536. rand2.resize(3000);
  15537. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15539. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15540. const ContentReader &content_reader) {
  15541. ASSERT_FALSE(req.is_multipart_form_data());
  15542. std::string body;
  15543. content_reader([&](const char *data, size_t data_length) {
  15544. body.append(data, data_length);
  15545. return true;
  15546. });
  15547. EXPECT_EQ(body, "");
  15548. });
  15549. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15550. const ContentReader &content_reader) {
  15551. ASSERT_TRUE(req.is_multipart_form_data());
  15552. std::vector<FormData> items;
  15553. content_reader(
  15554. [&](const FormData &file) {
  15555. items.push_back(file);
  15556. return true;
  15557. },
  15558. [&](const char *data, size_t data_length) {
  15559. items.back().content.append(data, data_length);
  15560. return true;
  15561. });
  15562. ASSERT_TRUE(items.size() == 2);
  15563. EXPECT_EQ(std::string(items[0].name), "name1");
  15564. EXPECT_EQ(items[0].content, "Testing123");
  15565. EXPECT_EQ(items[0].filename, "filename1");
  15566. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15567. EXPECT_EQ(items[1].name, "name2");
  15568. EXPECT_EQ(items[1].content, "Testing456");
  15569. EXPECT_EQ(items[1].filename, "");
  15570. EXPECT_EQ(items[1].content_type, "");
  15571. });
  15572. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15573. const ContentReader &content_reader) {
  15574. ASSERT_TRUE(req.is_multipart_form_data());
  15575. std::vector<FormData> items;
  15576. content_reader(
  15577. [&](const FormData &file) {
  15578. items.push_back(file);
  15579. return true;
  15580. },
  15581. [&](const char *data, size_t data_length) {
  15582. items.back().content.append(data, data_length);
  15583. return true;
  15584. });
  15585. ASSERT_TRUE(items.size() == 2);
  15586. EXPECT_EQ(items[0].name, "name3");
  15587. EXPECT_EQ(items[0].content, rand1);
  15588. EXPECT_EQ(items[0].filename, "filename3");
  15589. EXPECT_EQ(items[0].content_type, "");
  15590. EXPECT_EQ(items[1].name, "name4");
  15591. EXPECT_EQ(items[1].content, rand2);
  15592. EXPECT_EQ(items[1].filename, "filename4");
  15593. EXPECT_EQ(items[1].content_type, "");
  15594. });
  15595. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15596. const ContentReader &content_reader) {
  15597. ASSERT_TRUE(req.is_multipart_form_data());
  15598. std::vector<FormData> items;
  15599. content_reader(
  15600. [&](const FormData &file) {
  15601. items.push_back(file);
  15602. return true;
  15603. },
  15604. [&](const char *data, size_t data_length) {
  15605. items.back().content.append(data, data_length);
  15606. return true;
  15607. });
  15608. ASSERT_TRUE(items.size() == 4);
  15609. EXPECT_EQ(std::string(items[0].name), "name1");
  15610. EXPECT_EQ(items[0].content, "Testing123");
  15611. EXPECT_EQ(items[0].filename, "filename1");
  15612. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15613. EXPECT_EQ(items[1].name, "name2");
  15614. EXPECT_EQ(items[1].content, "Testing456");
  15615. EXPECT_EQ(items[1].filename, "");
  15616. EXPECT_EQ(items[1].content_type, "");
  15617. EXPECT_EQ(items[2].name, "name3");
  15618. EXPECT_EQ(items[2].content, rand1);
  15619. EXPECT_EQ(items[2].filename, "filename3");
  15620. EXPECT_EQ(items[2].content_type, "");
  15621. EXPECT_EQ(items[3].name, "name4");
  15622. EXPECT_EQ(items[3].content, rand2);
  15623. EXPECT_EQ(items[3].filename, "filename4");
  15624. EXPECT_EQ(items[3].content_type, "");
  15625. });
  15626. auto port = svr.bind_to_any_port("localhost");
  15627. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. t.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. {
  15635. SSLClient cli("localhost", port);
  15636. cli.enable_server_certificate_verification(false);
  15637. UploadFormDataItems items{
  15638. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15639. {"name2", "Testing456", "", ""}, // not a file
  15640. };
  15641. {
  15642. auto res = cli.Post("/post-none", {}, {}, {});
  15643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15644. ASSERT_EQ(StatusCode::OK_200, res->status);
  15645. }
  15646. FormDataProviderItems providers;
  15647. {
  15648. auto res =
  15649. cli.Post("/post-items", {}, items, providers); // empty providers
  15650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15651. ASSERT_EQ(StatusCode::OK_200, res->status);
  15652. }
  15653. providers.push_back({"name3",
  15654. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15655. // test the offset is given correctly at each step
  15656. if (!offset)
  15657. sink.os.write(rand1.data(), 30);
  15658. else if (offset == 30)
  15659. sink.os.write(rand1.data() + 30, 300);
  15660. else if (offset == 330)
  15661. sink.os.write(rand1.data() + 330, 670);
  15662. else if (offset == rand1.size())
  15663. sink.done();
  15664. return true;
  15665. },
  15666. "filename3",
  15667. {}});
  15668. providers.push_back({"name4",
  15669. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15670. // test the offset is given correctly at each step
  15671. if (!offset)
  15672. sink.os.write(rand2.data(), 2000);
  15673. else if (offset == 2000)
  15674. sink.os.write(rand2.data() + 2000, 1);
  15675. else if (offset == 2001)
  15676. sink.os.write(rand2.data() + 2001, 999);
  15677. else if (offset == rand2.size())
  15678. sink.done();
  15679. return true;
  15680. },
  15681. "filename4",
  15682. {}});
  15683. {
  15684. auto res = cli.Post("/post-providers", {}, {}, providers);
  15685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15686. ASSERT_EQ(StatusCode::OK_200, res->status);
  15687. }
  15688. {
  15689. auto res = cli.Post("/post-both", {}, items, providers);
  15690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15691. ASSERT_EQ(StatusCode::OK_200, res->status);
  15692. }
  15693. }
  15694. }
  15695. TEST(MultipartFormDataTest, BadHeader) {
  15696. Server svr;
  15697. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15698. res.set_content("ok", "text/plain");
  15699. });
  15700. thread t = thread([&] { svr.listen(HOST, PORT); });
  15701. auto se = detail::scope_exit([&] {
  15702. svr.stop();
  15703. t.join();
  15704. ASSERT_FALSE(svr.is_running());
  15705. });
  15706. svr.wait_until_ready();
  15707. const std::string body =
  15708. "This is the preamble. It is to be ignored, though it\r\n"
  15709. "is a handy place for composition agents to include an\r\n"
  15710. "explanatory note to non-MIME conformant readers.\r\n"
  15711. "\r\n"
  15712. "\r\n"
  15713. "--simple boundary\r\n"
  15714. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15715. ": BAD...\r\n"
  15716. "\r\n"
  15717. "value1\r\n"
  15718. "--simple boundary\r\n"
  15719. "Content-Disposition: form-data; name=\"field2\"; "
  15720. "filename=\"example.txt\"\r\n"
  15721. "\r\n"
  15722. "value2\r\n"
  15723. "--simple boundary--\r\n"
  15724. "This is the epilogue. It is also to be ignored.\r\n";
  15725. std::string content_type =
  15726. R"(multipart/form-data; boundary="simple boundary")";
  15727. Client cli(HOST, PORT);
  15728. auto res = cli.Post("/post", body, content_type.c_str());
  15729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15731. }
  15732. TEST(MultipartFormDataTest, WithPreamble) {
  15733. Server svr;
  15734. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. thread t = thread([&] { svr.listen(HOST, PORT); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. t.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. const std::string body =
  15745. "This is the preamble. It is to be ignored, though it\r\n"
  15746. "is a handy place for composition agents to include an\r\n"
  15747. "explanatory note to non-MIME conformant readers.\r\n"
  15748. "\r\n"
  15749. "\r\n"
  15750. "--simple boundary\r\n"
  15751. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15752. "\r\n"
  15753. "value1\r\n"
  15754. "--simple boundary\r\n"
  15755. "Content-Disposition: form-data; name=\"field2\"; "
  15756. "filename=\"example.txt\"\r\n"
  15757. "\r\n"
  15758. "value2\r\n"
  15759. "--simple boundary--\r\n"
  15760. "This is the epilogue. It is also to be ignored.\r\n";
  15761. std::string content_type =
  15762. R"(multipart/form-data; boundary="simple boundary")";
  15763. Client cli(HOST, PORT);
  15764. auto res = cli.Post("/post", body, content_type.c_str());
  15765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15766. EXPECT_EQ(StatusCode::OK_200, res->status);
  15767. }
  15768. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15770. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15771. const ContentReader &content_reader) {
  15772. if (req.is_multipart_form_data()) {
  15773. std::vector<FormData> items;
  15774. content_reader(
  15775. [&](const FormData &file) {
  15776. items.push_back(file);
  15777. return true;
  15778. },
  15779. [&](const char *data, size_t data_length) {
  15780. items.back().content.append(data, data_length);
  15781. return true;
  15782. });
  15783. EXPECT_TRUE(std::string(items[0].name) == "document");
  15784. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15785. EXPECT_TRUE(items[0].filename == "2MB_data");
  15786. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15787. EXPECT_TRUE(items[1].name == "hello");
  15788. EXPECT_TRUE(items[1].content == "world");
  15789. EXPECT_TRUE(items[1].filename == "");
  15790. EXPECT_TRUE(items[1].content_type == "");
  15791. } else {
  15792. std::string body;
  15793. content_reader([&](const char *data, size_t data_length) {
  15794. body.append(data, data_length);
  15795. return true;
  15796. });
  15797. }
  15798. });
  15799. auto port = svr.bind_to_any_port("localhost");
  15800. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. {
  15808. std::string data(1024 * 1024 * 2, '.');
  15809. std::stringstream buffer;
  15810. buffer << data;
  15811. SSLClient cli("localhost", port);
  15812. cli.enable_server_certificate_verification(false);
  15813. UploadFormDataItems items{
  15814. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15815. {"hello", "world", "", ""},
  15816. };
  15817. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15819. ASSERT_EQ(StatusCode::OK_200, res->status);
  15820. }
  15821. }
  15822. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15823. std::string data(1024 * 1024 * 2, '&');
  15824. std::stringstream buffer;
  15825. buffer << data;
  15826. Client cli("https://localhost:8080");
  15827. UploadFormDataItems items{
  15828. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15829. {"hello", "world", "", ""},
  15830. };
  15831. for (const char &c : " \t\r\n") {
  15832. auto res =
  15833. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15834. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15835. ASSERT_FALSE(res);
  15836. }
  15837. }
  15838. TEST(MultipartFormDataTest, PutFormData) {
  15839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15840. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15841. const ContentReader &content_reader) {
  15842. if (req.is_multipart_form_data()) {
  15843. std::vector<FormData> items;
  15844. content_reader(
  15845. [&](const FormData &file) {
  15846. items.push_back(file);
  15847. return true;
  15848. },
  15849. [&](const char *data, size_t data_length) {
  15850. items.back().content.append(data, data_length);
  15851. return true;
  15852. });
  15853. EXPECT_TRUE(std::string(items[0].name) == "document");
  15854. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15855. EXPECT_TRUE(items[0].filename == "2MB_data");
  15856. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15857. EXPECT_TRUE(items[1].name == "hello");
  15858. EXPECT_TRUE(items[1].content == "world");
  15859. EXPECT_TRUE(items[1].filename == "");
  15860. EXPECT_TRUE(items[1].content_type == "");
  15861. } else {
  15862. std::string body;
  15863. content_reader([&](const char *data, size_t data_length) {
  15864. body.append(data, data_length);
  15865. return true;
  15866. });
  15867. }
  15868. });
  15869. auto port = svr.bind_to_any_port("localhost");
  15870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15871. auto se = detail::scope_exit([&] {
  15872. svr.stop();
  15873. t.join();
  15874. ASSERT_FALSE(svr.is_running());
  15875. });
  15876. svr.wait_until_ready();
  15877. {
  15878. std::string data(1024 * 1024 * 2, '&');
  15879. std::stringstream buffer;
  15880. buffer << data;
  15881. SSLClient cli("localhost", port);
  15882. cli.enable_server_certificate_verification(false);
  15883. UploadFormDataItems items{
  15884. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15885. {"hello", "world", "", ""},
  15886. };
  15887. auto res = cli.Put("/put", items);
  15888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15889. ASSERT_EQ(StatusCode::OK_200, res->status);
  15890. }
  15891. }
  15892. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15894. svr.Put("/put_customboundary",
  15895. [&](const Request &req, const Response & /*res*/,
  15896. const ContentReader &content_reader) {
  15897. if (req.is_multipart_form_data()) {
  15898. std::vector<FormData> items;
  15899. content_reader(
  15900. [&](const FormData &file) {
  15901. items.push_back(file);
  15902. return true;
  15903. },
  15904. [&](const char *data, size_t data_length) {
  15905. items.back().content.append(data, data_length);
  15906. return true;
  15907. });
  15908. EXPECT_TRUE(std::string(items[0].name) == "document");
  15909. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15910. EXPECT_TRUE(items[0].filename == "2MB_data");
  15911. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15912. EXPECT_TRUE(items[1].name == "hello");
  15913. EXPECT_TRUE(items[1].content == "world");
  15914. EXPECT_TRUE(items[1].filename == "");
  15915. EXPECT_TRUE(items[1].content_type == "");
  15916. } else {
  15917. std::string body;
  15918. content_reader([&](const char *data, size_t data_length) {
  15919. body.append(data, data_length);
  15920. return true;
  15921. });
  15922. }
  15923. });
  15924. auto port = svr.bind_to_any_port("localhost");
  15925. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15926. auto se = detail::scope_exit([&] {
  15927. svr.stop();
  15928. t.join();
  15929. ASSERT_FALSE(svr.is_running());
  15930. });
  15931. svr.wait_until_ready();
  15932. {
  15933. std::string data(1024 * 1024 * 2, '&');
  15934. std::stringstream buffer;
  15935. buffer << data;
  15936. SSLClient cli("localhost", port);
  15937. cli.enable_server_certificate_verification(false);
  15938. UploadFormDataItems items{
  15939. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15940. {"hello", "world", "", ""},
  15941. };
  15942. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15944. ASSERT_EQ(StatusCode::OK_200, res->status);
  15945. }
  15946. }
  15947. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15948. std::string data(1024 * 1024 * 2, '&');
  15949. std::stringstream buffer;
  15950. buffer << data;
  15951. Client cli("https://localhost:8080");
  15952. cli.enable_server_certificate_verification(false);
  15953. UploadFormDataItems items{
  15954. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15955. {"hello", "world", "", ""},
  15956. };
  15957. for (const char &c : " \t\r\n") {
  15958. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15959. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15960. ASSERT_FALSE(res);
  15961. }
  15962. }
  15963. TEST(MultipartFormDataTest, AlternateFilename) {
  15964. auto handled = false;
  15965. Server svr;
  15966. svr.Post("/test", [&](const Request &req, Response &res) {
  15967. ASSERT_EQ(2u, req.form.files.size());
  15968. ASSERT_EQ(1u, req.form.fields.size());
  15969. // Test files
  15970. const auto &file1 = req.form.get_file("file1");
  15971. ASSERT_EQ("file1", file1.name);
  15972. ASSERT_EQ("A.txt", file1.filename);
  15973. ASSERT_EQ("text/plain", file1.content_type);
  15974. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15975. const auto &file2 = req.form.get_file("file2");
  15976. ASSERT_EQ("file2", file2.name);
  15977. ASSERT_EQ("a.html", file2.filename);
  15978. ASSERT_EQ("text/html", file2.content_type);
  15979. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15980. file2.content);
  15981. // Test text field
  15982. const auto &text = req.form.get_field("text");
  15983. ASSERT_EQ("text default", text);
  15984. res.set_content("ok", "text/plain");
  15985. handled = true;
  15986. });
  15987. thread t = thread([&] { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. ASSERT_TRUE(handled);
  15993. });
  15994. svr.wait_until_ready();
  15995. auto req = "POST /test HTTP/1.1\r\n"
  15996. "Host: localhost\r\n"
  15997. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15998. "Content-Length: 399\r\n"
  15999. "\r\n"
  16000. "----------\r\n"
  16001. "Content-Disposition: form-data; name=\"text\"\r\n"
  16002. "\r\n"
  16003. "text default\r\n"
  16004. "----------\r\n"
  16005. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16006. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16007. "Content-Type: text/plain\r\n"
  16008. "\r\n"
  16009. "Content of a.txt.\r\n"
  16010. "\r\n"
  16011. "----------\r\n"
  16012. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16013. "\"a.html\"\r\n"
  16014. "Content-Type: text/html\r\n"
  16015. "\r\n"
  16016. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16017. "\r\n"
  16018. "------------\r\n";
  16019. ASSERT_TRUE(send_request(1, req));
  16020. }
  16021. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16022. auto handled = false;
  16023. Server svr;
  16024. svr.Post("/test", [&](const Request &req, Response &res) {
  16025. // Case-insensitive "utf-8''" prefix with a long value
  16026. const auto &file = req.form.get_file("file1");
  16027. ASSERT_EQ("file1", file.name);
  16028. // 8000 chars exercises both the Content-Disposition parser and the
  16029. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16030. // Prior to the fix, std::regex_match on this header would cause O(N)
  16031. // stack recursion in libstdc++, leading to SIGSEGV.
  16032. std::string expected_filename(8000, 'A');
  16033. ASSERT_EQ(expected_filename, file.filename);
  16034. res.set_content("ok", "text/plain");
  16035. handled = true;
  16036. });
  16037. thread t = thread([&] { svr.listen(HOST, PORT); });
  16038. auto se = detail::scope_exit([&] {
  16039. svr.stop();
  16040. t.join();
  16041. ASSERT_FALSE(svr.is_running());
  16042. ASSERT_TRUE(handled);
  16043. });
  16044. svr.wait_until_ready();
  16045. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16046. // Regression test for GHSA-qq6v-r583-3h69
  16047. std::string long_filename(8000, 'A');
  16048. std::string body = "----------\r\n"
  16049. "Content-Disposition: form-data; name=\"file1\"; "
  16050. "filename*=\"Utf-8''" +
  16051. long_filename +
  16052. "\"\r\n"
  16053. "\r\n"
  16054. "hello\r\n"
  16055. "------------\r\n";
  16056. auto req = "POST /test HTTP/1.1\r\n"
  16057. "Host: localhost\r\n"
  16058. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16059. "Content-Length: " +
  16060. std::to_string(body.size()) + "\r\n\r\n" + body;
  16061. ASSERT_TRUE(send_request(1, req));
  16062. }
  16063. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16064. auto handled = false;
  16065. Server svr;
  16066. svr.Post("/test", [&](const Request &req, Response &) {
  16067. ASSERT_EQ(2u, req.form.fields.size());
  16068. const auto &text1 = req.form.get_field("text1");
  16069. ASSERT_EQ("text1", text1);
  16070. const auto &text2 = req.form.get_field("text2");
  16071. ASSERT_EQ("text2", text2);
  16072. handled = true;
  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. ASSERT_TRUE(handled);
  16080. });
  16081. svr.wait_until_ready();
  16082. auto req = "POST /test HTTP/1.1\r\n"
  16083. "Host: localhost\r\n"
  16084. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16085. "Content-Length: 146\r\n"
  16086. "\r\n----------\r\n"
  16087. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16088. "\r\n"
  16089. "text1"
  16090. "\r\n----------\r\n"
  16091. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16092. "\r\n"
  16093. "text2"
  16094. "\r\n------------";
  16095. std::string response;
  16096. ASSERT_TRUE(send_request(1, req, &response));
  16097. ASSERT_EQ("200", response.substr(9, 3));
  16098. }
  16099. TEST(MultipartFormDataTest, ContentLength) {
  16100. auto handled = false;
  16101. Server svr;
  16102. svr.Post("/test", [&](const Request &req, Response &) {
  16103. ASSERT_EQ(2u, req.form.fields.size());
  16104. const auto &text1 = req.form.get_field("text1");
  16105. ASSERT_EQ("text1", text1);
  16106. const auto &text2 = req.form.get_field("text2");
  16107. ASSERT_EQ("text2", text2);
  16108. handled = true;
  16109. });
  16110. thread t = thread([&] { svr.listen(HOST, PORT); });
  16111. auto se = detail::scope_exit([&] {
  16112. svr.stop();
  16113. t.join();
  16114. ASSERT_FALSE(svr.is_running());
  16115. ASSERT_TRUE(handled);
  16116. });
  16117. svr.wait_until_ready();
  16118. auto req = "POST /test HTTP/1.1\r\n"
  16119. "Host: localhost\r\n"
  16120. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16121. "Content-Length: 167\r\n"
  16122. "\r\n----------\r\n"
  16123. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16124. "Content-Length: 5\r\n"
  16125. "\r\n"
  16126. "text1"
  16127. "\r\n----------\r\n"
  16128. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16129. "\r\n"
  16130. "text2"
  16131. "\r\n------------\r\n";
  16132. std::string response;
  16133. ASSERT_TRUE(send_request(1, req, &response));
  16134. ASSERT_EQ("200", response.substr(9, 3));
  16135. }
  16136. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16137. auto handled = false;
  16138. Server svr;
  16139. svr.Post("/test", [&](const Request &req, Response &) {
  16140. ASSERT_EQ(2u, req.form.fields.size());
  16141. const auto &text1 = req.form.get_field("text1");
  16142. ASSERT_EQ("text1", text1);
  16143. // TODO: Add header access for text fields if needed
  16144. const auto &text2 = req.form.get_field("text2");
  16145. ASSERT_EQ("text2", text2);
  16146. // TODO: Header access for text fields needs to be implemented
  16147. // auto &headers = it->second.headers;
  16148. // ASSERT_EQ(3U, headers.size());
  16149. // auto custom_header = headers.find("x-whatever");
  16150. // ASSERT_TRUE(custom_header != headers.end());
  16151. // ASSERT_NE("customvalue", custom_header->second);
  16152. // ASSERT_EQ("CustomValue", custom_header->second);
  16153. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16154. handled = true;
  16155. });
  16156. thread t = thread([&] { svr.listen(HOST, PORT); });
  16157. auto se = detail::scope_exit([&] {
  16158. svr.stop();
  16159. t.join();
  16160. ASSERT_FALSE(svr.is_running());
  16161. ASSERT_TRUE(handled);
  16162. });
  16163. svr.wait_until_ready();
  16164. auto req = "POST /test HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16167. "Content-Length: 232\r\n"
  16168. "\r\n----------\r\n"
  16169. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16170. "Content-Length: 5\r\n"
  16171. "X-Test: 1\r\n"
  16172. "\r\n"
  16173. "text1"
  16174. "\r\n----------\r\n"
  16175. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16176. "Content-Type: text/plain\r\n"
  16177. "X-Whatever: CustomValue\r\n"
  16178. "\r\n"
  16179. "text2"
  16180. "\r\n------------\r\n"
  16181. "That should be disregarded. Not even read";
  16182. std::string response;
  16183. ASSERT_TRUE(send_request(1, req, &response));
  16184. ASSERT_EQ("200", response.substr(9, 3));
  16185. }
  16186. TEST(MultipartFormDataTest, LargeHeader) {
  16187. auto handled = false;
  16188. Server svr;
  16189. svr.Post("/test", [&](const Request &req, Response &) {
  16190. ASSERT_EQ(1u, req.form.fields.size());
  16191. const auto &text = req.form.get_field("name1");
  16192. ASSERT_EQ("text1", text);
  16193. handled = true;
  16194. });
  16195. thread t = thread([&] { svr.listen(HOST, PORT); });
  16196. auto se = detail::scope_exit([&] {
  16197. svr.stop();
  16198. t.join();
  16199. ASSERT_FALSE(svr.is_running());
  16200. ASSERT_TRUE(handled);
  16201. });
  16202. svr.wait_until_ready();
  16203. auto boundary = std::string("cpp-httplib-multipart-data");
  16204. std::string content = "--" + boundary +
  16205. "\r\n"
  16206. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16207. "\r\n"
  16208. "text1\r\n"
  16209. "--" +
  16210. boundary + "--\r\n";
  16211. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16212. "Host: localhost\r\n"
  16213. "Content-Type: multipart/form-data;boundary=" +
  16214. boundary +
  16215. "\r\n"
  16216. "Content-Length: " +
  16217. std::to_string(content.size()) +
  16218. "\r\n"
  16219. "Dummy-Header: ";
  16220. std::string header_suffix = "\r\n"
  16221. "\r\n";
  16222. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16223. size_t header_dummy_size =
  16224. read_buff_size -
  16225. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16226. auto header_dummy = std::string(header_dummy_size, '@');
  16227. auto req = header_prefix + header_dummy + header_suffix + content;
  16228. std::string response;
  16229. ASSERT_TRUE(send_request(1, req, &response));
  16230. ASSERT_EQ("200", response.substr(9, 3));
  16231. }
  16232. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16233. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16234. // (not chunked Transfer-Encoding) after the streaming refactor.
  16235. auto handled = false;
  16236. Server svr;
  16237. svr.Post("/upload", [&](const Request &req, Response &res) {
  16238. auto cl_it = req.headers.find("Content-Length");
  16239. EXPECT_TRUE(cl_it != req.headers.end());
  16240. auto te_it = req.headers.find("Transfer-Encoding");
  16241. EXPECT_TRUE(te_it == req.headers.end());
  16242. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16243. res.set_content("ok", "text/plain");
  16244. handled = true;
  16245. });
  16246. auto port = svr.bind_to_any_port(HOST);
  16247. auto t = thread([&] { svr.listen_after_bind(); });
  16248. auto se = detail::scope_exit([&] {
  16249. svr.stop();
  16250. t.join();
  16251. ASSERT_FALSE(svr.is_running());
  16252. ASSERT_TRUE(handled);
  16253. });
  16254. svr.wait_until_ready();
  16255. UploadFormDataItems items = {
  16256. {"field1", "hello", "", "text/plain"},
  16257. {"file1", "world", "test.txt", "application/octet-stream"},
  16258. };
  16259. Client cli(HOST, port);
  16260. auto res = cli.Post("/upload", {}, items);
  16261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16262. EXPECT_EQ(StatusCode::OK_200, res->status);
  16263. }
  16264. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16265. // Verify that make_multipart_content_provider coalesces many small segments
  16266. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16267. constexpr size_t kItemCount = 1000;
  16268. UploadFormDataItems items;
  16269. items.reserve(kItemCount);
  16270. for (size_t i = 0; i < kItemCount; i++) {
  16271. items.push_back(
  16272. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16273. }
  16274. const std::string boundary = "----test-boundary";
  16275. auto content_length = detail::get_multipart_content_length(items, boundary);
  16276. auto provider = detail::make_multipart_content_provider(items, boundary);
  16277. // Drive the provider the same way write_content_with_progress does
  16278. size_t write_count = 0;
  16279. size_t total_bytes = 0;
  16280. DataSink sink;
  16281. size_t offset = 0;
  16282. sink.write = [&](const char *d, size_t l) -> bool {
  16283. (void)d;
  16284. write_count++;
  16285. total_bytes += l;
  16286. offset += l;
  16287. return true;
  16288. };
  16289. sink.is_writable = []() -> bool { return true; };
  16290. while (offset < content_length) {
  16291. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16292. }
  16293. EXPECT_EQ(content_length, total_bytes);
  16294. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16295. // With buffering into 64KB blocks, write_count should be much smaller.
  16296. auto segment_count = 3 * kItemCount + 1;
  16297. EXPECT_LT(write_count, segment_count / 10);
  16298. }
  16299. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16300. // Integration test: send many UploadFormDataItems and verify the server
  16301. // receives all of them correctly (#2410).
  16302. constexpr size_t kItemCount = 500;
  16303. auto handled = false;
  16304. Server svr;
  16305. svr.Post("/upload", [&](const Request &req, Response &res) {
  16306. EXPECT_EQ(kItemCount, req.form.fields.size());
  16307. for (size_t i = 0; i < kItemCount; i++) {
  16308. auto key = "field" + std::to_string(i);
  16309. auto val = "value" + std::to_string(i);
  16310. auto it = req.form.fields.find(key);
  16311. if (it != req.form.fields.end()) {
  16312. EXPECT_EQ(val, it->second.content);
  16313. } else {
  16314. ADD_FAILURE() << "Missing field: " << key;
  16315. }
  16316. }
  16317. res.set_content("ok", "text/plain");
  16318. handled = true;
  16319. });
  16320. auto port = svr.bind_to_any_port(HOST);
  16321. auto t = thread([&] { svr.listen_after_bind(); });
  16322. auto se = detail::scope_exit([&] {
  16323. svr.stop();
  16324. t.join();
  16325. ASSERT_FALSE(svr.is_running());
  16326. ASSERT_TRUE(handled);
  16327. });
  16328. svr.wait_until_ready();
  16329. UploadFormDataItems items;
  16330. items.reserve(kItemCount);
  16331. for (size_t i = 0; i < kItemCount; i++) {
  16332. items.push_back(
  16333. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16334. }
  16335. Client cli(HOST, port);
  16336. auto res = cli.Post("/upload", items);
  16337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16338. EXPECT_EQ(StatusCode::OK_200, res->status);
  16339. }
  16340. TEST(MultipartFormDataTest, MakeFileProvider) {
  16341. // Verify make_file_provider sends a file's contents correctly.
  16342. const std::string file_content(4096, 'Z');
  16343. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16344. {
  16345. std::ofstream ofs(tmp_path, std::ios::binary);
  16346. ofs.write(file_content.data(),
  16347. static_cast<std::streamsize>(file_content.size()));
  16348. }
  16349. auto handled = false;
  16350. Server svr;
  16351. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16352. const ContentReader &content_reader) {
  16353. ASSERT_TRUE(req.is_multipart_form_data());
  16354. std::vector<FormData> items;
  16355. content_reader(
  16356. [&](const FormData &file) {
  16357. items.push_back(file);
  16358. return true;
  16359. },
  16360. [&](const char *data, size_t data_length) {
  16361. items.back().content.append(data, data_length);
  16362. return true;
  16363. });
  16364. ASSERT_EQ(1u, items.size());
  16365. EXPECT_EQ("myfile", items[0].name);
  16366. EXPECT_EQ("data.bin", items[0].filename);
  16367. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16368. EXPECT_EQ(file_content, items[0].content);
  16369. handled = true;
  16370. });
  16371. auto port = svr.bind_to_any_port(HOST);
  16372. auto t = thread([&] { svr.listen_after_bind(); });
  16373. auto se = detail::scope_exit([&] {
  16374. svr.stop();
  16375. t.join();
  16376. ASSERT_FALSE(svr.is_running());
  16377. ASSERT_TRUE(handled);
  16378. std::remove(tmp_path.c_str());
  16379. });
  16380. svr.wait_until_ready();
  16381. FormDataProviderItems providers;
  16382. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16383. "application/octet-stream"));
  16384. Client cli(HOST, port);
  16385. auto res = cli.Post("/upload", {}, {}, providers);
  16386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16387. EXPECT_EQ(StatusCode::OK_200, res->status);
  16388. }
  16389. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16390. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16391. // (100) headers is rejected with a 400 Bad Request response.
  16392. Server svr;
  16393. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16394. res.set_content("ok", "text/plain");
  16395. });
  16396. thread t = thread([&] { svr.listen(HOST, PORT); });
  16397. auto se = detail::scope_exit([&] {
  16398. svr.stop();
  16399. t.join();
  16400. ASSERT_FALSE(svr.is_running());
  16401. });
  16402. svr.wait_until_ready();
  16403. // Build a multipart part with 101 custom headers (exceeding
  16404. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16405. std::stringstream body;
  16406. body << "--simpleboundary\r\n"
  16407. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16408. for (int i = 0; i < 101; i++) {
  16409. body << "X-Custom-Header-" << i << ": value\r\n";
  16410. }
  16411. body << "\r\n"
  16412. << "value1\r\n"
  16413. << "--simpleboundary--\r\n";
  16414. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16415. Client cli(HOST, PORT);
  16416. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16419. }
  16420. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16421. // A body that never contains the declared boundary must not be accumulated
  16422. // while the parser waits for it. Buffering it would also make every read
  16423. // rescan everything seen so far, which is quadratic in the body size.
  16424. Server svr;
  16425. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16426. res.set_content("ok", "text/plain");
  16427. });
  16428. auto port = svr.bind_to_any_port(HOST);
  16429. thread t = thread([&] { svr.listen_after_bind(); });
  16430. auto se = detail::scope_exit([&] {
  16431. svr.stop();
  16432. t.join();
  16433. ASSERT_FALSE(svr.is_running());
  16434. });
  16435. svr.wait_until_ready();
  16436. Client cli(HOST, port);
  16437. cli.set_read_timeout(60, 0);
  16438. cli.set_write_timeout(60, 0);
  16439. // '-' is the worst case: it matches the first character of the boundary, so
  16440. // every position has to be checked against it.
  16441. auto post_dashes = [&](size_t size) {
  16442. const std::string body(size, '-');
  16443. auto start = std::chrono::steady_clock::now();
  16444. auto res =
  16445. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16446. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16447. std::chrono::steady_clock::now() - start)
  16448. .count();
  16449. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16450. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16451. return ms;
  16452. };
  16453. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16454. // Windows.
  16455. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16456. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16457. // Comparing the two sizes rather than checking an absolute duration keeps
  16458. // this meaningful across build types and CI load, both of which move the
  16459. // absolute numbers by more than an order of magnitude. Four times the bytes
  16460. // costs about four times the time when parsing is linear, and about sixteen
  16461. // times when the body is buffered and rescanned.
  16462. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16463. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16464. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16465. << "ms, which suggests the body is being buffered and rescanned";
  16466. }
  16467. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16468. // A boundary can only be followed by CRLF or by "--", so anything else is
  16469. // malformed no matter what comes next. The parser must say so right away
  16470. // instead of buffering the rest of the declared body.
  16471. Server svr;
  16472. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16473. res.set_content("ok", "text/plain");
  16474. });
  16475. auto port = svr.bind_to_any_port(HOST);
  16476. thread t = thread([&] { svr.listen_after_bind(); });
  16477. auto se = detail::scope_exit([&] {
  16478. svr.stop();
  16479. t.join();
  16480. ASSERT_FALSE(svr.is_running());
  16481. });
  16482. svr.wait_until_ready();
  16483. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16484. // buffers instead of failing would still be waiting for the remaining bytes.
  16485. const std::string body = "--zzzz\r\n"
  16486. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16487. "\r\n"
  16488. "text1"
  16489. "\r\n--zzzzXX";
  16490. const std::string req = "POST /post HTTP/1.1\r\n"
  16491. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16492. "Content-Length: 1048576\r\n"
  16493. "\r\n" +
  16494. body;
  16495. std::string response;
  16496. ASSERT_TRUE(send_request(3, req, &response, port));
  16497. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16498. EXPECT_EQ("400", response.substr(9, 3));
  16499. }
  16500. // Posts a multipart body split into two writes, so that the server sees the
  16501. // split at whatever offset the caller chose, and expects the single "text1"
  16502. // field to come through.
  16503. static void expect_split_multipart_ok(const std::string &body1,
  16504. const std::string &body2) {
  16505. auto handled = false;
  16506. Server svr;
  16507. svr.Post("/post", [&](const Request &req, Response &) {
  16508. EXPECT_EQ(1u, req.form.fields.size());
  16509. EXPECT_EQ("text1", req.form.get_field("text1"));
  16510. handled = true;
  16511. });
  16512. auto port = svr.bind_to_any_port(HOST);
  16513. thread t = thread([&] { svr.listen_after_bind(); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. ASSERT_TRUE(handled);
  16519. });
  16520. svr.wait_until_ready();
  16521. // "Connection: close" makes the server close once it has answered, so the
  16522. // response drain ends immediately instead of idling until the read timeout.
  16523. const std::string head =
  16524. "POST /post HTTP/1.1\r\n"
  16525. "Host: localhost\r\n"
  16526. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16527. "Connection: close\r\n"
  16528. "Content-Length: " +
  16529. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16530. std::string response;
  16531. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16532. ASSERT_GE(response.size(), 12u) << "no response";
  16533. EXPECT_EQ("200", response.substr(9, 3));
  16534. }
  16535. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16536. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16537. // ignored, including when it does not arrive in the same read as the
  16538. // close-delimiter itself.
  16539. expect_split_multipart_ok("--zzzz\r\n"
  16540. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16541. "\r\n"
  16542. "text1"
  16543. "\r\n--zzzz--",
  16544. "\r\nthis epilogue must be ignored\r\n");
  16545. }
  16546. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16547. // The initial boundary may be preceded by a preamble of any length and may
  16548. // straddle a read boundary. Discarding data while waiting for it must not
  16549. // throw away a partial boundary sitting at the end of the buffer.
  16550. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16551. "zz\r\n"
  16552. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16553. "\r\n"
  16554. "text1"
  16555. "\r\n--zzzz--\r\n");
  16556. }
  16557. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16558. // The received boundary was only checked for being non-empty, so it could be
  16559. // as long as a header is allowed to be. The parser scans the body for
  16560. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16561. // costs a nearly full comparison at nearly every position, making the
  16562. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16563. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16564. Server svr;
  16565. svr.Post("/post", [](const Request &req, Response &res) {
  16566. EXPECT_EQ(1u, req.form.fields.size());
  16567. EXPECT_EQ("text1", req.form.get_field("text1"));
  16568. res.set_content("ok", "text/plain");
  16569. });
  16570. auto port = svr.bind_to_any_port(HOST);
  16571. thread t = thread([&] { svr.listen_after_bind(); });
  16572. auto se = detail::scope_exit([&] {
  16573. svr.stop();
  16574. t.join();
  16575. ASSERT_FALSE(svr.is_running());
  16576. });
  16577. svr.wait_until_ready();
  16578. Client cli(HOST, port);
  16579. auto post_with_boundary_of_length = [&](size_t len) {
  16580. const std::string boundary(len, 'a');
  16581. const std::string body =
  16582. "--" + boundary +
  16583. "\r\n"
  16584. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16585. "\r\n"
  16586. "text1"
  16587. "\r\n--" +
  16588. boundary + "--\r\n";
  16589. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16590. };
  16591. auto res = post_with_boundary_of_length(70);
  16592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16593. EXPECT_EQ(StatusCode::OK_200, res->status);
  16594. res = post_with_boundary_of_length(71);
  16595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16596. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16597. }
  16598. TEST(MakeFileBodyTest, Basic) {
  16599. const std::string file_content(4096, 'Z');
  16600. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16601. {
  16602. std::ofstream ofs(tmp_path, std::ios::binary);
  16603. ofs.write(file_content.data(),
  16604. static_cast<std::streamsize>(file_content.size()));
  16605. }
  16606. auto handled = false;
  16607. Server svr;
  16608. svr.Post("/upload", [&](const Request &req, Response &res) {
  16609. EXPECT_EQ(file_content, req.body);
  16610. handled = true;
  16611. res.status = StatusCode::OK_200;
  16612. });
  16613. auto port = svr.bind_to_any_port(HOST);
  16614. auto t = thread([&] { svr.listen_after_bind(); });
  16615. auto se = detail::scope_exit([&] {
  16616. svr.stop();
  16617. t.join();
  16618. ASSERT_FALSE(svr.is_running());
  16619. ASSERT_TRUE(handled);
  16620. std::remove(tmp_path.c_str());
  16621. });
  16622. svr.wait_until_ready();
  16623. auto fb = make_file_body(tmp_path);
  16624. ASSERT_GT(fb.first, 0u);
  16625. Client cli(HOST, port);
  16626. auto res =
  16627. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16629. EXPECT_EQ(StatusCode::OK_200, res->status);
  16630. }
  16631. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16632. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16633. {
  16634. std::ofstream ofs(path, std::ios::binary);
  16635. const std::string content(100, 'A');
  16636. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16637. }
  16638. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16639. auto body = make_file_body(path);
  16640. ASSERT_EQ(100u, body.first);
  16641. ASSERT_TRUE(static_cast<bool>(body.second));
  16642. // Rewritten shorter after its length was measured - and, on a server, after
  16643. // that length has already gone out as Content-Length.
  16644. {
  16645. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16646. const std::string content(10, 'A');
  16647. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16648. }
  16649. std::string written;
  16650. DataSink sink;
  16651. sink.write = [&](const char *d, size_t l) {
  16652. written.append(d, l);
  16653. return true;
  16654. };
  16655. // The provider has to report failure. write_content_with_progress() advances
  16656. // its offset only by what was written, so a provider that returns true
  16657. // without completing the length it promised is called again straight away,
  16658. // and again.
  16659. EXPECT_FALSE(body.second(0, body.first, sink));
  16660. EXPECT_EQ(std::string(10, 'A'), written);
  16661. }
  16662. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16663. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16664. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16665. {
  16666. std::ofstream ofs(path, std::ios::binary);
  16667. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16668. }
  16669. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16670. auto body = make_file_body(path);
  16671. ASSERT_EQ(content.size(), body.first);
  16672. ASSERT_TRUE(static_cast<bool>(body.second));
  16673. std::string written;
  16674. DataSink sink;
  16675. sink.write = [&](const char *d, size_t l) {
  16676. written.append(d, l);
  16677. return true;
  16678. };
  16679. EXPECT_TRUE(body.second(0, body.first, sink));
  16680. EXPECT_EQ(content, written);
  16681. }
  16682. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16683. static constexpr unsigned int number_of_tasks{1000000};
  16684. std::atomic_uint count{0};
  16685. std::unique_ptr<TaskQueue> task_queue{
  16686. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16687. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16688. auto queued = task_queue->enqueue(
  16689. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16690. EXPECT_TRUE(queued);
  16691. }
  16692. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16693. task_queue->shutdown();
  16694. #else
  16695. EXPECT_NO_THROW(task_queue->shutdown());
  16696. #endif
  16697. EXPECT_EQ(number_of_tasks, count.load());
  16698. }
  16699. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16700. static constexpr unsigned int number_of_tasks{1000000};
  16701. static constexpr unsigned int qlimit{2};
  16702. unsigned int queued_count{0};
  16703. std::atomic_uint count{0};
  16704. std::unique_ptr<TaskQueue> task_queue{
  16705. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16706. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16707. if (task_queue->enqueue(
  16708. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16709. queued_count++;
  16710. }
  16711. }
  16712. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16713. task_queue->shutdown();
  16714. #else
  16715. EXPECT_NO_THROW(task_queue->shutdown());
  16716. #endif
  16717. EXPECT_EQ(queued_count, count.load());
  16718. EXPECT_TRUE(queued_count <= number_of_tasks);
  16719. EXPECT_TRUE(queued_count >= qlimit);
  16720. }
  16721. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16722. // Use a short idle timeout so a dynamic thread spawns, times out and
  16723. // exits during the test, and the pool keeps working afterwards.
  16724. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16725. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16726. /*idle_timeout_sec=*/1}};
  16727. std::atomic_uint count{0};
  16728. std::condition_variable cv;
  16729. std::mutex mtx;
  16730. bool release = false;
  16731. // Block the base thread so the second task spawns a dynamic thread.
  16732. EXPECT_TRUE(task_queue->enqueue([&] {
  16733. std::unique_lock<std::mutex> lock(mtx);
  16734. while (!release) {
  16735. cv.wait(lock);
  16736. }
  16737. count++;
  16738. }));
  16739. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16740. // Let the dynamic thread finish its task and exceed the idle timeout.
  16741. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16742. {
  16743. std::unique_lock<std::mutex> lock(mtx);
  16744. release = true;
  16745. }
  16746. cv.notify_all();
  16747. // The pool must still accept and run tasks after the dynamic thread exited.
  16748. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16749. task_queue->shutdown();
  16750. EXPECT_EQ(3u, count.load());
  16751. }
  16752. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16753. static constexpr size_t number_of_tasks{32};
  16754. std::unique_ptr<TaskQueue> task_queue{
  16755. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16756. // Let the base threads go idle so the burst below finds them waiting.
  16757. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16758. std::mutex mtx;
  16759. std::condition_variable cv;
  16760. size_t running = 0;
  16761. bool release = false;
  16762. for (size_t i = 0; i < number_of_tasks; i++) {
  16763. EXPECT_TRUE(task_queue->enqueue([&] {
  16764. std::unique_lock<std::mutex> lock(mtx);
  16765. running++;
  16766. cv.notify_all();
  16767. cv.wait(lock, [&] { return release; });
  16768. }));
  16769. }
  16770. {
  16771. std::unique_lock<std::mutex> lock(mtx);
  16772. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16773. [&] { return running == number_of_tasks; }));
  16774. release = true;
  16775. }
  16776. cv.notify_all();
  16777. task_queue->shutdown();
  16778. }
  16779. TEST(TaskQueueTest, MaxQueuedRequests) {
  16780. static constexpr unsigned int qlimit{3};
  16781. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16782. std::condition_variable sem_cv;
  16783. std::mutex sem_mtx;
  16784. int credits = 0;
  16785. bool queued;
  16786. /* Fill up the queue with tasks that will block until we give them credits to
  16787. * complete. */
  16788. for (unsigned int n = 0; n <= qlimit;) {
  16789. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16790. std::unique_lock<std::mutex> lock(sem_mtx);
  16791. while (credits <= 0) {
  16792. sem_cv.wait(lock);
  16793. }
  16794. /* Consume the credit and signal the test code if they are all gone. */
  16795. if (--credits == 0) { sem_cv.notify_one(); }
  16796. });
  16797. if (n < qlimit) {
  16798. /* The first qlimit enqueues must succeed. */
  16799. EXPECT_TRUE(queued);
  16800. } else {
  16801. /* The last one will succeed only when the worker thread
  16802. * starts and dequeues the first blocking task. Although
  16803. * not necessary for the correctness of this test, we sleep for
  16804. * a short while to avoid busy waiting. */
  16805. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16806. }
  16807. if (queued) { n++; }
  16808. }
  16809. /* Further enqueues must fail since the queue is full. */
  16810. for (auto i = 0; i < 4; i++) {
  16811. queued = task_queue->enqueue([] {});
  16812. EXPECT_FALSE(queued);
  16813. }
  16814. /* Give the credits to allow the previous tasks to complete. */
  16815. {
  16816. std::unique_lock<std::mutex> lock(sem_mtx);
  16817. credits += qlimit + 1;
  16818. }
  16819. sem_cv.notify_all();
  16820. /* Wait for all the credits to be consumed. */
  16821. {
  16822. std::unique_lock<std::mutex> lock(sem_mtx);
  16823. while (credits > 0) {
  16824. sem_cv.wait(lock);
  16825. }
  16826. }
  16827. /* Check that we are able again to enqueue at least qlimit tasks. */
  16828. for (unsigned int i = 0; i < qlimit; i++) {
  16829. queued = task_queue->enqueue([] {});
  16830. EXPECT_TRUE(queued);
  16831. }
  16832. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16833. task_queue->shutdown();
  16834. #else
  16835. EXPECT_NO_THROW(task_queue->shutdown());
  16836. #endif
  16837. }
  16838. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16839. Server svr;
  16840. std::string method;
  16841. std::string body;
  16842. auto has_content_length = false;
  16843. auto has_transfer_encoding = false;
  16844. std::atomic<int> bad_requests{0};
  16845. // Leftover body bytes get parsed as a malformed request and answered with
  16846. // 400
  16847. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16848. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16849. });
  16850. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16851. res.set_redirect("/down", StatusCode::SeeOther_303);
  16852. });
  16853. svr.Get("/down", [&](const Request &req, Response &res) {
  16854. method = req.method;
  16855. body = req.body;
  16856. has_content_length = req.has_header("Content-Length");
  16857. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16858. res.set_content("ok", "text/plain");
  16859. });
  16860. auto port = svr.bind_to_any_port(HOST);
  16861. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16862. auto se = detail::scope_exit([&] {
  16863. svr.stop();
  16864. thread.join();
  16865. ASSERT_FALSE(svr.is_running());
  16866. });
  16867. svr.wait_until_ready();
  16868. const std::string payload = "SECRET-BODY";
  16869. auto check = [&](Client &cli, const Result &res) {
  16870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16871. EXPECT_EQ(StatusCode::OK_200, res->status);
  16872. EXPECT_EQ("ok", res->body);
  16873. EXPECT_EQ("GET", method);
  16874. EXPECT_TRUE(body.empty());
  16875. EXPECT_FALSE(has_content_length);
  16876. EXPECT_FALSE(has_transfer_encoding);
  16877. // Nothing of the original body may be left on the connection
  16878. auto res2 = cli.Get("/down");
  16879. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16880. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16881. EXPECT_EQ("ok", res2->body);
  16882. EXPECT_EQ(0, bad_requests);
  16883. };
  16884. // With content length
  16885. {
  16886. Client cli(HOST, port);
  16887. cli.set_keep_alive(true);
  16888. cli.set_follow_location(true);
  16889. auto res = cli.Post(
  16890. "/up", payload.size(),
  16891. [&](size_t offset, size_t length, DataSink &sink) {
  16892. return sink.write(payload.data() + offset, length);
  16893. },
  16894. "text/plain");
  16895. check(cli, res);
  16896. }
  16897. // Without content length (chunked)
  16898. {
  16899. Client cli(HOST, port);
  16900. cli.set_keep_alive(true);
  16901. cli.set_follow_location(true);
  16902. auto res = cli.Post(
  16903. "/up",
  16904. [&](size_t /*offset*/, DataSink &sink) {
  16905. sink.write(payload.data(), payload.size());
  16906. sink.done();
  16907. return true;
  16908. },
  16909. "text/plain");
  16910. check(cli, res);
  16911. }
  16912. }
  16913. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16914. Server svr;
  16915. std::string target;
  16916. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16917. // Echo the still-encoded name back in the Location
  16918. const std::string prefix = "/start/";
  16919. res.status = StatusCode::Found_302;
  16920. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16921. });
  16922. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16923. target = req.target;
  16924. res.set_content("ok", "text/plain");
  16925. });
  16926. auto port = svr.bind_to_any_port(HOST);
  16927. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16928. auto se = detail::scope_exit([&] {
  16929. svr.stop();
  16930. thread.join();
  16931. ASSERT_FALSE(svr.is_running());
  16932. });
  16933. svr.wait_until_ready();
  16934. // Decoding the Location path would turn the first four into a path
  16935. // separator, a query delimiter, a fragment delimiter and a different
  16936. // percent-encoded octet. The rest must keep reaching the server as they are.
  16937. const std::vector<std::string> names = {
  16938. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16939. };
  16940. for (auto path_encode : {true, false}) {
  16941. Client cli(HOST, port);
  16942. cli.set_follow_location(true);
  16943. cli.set_path_encode(path_encode);
  16944. for (const auto &name : names) {
  16945. target.clear();
  16946. auto res = cli.Get("/start/" + name);
  16947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16948. EXPECT_EQ(StatusCode::OK_200, res->status);
  16949. EXPECT_EQ("/dest/" + name, target);
  16950. }
  16951. }
  16952. }
  16953. TEST(RedirectTest, NotModifiedIsReturned) {
  16954. Server svr;
  16955. svr.Get("/cached", [](const Request &, Response &res) {
  16956. res.status = StatusCode::NotModified_304;
  16957. });
  16958. auto port = svr.bind_to_any_port(HOST);
  16959. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16960. auto se = detail::scope_exit([&] {
  16961. svr.stop();
  16962. thread.join();
  16963. ASSERT_FALSE(svr.is_running());
  16964. });
  16965. svr.wait_until_ready();
  16966. Client cli(HOST, port);
  16967. cli.set_follow_location(true);
  16968. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16970. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16971. }
  16972. TEST(RedirectTest, NoLocationIsReturned) {
  16973. Server svr;
  16974. svr.Get("/no-location", [](const Request &, Response &res) {
  16975. res.status = StatusCode::Found_302;
  16976. res.set_content("no location", "text/plain");
  16977. });
  16978. auto port = svr.bind_to_any_port(HOST);
  16979. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16980. auto se = detail::scope_exit([&] {
  16981. svr.stop();
  16982. thread.join();
  16983. ASSERT_FALSE(svr.is_running());
  16984. });
  16985. svr.wait_until_ready();
  16986. Client cli(HOST, port);
  16987. cli.set_follow_location(true);
  16988. auto res = cli.Get("/no-location");
  16989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16990. EXPECT_EQ(StatusCode::Found_302, res->status);
  16991. EXPECT_EQ("no location", res->body);
  16992. // The callbacks see the body of the response that is returned
  16993. auto handler_called = false;
  16994. auto progress_called = false;
  16995. std::string body;
  16996. auto res2 = cli.Get(
  16997. "/no-location",
  16998. [&](const Response &) {
  16999. handler_called = true;
  17000. return true;
  17001. },
  17002. [&](const char *data, size_t data_length) {
  17003. body.append(data, data_length);
  17004. return true;
  17005. },
  17006. [&](size_t, size_t) {
  17007. progress_called = true;
  17008. return true;
  17009. });
  17010. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17011. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17012. EXPECT_TRUE(handler_called);
  17013. EXPECT_TRUE(progress_called);
  17014. EXPECT_EQ("no location", body);
  17015. }
  17016. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17017. Server svr;
  17018. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17019. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17020. });
  17021. svr.Get("/hello", [](const Request &req, Response &res) {
  17022. res.set_content(req.get_param_value("key"), "text/plain");
  17023. });
  17024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. {
  17032. Client cli(HOST, PORT);
  17033. cli.set_follow_location(true);
  17034. auto res = cli.Get("/");
  17035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17036. EXPECT_EQ(StatusCode::OK_200, res->status);
  17037. EXPECT_EQ("val&key2=val2", res->body);
  17038. }
  17039. }
  17040. #endif
  17041. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17042. Server svr;
  17043. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17044. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17045. });
  17046. svr.Get("/hello", [](const Request &req, Response &res) {
  17047. res.set_content(req.get_param_value("key"), "text/plain");
  17048. });
  17049. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17050. auto se = detail::scope_exit([&] {
  17051. svr.stop();
  17052. thread.join();
  17053. ASSERT_FALSE(svr.is_running());
  17054. });
  17055. svr.wait_until_ready();
  17056. {
  17057. Client cli(HOST, PORT);
  17058. cli.set_follow_location(true);
  17059. auto res = cli.Get("/");
  17060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17061. EXPECT_EQ(StatusCode::OK_200, res->status);
  17062. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17063. }
  17064. }
  17065. TEST(RedirectTest, RedirectWithPlusInPath) {
  17066. Server svr;
  17067. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17068. res.set_redirect("/a+b");
  17069. });
  17070. // Route pattern uses regex; escape + as \\+
  17071. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17072. res.set_content(req.path, "text/plain");
  17073. });
  17074. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17075. auto se = detail::scope_exit([&] {
  17076. svr.stop();
  17077. thread.join();
  17078. ASSERT_FALSE(svr.is_running());
  17079. });
  17080. svr.wait_until_ready();
  17081. {
  17082. Client cli(HOST, PORT);
  17083. cli.set_follow_location(true);
  17084. auto res = cli.Get("/");
  17085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17086. EXPECT_EQ(StatusCode::OK_200, res->status);
  17087. EXPECT_EQ("/a+b", res->body);
  17088. }
  17089. }
  17090. TEST(RedirectTest, ResolveRelativeLocation) {
  17091. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17092. const std::vector<std::pair<std::string, std::string>> cases = {
  17093. {"g", "/b/c/g"},
  17094. {"./g", "/b/c/g"},
  17095. {"g/", "/b/c/g/"},
  17096. {"?y", "/b/c/d;p?y"},
  17097. {"g?y", "/b/c/g?y"},
  17098. {"#s", "/b/c/d;p?q#s"},
  17099. {"g#s", "/b/c/g#s"},
  17100. {"g?y#s", "/b/c/g?y#s"},
  17101. {";x", "/b/c/;x"},
  17102. {"g;x", "/b/c/g;x"},
  17103. {".", "/b/c/"},
  17104. {"./", "/b/c/"},
  17105. {"..", "/b/"},
  17106. {"../", "/b/"},
  17107. {"../g", "/b/g"},
  17108. {"../..", "/"},
  17109. {"../../", "/"},
  17110. {"../../g", "/g"},
  17111. {"../../../g", "/g"},
  17112. {"g.", "/b/c/g."},
  17113. {".g", "/b/c/.g"},
  17114. {"g..", "/b/c/g.."},
  17115. {"..g", "/b/c/..g"},
  17116. {"./../g", "/b/g"},
  17117. {"./g/.", "/b/c/g/"},
  17118. {"g/./h", "/b/c/g/h"},
  17119. {"g/../h", "/b/c/h"},
  17120. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17121. {"g;x=1/../y", "/b/c/y"},
  17122. {"g?y/./x", "/b/c/g?y/./x"},
  17123. {"g#s/../x", "/b/c/g#s/../x"},
  17124. // Not relative-path references, so left for parse_url.
  17125. {"/g", "/g"},
  17126. {"//g", "//g"},
  17127. {"http://g/x", "http://g/x"},
  17128. {"g:h", "g:h"},
  17129. };
  17130. for (const auto &c : cases) {
  17131. EXPECT_EQ(c.second,
  17132. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17133. << c.first;
  17134. }
  17135. }
  17136. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17137. Server svr;
  17138. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17139. res.set_redirect(req.get_param_value("to"));
  17140. });
  17141. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17142. res.set_content(req.target, "text/plain");
  17143. });
  17144. svr.Get("/other", [](const Request &req, Response &res) {
  17145. res.set_content(req.target, "text/plain");
  17146. });
  17147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17148. auto se = detail::scope_exit([&] {
  17149. svr.stop();
  17150. thread.join();
  17151. ASSERT_FALSE(svr.is_running());
  17152. });
  17153. svr.wait_until_ready();
  17154. const std::vector<std::pair<std::string, std::string>> cases = {
  17155. {"next", "/dir/next"},
  17156. {"./next?x=1", "/dir/next?x=1"},
  17157. {"../other", "/other"},
  17158. };
  17159. for (const auto &c : cases) {
  17160. Client cli(HOST, PORT);
  17161. cli.set_follow_location(true);
  17162. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17163. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17164. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17165. EXPECT_EQ(c.second, res->body) << c.first;
  17166. }
  17167. }
  17168. #ifdef CPPHTTPLIB_SSL_ENABLED
  17169. TEST(RedirectTest, Issue2185_Online) {
  17170. SSLClient client("github.com");
  17171. client.set_follow_location(true);
  17172. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17173. "Coollab-Windows.zip");
  17174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17175. EXPECT_EQ(StatusCode::OK_200, res->status);
  17176. EXPECT_EQ(9920427U, res->body.size());
  17177. }
  17178. #endif
  17179. TEST(VulnerabilityTest, CRLFInjection) {
  17180. Server svr;
  17181. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17182. res.set_content("Hello 1", "text/plain");
  17183. });
  17184. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17185. res.set_content("Hello 2", "text/plain");
  17186. });
  17187. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17188. res.set_content("Hello 3", "text/plain");
  17189. });
  17190. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17191. res.set_content("Hello 4", "text/plain");
  17192. });
  17193. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17194. for (const auto &x : req.headers) {
  17195. auto key = x.first;
  17196. EXPECT_STRNE("evil", key.c_str());
  17197. }
  17198. });
  17199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17200. auto se = detail::scope_exit([&] {
  17201. svr.stop();
  17202. thread.join();
  17203. ASSERT_FALSE(svr.is_running());
  17204. });
  17205. svr.wait_until_ready();
  17206. {
  17207. Client cli(HOST, PORT);
  17208. cli.Post("/test1", "A=B",
  17209. "application/x-www-form-urlencoded\r\nevil: hello1");
  17210. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17211. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17212. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17213. }
  17214. }
  17215. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17216. auto server_thread = std::thread([] {
  17217. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17218. default_socket_options(srv);
  17219. sockaddr_in addr{};
  17220. addr.sin_family = AF_INET;
  17221. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17222. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17223. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17224. ::listen(srv, 1);
  17225. sockaddr_in cli_addr{};
  17226. socklen_t cli_len = sizeof(cli_addr);
  17227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17228. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17229. std::string buf_all;
  17230. char buf[2048];
  17231. ssize_t n;
  17232. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17233. buf_all.append(buf, static_cast<size_t>(n));
  17234. size_t pos;
  17235. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17236. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17237. auto e = request_block.find("\r\n");
  17238. if (e != std::string::npos) {
  17239. auto request_line = request_block.substr(0, e);
  17240. std::string msg =
  17241. "CRLF injection detected in request line: '" + request_line + "'";
  17242. EXPECT_FALSE(true) << msg;
  17243. }
  17244. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17245. ::send(cli,
  17246. #ifdef _WIN32
  17247. static_cast<const char *>(resp.c_str()),
  17248. static_cast<int>(resp.size()),
  17249. #else
  17250. resp.c_str(), resp.size(),
  17251. #endif
  17252. 0);
  17253. buf_all.erase(0, pos + 4);
  17254. }
  17255. }
  17256. detail::close_socket(cli);
  17257. detail::close_socket(srv);
  17258. });
  17259. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17260. auto cli = Client("127.0.0.1", PORT + 1);
  17261. auto headers = Headers{
  17262. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17263. {"Connection", "keep-alive"}};
  17264. auto res = cli.Get("/hi", headers);
  17265. EXPECT_FALSE(res);
  17266. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17267. server_thread.join();
  17268. }
  17269. // A request rejected before any byte reaches the socket must fail right away
  17270. // instead of waiting for a response the server will never send.
  17271. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17272. // The kernel completes the TCP handshake from the listen backlog, so the
  17273. // client connects, but nothing ever reads, responds or closes.
  17274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17275. default_socket_options(srv);
  17276. sockaddr_in addr{};
  17277. addr.sin_family = AF_INET;
  17278. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17279. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17280. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17281. ASSERT_EQ(0, ::listen(srv, 8));
  17282. auto cli = Client("127.0.0.1", PORT + 1);
  17283. cli.set_read_timeout(10, 0);
  17284. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17285. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17286. std::chrono::steady_clock::now() - start)
  17287. .count();
  17288. };
  17289. {
  17290. Request req;
  17291. req.method = "GE T";
  17292. req.path = "/";
  17293. auto start = std::chrono::steady_clock::now();
  17294. auto res = cli.send(req);
  17295. EXPECT_FALSE(res);
  17296. EXPECT_EQ(Error::Write, res.error());
  17297. EXPECT_LT(elapsed_ms(start), 1000);
  17298. }
  17299. {
  17300. auto start = std::chrono::steady_clock::now();
  17301. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17302. EXPECT_FALSE(res);
  17303. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17304. EXPECT_LT(elapsed_ms(start), 1000);
  17305. }
  17306. EXPECT_FALSE(cli.is_socket_open());
  17307. detail::close_socket(srv);
  17308. }
  17309. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17310. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17311. default_socket_options(srv);
  17312. sockaddr_in addr{};
  17313. addr.sin_family = AF_INET;
  17314. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17315. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17316. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17317. ASSERT_EQ(0, ::listen(srv, 1));
  17318. std::string received;
  17319. auto server_thread = std::thread([&] {
  17320. auto sock = ::accept(srv, nullptr, nullptr);
  17321. if (sock == INVALID_SOCKET) { return; }
  17322. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17323. char buf[2048];
  17324. ssize_t n;
  17325. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17326. received.append(buf, static_cast<size_t>(n));
  17327. }
  17328. detail::close_socket(sock);
  17329. });
  17330. {
  17331. auto cli = Client("127.0.0.1", PORT + 1);
  17332. // "Z" sorts after the default headers, so writing straight to the socket
  17333. // would have sent the request line and those headers before the rejection.
  17334. auto handle =
  17335. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17336. EXPECT_FALSE(handle.is_valid());
  17337. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17338. }
  17339. server_thread.join();
  17340. detail::close_socket(srv);
  17341. EXPECT_TRUE(received.empty()) << received;
  17342. }
  17343. TEST(PathParamsTest, StaticMatch) {
  17344. const auto pattern = "/users/all";
  17345. detail::PathParamsMatcher matcher(pattern);
  17346. Request request;
  17347. request.path = "/users/all";
  17348. ASSERT_TRUE(matcher.match(request));
  17349. std::unordered_map<std::string, std::string> expected_params = {};
  17350. EXPECT_EQ(request.path_params, expected_params);
  17351. }
  17352. TEST(PathParamsTest, StaticMismatch) {
  17353. const auto pattern = "/users/all";
  17354. detail::PathParamsMatcher matcher(pattern);
  17355. Request request;
  17356. request.path = "/users/1";
  17357. ASSERT_FALSE(matcher.match(request));
  17358. }
  17359. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17360. const auto pattern = "/users/:id/subscriptions";
  17361. detail::PathParamsMatcher matcher(pattern);
  17362. Request request;
  17363. request.path = "/users/42/subscriptions";
  17364. ASSERT_TRUE(matcher.match(request));
  17365. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17366. EXPECT_EQ(request.path_params, expected_params);
  17367. }
  17368. TEST(PathParamsTest, SingleParamInTheEnd) {
  17369. const auto pattern = "/users/:id";
  17370. detail::PathParamsMatcher matcher(pattern);
  17371. Request request;
  17372. request.path = "/users/24";
  17373. ASSERT_TRUE(matcher.match(request));
  17374. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17375. EXPECT_EQ(request.path_params, expected_params);
  17376. }
  17377. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17378. const auto pattern = "/users/:id/";
  17379. detail::PathParamsMatcher matcher(pattern);
  17380. Request request;
  17381. request.path = "/users/42/";
  17382. ASSERT_TRUE(matcher.match(request));
  17383. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17384. EXPECT_EQ(request.path_params, expected_params);
  17385. }
  17386. TEST(PathParamsTest, EmptyParam) {
  17387. const auto pattern = "/users/:id/";
  17388. detail::PathParamsMatcher matcher(pattern);
  17389. Request request;
  17390. request.path = "/users//";
  17391. ASSERT_TRUE(matcher.match(request));
  17392. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17393. EXPECT_EQ(request.path_params, expected_params);
  17394. }
  17395. TEST(PathParamsTest, FragmentMismatch) {
  17396. const auto pattern = "/users/:id/";
  17397. detail::PathParamsMatcher matcher(pattern);
  17398. Request request;
  17399. request.path = "/admins/24/";
  17400. ASSERT_FALSE(matcher.match(request));
  17401. }
  17402. TEST(PathParamsTest, ExtraFragments) {
  17403. const auto pattern = "/users/:id";
  17404. detail::PathParamsMatcher matcher(pattern);
  17405. Request request;
  17406. request.path = "/users/42/subscriptions";
  17407. ASSERT_FALSE(matcher.match(request));
  17408. }
  17409. TEST(PathParamsTest, MissingTrailingParam) {
  17410. const auto pattern = "/users/:id";
  17411. detail::PathParamsMatcher matcher(pattern);
  17412. Request request;
  17413. request.path = "/users";
  17414. ASSERT_FALSE(matcher.match(request));
  17415. }
  17416. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17417. const auto pattern = "/users/:id/subscriptions";
  17418. detail::PathParamsMatcher matcher(pattern);
  17419. Request request;
  17420. request.path = "/users/subscriptions";
  17421. ASSERT_FALSE(matcher.match(request));
  17422. }
  17423. TEST(PathParamsTest, MultipleParams) {
  17424. const auto pattern = "/users/:userid/subscriptions/:subid";
  17425. detail::PathParamsMatcher matcher(pattern);
  17426. Request request;
  17427. request.path = "/users/42/subscriptions/2";
  17428. ASSERT_TRUE(matcher.match(request));
  17429. std::unordered_map<std::string, std::string> expected_params = {
  17430. {"userid", "42"}, {"subid", "2"}};
  17431. EXPECT_EQ(request.path_params, expected_params);
  17432. }
  17433. TEST(PathParamsTest, SequenceOfParams) {
  17434. const auto pattern = "/values/:x/:y/:z";
  17435. detail::PathParamsMatcher matcher(pattern);
  17436. Request request;
  17437. request.path = "/values/1/2/3";
  17438. ASSERT_TRUE(matcher.match(request));
  17439. std::unordered_map<std::string, std::string> expected_params = {
  17440. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17441. EXPECT_EQ(request.path_params, expected_params);
  17442. }
  17443. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17444. const auto pattern = "/prefix:suffix";
  17445. detail::PathParamsMatcher matcher(pattern);
  17446. Request request;
  17447. request.path = "/prefix:suffix";
  17448. ASSERT_TRUE(matcher.match(request));
  17449. const std::unordered_map<std::string, std::string> expected_params = {};
  17450. EXPECT_EQ(request.path_params, expected_params);
  17451. }
  17452. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17453. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17454. // calling thread's stack on a long enough path for a quantified pattern;
  17455. // RegexMatcher must refuse to run regex matching on paths beyond
  17456. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17457. detail::RegexMatcher matcher("/files/(.*)");
  17458. Request within_limit;
  17459. within_limit.path = "/files/" + std::string(10, 'A');
  17460. EXPECT_TRUE(matcher.match(within_limit));
  17461. Request over_limit;
  17462. over_limit.path =
  17463. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17464. EXPECT_FALSE(matcher.match(over_limit));
  17465. }
  17466. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17467. Server svr;
  17468. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. auto port = svr.bind_to_any_port(HOST);
  17472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17473. auto se = detail::scope_exit([&] {
  17474. svr.stop();
  17475. thread.join();
  17476. ASSERT_FALSE(svr.is_running());
  17477. });
  17478. svr.wait_until_ready();
  17479. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17480. // request URI limit; this used to be able to crash the process.
  17481. std::string path =
  17482. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17483. std::string req = "GET " + path +
  17484. " HTTP/1.1\r\n"
  17485. "Host: " +
  17486. std::string(HOST) + ":" + std::to_string(port) +
  17487. "\r\n"
  17488. "Connection: close\r\n"
  17489. "\r\n";
  17490. std::string response;
  17491. ASSERT_TRUE(send_request(5, req, &response, port));
  17492. EXPECT_NE(std::string::npos, response.find("404"));
  17493. }
  17494. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17495. Server svr;
  17496. auto handler = [](const Request & /*req*/, Response &res) {
  17497. res.set_content("hit", "text/plain");
  17498. };
  17499. // No regex metacharacter, so this one is compared literally
  17500. svr.Get("/literal/route", handler);
  17501. // '.' is a regex metacharacter, so this one must keep regex semantics
  17502. svr.Get("/a.c", handler);
  17503. auto port = svr.bind_to_any_port(HOST);
  17504. std::thread t([&]() { svr.listen_after_bind(); });
  17505. auto se = detail::scope_exit([&] {
  17506. svr.stop();
  17507. t.join();
  17508. ASSERT_FALSE(svr.is_running());
  17509. });
  17510. svr.wait_until_ready();
  17511. Client cli(HOST, port);
  17512. struct {
  17513. const char *path;
  17514. int status;
  17515. } cases[] = {
  17516. {"/literal/route", StatusCode::OK_200},
  17517. {"/literal/routes", StatusCode::NotFound_404},
  17518. {"/literal/rout", StatusCode::NotFound_404},
  17519. {"/abc", StatusCode::OK_200},
  17520. {"/a.c", StatusCode::OK_200},
  17521. };
  17522. for (const auto &x : cases) {
  17523. auto res = cli.Get(x.path);
  17524. ASSERT_TRUE(res) << x.path;
  17525. EXPECT_EQ(x.status, res->status) << x.path;
  17526. }
  17527. }
  17528. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17529. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17530. // from exhausting the stack, so it must only constrain routes that actually
  17531. // run a regular expression. A literal route is matched by comparison and
  17532. // stays usable at any length.
  17533. Server svr;
  17534. const std::string pattern =
  17535. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17536. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17537. res.set_content("hit", "text/plain");
  17538. });
  17539. auto port = svr.bind_to_any_port(HOST);
  17540. std::thread t([&]() { svr.listen_after_bind(); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. Client cli(HOST, port);
  17548. auto res = cli.Get(pattern);
  17549. ASSERT_TRUE(res);
  17550. EXPECT_EQ(StatusCode::OK_200, res->status);
  17551. }
  17552. TEST(ParseUrlTest, VariousPatterns) {
  17553. {
  17554. detail::UrlComponents uc;
  17555. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17556. EXPECT_EQ("http", uc.scheme);
  17557. EXPECT_EQ("example.com", uc.host);
  17558. EXPECT_EQ("8080", uc.port);
  17559. EXPECT_EQ("/path", uc.path);
  17560. EXPECT_EQ("?q=1", uc.query);
  17561. }
  17562. {
  17563. detail::UrlComponents uc;
  17564. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17565. EXPECT_EQ("https", uc.scheme);
  17566. EXPECT_EQ("example.com", uc.host);
  17567. EXPECT_TRUE(uc.port.empty());
  17568. EXPECT_EQ("/path", uc.path);
  17569. }
  17570. {
  17571. detail::UrlComponents uc;
  17572. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17573. EXPECT_EQ("::1", uc.host);
  17574. EXPECT_EQ("8080", uc.port);
  17575. EXPECT_EQ("/path", uc.path);
  17576. }
  17577. {
  17578. detail::UrlComponents uc;
  17579. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17580. }
  17581. {
  17582. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17583. // the path while the connection still targets the bracketed host.
  17584. detail::UrlComponents uc;
  17585. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17586. }
  17587. {
  17588. detail::UrlComponents uc;
  17589. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17590. }
  17591. {
  17592. detail::UrlComponents uc;
  17593. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17594. EXPECT_EQ("::1", uc.host);
  17595. EXPECT_TRUE(uc.port.empty());
  17596. EXPECT_EQ("/path", uc.path);
  17597. }
  17598. {
  17599. detail::UrlComponents uc;
  17600. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17601. EXPECT_TRUE(uc.scheme.empty());
  17602. EXPECT_EQ("example.com", uc.host);
  17603. EXPECT_EQ("/path", uc.path);
  17604. EXPECT_EQ("?q=1", uc.query);
  17605. }
  17606. {
  17607. detail::UrlComponents uc;
  17608. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17609. EXPECT_TRUE(uc.host.empty());
  17610. EXPECT_EQ("/path", uc.path);
  17611. EXPECT_EQ("?q=1", uc.query);
  17612. }
  17613. {
  17614. detail::UrlComponents uc;
  17615. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17616. EXPECT_EQ("example.com", uc.host);
  17617. EXPECT_EQ("8080", uc.port);
  17618. }
  17619. {
  17620. // Unix socket path — must not be parsed as host
  17621. detail::UrlComponents uc;
  17622. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17623. EXPECT_TRUE(uc.host.empty());
  17624. }
  17625. {
  17626. detail::UrlComponents uc;
  17627. ASSERT_TRUE(detail::parse_url("", uc));
  17628. EXPECT_TRUE(uc.host.empty());
  17629. EXPECT_TRUE(uc.path.empty());
  17630. }
  17631. {
  17632. detail::UrlComponents uc;
  17633. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17634. }
  17635. {
  17636. detail::UrlComponents uc;
  17637. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17638. }
  17639. {
  17640. // Accepted by parse_url; callers restrict to http/https
  17641. detail::UrlComponents uc;
  17642. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17643. EXPECT_EQ("ftp", uc.scheme);
  17644. }
  17645. {
  17646. detail::UrlComponents uc;
  17647. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17648. }
  17649. {
  17650. detail::UrlComponents uc;
  17651. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17652. }
  17653. }
  17654. TEST(ParseUrlTest, FragmentHandling) {
  17655. {
  17656. detail::UrlComponents uc;
  17657. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17658. EXPECT_EQ("/path", uc.path);
  17659. EXPECT_TRUE(uc.query.empty());
  17660. }
  17661. {
  17662. detail::UrlComponents uc;
  17663. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17664. EXPECT_TRUE(uc.path.empty());
  17665. EXPECT_TRUE(uc.query.empty());
  17666. }
  17667. }
  17668. TEST(ParseUrlTest, UserinfoHandling) {
  17669. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17670. // parsers would see evil.com as the host.
  17671. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17672. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17673. for (auto url : urls) {
  17674. detail::UrlComponents uc;
  17675. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17676. }
  17677. }
  17678. TEST(ParseUrlTest, IPv6EdgeCases) {
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17682. EXPECT_TRUE(uc.scheme.empty());
  17683. EXPECT_EQ("::1", uc.host);
  17684. EXPECT_EQ("8080", uc.port);
  17685. }
  17686. {
  17687. // Zone ID '%25' is not in [a-fA-F0-9:]
  17688. detail::UrlComponents uc;
  17689. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17690. }
  17691. }
  17692. TEST(ParseUrlTest, SchemeEdgeCases) {
  17693. {
  17694. detail::UrlComponents uc;
  17695. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17696. }
  17697. {
  17698. detail::UrlComponents uc;
  17699. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17700. }
  17701. {
  17702. detail::UrlComponents uc;
  17703. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17704. }
  17705. }
  17706. TEST(ParseUrlTest, PortEdgeCases) {
  17707. {
  17708. detail::UrlComponents uc;
  17709. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17710. EXPECT_TRUE(uc.port.empty());
  17711. EXPECT_EQ("/path", uc.path);
  17712. }
  17713. {
  17714. // parse_url accepts any port string; validation is done by parse_port
  17715. detail::UrlComponents uc;
  17716. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17717. EXPECT_EQ("abc", uc.port);
  17718. }
  17719. }
  17720. TEST(ParseUrlTest, WebSocketPatterns) {
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17724. EXPECT_EQ("ws", uc.scheme);
  17725. EXPECT_EQ("echo.example.com", uc.host);
  17726. EXPECT_EQ("8080", uc.port);
  17727. EXPECT_EQ("/ws", uc.path);
  17728. }
  17729. {
  17730. detail::UrlComponents uc;
  17731. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17732. EXPECT_EQ("wss", uc.scheme);
  17733. EXPECT_EQ("echo.example.com", uc.host);
  17734. EXPECT_TRUE(uc.port.empty());
  17735. EXPECT_EQ("/ws", uc.path);
  17736. }
  17737. }
  17738. TEST(ParseUrlTest, QueryOnly) {
  17739. detail::UrlComponents uc;
  17740. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17741. EXPECT_TRUE(uc.host.empty());
  17742. EXPECT_TRUE(uc.path.empty());
  17743. EXPECT_EQ("?q=1&r=2", uc.query);
  17744. }
  17745. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17746. detail::UrlComponents uc;
  17747. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17748. EXPECT_TRUE(uc.scheme.empty());
  17749. EXPECT_EQ("example.com", uc.host);
  17750. EXPECT_EQ("443", uc.port);
  17751. EXPECT_EQ("/path", uc.path);
  17752. }
  17753. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17754. // If ipv6 regex working, regex match codepath is taken.
  17755. // else port will default to 80 in Client impl
  17756. int clientImplMagicPort = 80;
  17757. int port = 4321;
  17758. // above ports must be different to avoid false negative
  17759. EXPECT_NE(clientImplMagicPort, port);
  17760. std::string ipV6TestURL = "http://[ff06::c3]";
  17761. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17762. CLIENT_PRIVATE_KEY_FILE);
  17763. EXPECT_EQ(cli.port(), port);
  17764. }
  17765. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17766. auto file_path = "./www/dir/index.html";
  17767. auto dir_path = "./www/dir";
  17768. detail::FileStat stat_file(file_path);
  17769. EXPECT_TRUE(stat_file.is_file());
  17770. EXPECT_FALSE(stat_file.is_dir());
  17771. detail::FileStat stat_dir(dir_path);
  17772. EXPECT_FALSE(stat_dir.is_file());
  17773. EXPECT_TRUE(stat_dir.is_dir());
  17774. }
  17775. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17776. // IPv4 with default HTTP port (80)
  17777. EXPECT_EQ("example.com",
  17778. detail::make_host_and_port_string("example.com", 80, false));
  17779. // IPv4 with default HTTPS port (443)
  17780. EXPECT_EQ("example.com",
  17781. detail::make_host_and_port_string("example.com", 443, true));
  17782. // IPv4 with non-default HTTP port
  17783. EXPECT_EQ("example.com:8080",
  17784. detail::make_host_and_port_string("example.com", 8080, false));
  17785. // IPv4 with non-default HTTPS port
  17786. EXPECT_EQ("example.com:8443",
  17787. detail::make_host_and_port_string("example.com", 8443, true));
  17788. // IPv6 with default HTTP port (80)
  17789. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17790. // IPv6 with default HTTPS port (443)
  17791. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17792. // IPv6 with non-default HTTP port
  17793. EXPECT_EQ("[::1]:8080",
  17794. detail::make_host_and_port_string("::1", 8080, false));
  17795. // IPv6 with non-default HTTPS port
  17796. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17797. // IPv6 full address with default port
  17798. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17799. detail::make_host_and_port_string(
  17800. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17801. // IPv6 full address with non-default port
  17802. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17803. detail::make_host_and_port_string(
  17804. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17805. // IPv6 localhost with non-default port
  17806. EXPECT_EQ("[::1]:3000",
  17807. detail::make_host_and_port_string("::1", 3000, false));
  17808. // IPv6 with zone ID (link-local address) with default port
  17809. EXPECT_EQ("[fe80::1%eth0]",
  17810. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17811. // IPv6 with zone ID (link-local address) with non-default port
  17812. EXPECT_EQ("[fe80::1%eth0]:8080",
  17813. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17814. // Edge case: Port 443 with is_ssl=false (should add port)
  17815. EXPECT_EQ("example.com:443",
  17816. detail::make_host_and_port_string("example.com", 443, false));
  17817. // Edge case: Port 80 with is_ssl=true (should add port)
  17818. EXPECT_EQ("example.com:80",
  17819. detail::make_host_and_port_string("example.com", 80, true));
  17820. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17821. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17822. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17823. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17824. // Security fix: Already bracketed IPv6 should not get double brackets
  17825. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17826. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17827. EXPECT_EQ("[::1]:8080",
  17828. detail::make_host_and_port_string("[::1]", 8080, false));
  17829. EXPECT_EQ("[2001:db8::1]:8080",
  17830. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17831. EXPECT_EQ("[fe80::1%eth0]",
  17832. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17833. EXPECT_EQ("[fe80::1%eth0]:8080",
  17834. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17835. // Edge case: Empty host (should return as-is)
  17836. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17837. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17838. // This is a known limitation but shouldn't crash
  17839. EXPECT_EQ("[host:name]",
  17840. detail::make_host_and_port_string("host:name", 80, false));
  17841. // Port number edge cases (no validation, but should not crash)
  17842. EXPECT_EQ("example.com:0",
  17843. detail::make_host_and_port_string("example.com", 0, false));
  17844. EXPECT_EQ("example.com:-1",
  17845. detail::make_host_and_port_string("example.com", -1, false));
  17846. EXPECT_EQ("example.com:65535",
  17847. detail::make_host_and_port_string("example.com", 65535, false));
  17848. EXPECT_EQ("example.com:65536",
  17849. detail::make_host_and_port_string("example.com", 65536, false));
  17850. }
  17851. #ifdef CPPHTTPLIB_SSL_ENABLED
  17852. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17853. httplib::SSLClient cli("roblox.com", 443);
  17854. cli.set_follow_location(true);
  17855. auto res = cli.Get("/");
  17856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17857. EXPECT_EQ(StatusCode::OK_200, res->status);
  17858. }
  17859. #endif
  17860. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17861. Server svr;
  17862. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17863. EXPECT_EQ(res.status, 400);
  17864. });
  17865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17866. auto se = detail::scope_exit([&] {
  17867. svr.stop();
  17868. thread.join();
  17869. ASSERT_FALSE(svr.is_running());
  17870. });
  17871. svr.wait_until_ready();
  17872. Client cli(HOST, PORT);
  17873. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17874. }
  17875. TEST(InvalidHeaderCharsTest, is_field_name) {
  17876. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17877. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17878. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17879. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17880. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17881. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17882. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17883. EXPECT_FALSE(detail::fields::is_field_name(""));
  17884. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17885. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17886. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17887. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17888. }
  17889. TEST(InvalidHeaderCharsTest, is_field_value) {
  17890. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17891. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17892. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17893. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17894. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17895. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17896. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17897. EXPECT_TRUE(detail::fields::is_field_value(""));
  17898. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17899. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17900. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17901. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17902. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17903. }
  17904. TEST(InvalidHeaderCharsTest, OnServer) {
  17905. Server svr;
  17906. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17907. std::string header = "Not Set";
  17908. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17909. res.set_header(header, "value");
  17910. res.set_content("Page Content Page Content", "text/plain");
  17911. });
  17912. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17913. std::string header = "Not Set";
  17914. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17915. res.set_header("X-Test", header);
  17916. res.set_content("Page Content Page Content", "text/plain");
  17917. });
  17918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17919. auto se = detail::scope_exit([&] {
  17920. svr.stop();
  17921. thread.join();
  17922. ASSERT_FALSE(svr.is_running());
  17923. });
  17924. svr.wait_until_ready();
  17925. Client cli(HOST, PORT);
  17926. {
  17927. auto res = cli.Get(
  17928. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17930. EXPECT_EQ("Page Content Page Content", res->body);
  17931. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17932. }
  17933. {
  17934. auto res = cli.Get(
  17935. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17937. EXPECT_EQ("Page Content Page Content", res->body);
  17938. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17939. }
  17940. }
  17941. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17942. auto handled = false;
  17943. Server svr;
  17944. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17945. thread t = thread([&] { svr.listen(HOST, PORT); });
  17946. auto se = detail::scope_exit([&] {
  17947. svr.stop();
  17948. t.join();
  17949. ASSERT_FALSE(svr.is_running());
  17950. ASSERT_FALSE(handled);
  17951. });
  17952. svr.wait_until_ready();
  17953. auto req = "POST /test HTTP/1.1\r\n"
  17954. "Content-Length: x\r\n"
  17955. "\r\n";
  17956. std::string response;
  17957. ASSERT_TRUE(send_request(1, req, &response));
  17958. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17959. response.substr(0, response.find("\r\n")));
  17960. }
  17961. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17962. // case-insensitive, and a server that receives a 100-continue expectation in
  17963. // an HTTP/1.0 request MUST ignore it.
  17964. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17965. std::string response;
  17966. ASSERT_TRUE(send_request(1, req, &response, port));
  17967. *got_100 = response.find("100 Continue") != std::string::npos;
  17968. }
  17969. class ExpectTokenTest : public ::testing::Test {
  17970. protected:
  17971. void SetUp() override {
  17972. svr_.Post("/p", [](const Request &, Response &res) {
  17973. res.set_content("ok", "text/plain");
  17974. });
  17975. port_ = svr_.bind_to_any_port(HOST);
  17976. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17977. svr_.wait_until_ready();
  17978. }
  17979. void TearDown() override {
  17980. svr_.stop();
  17981. if (thread_.joinable()) { thread_.join(); }
  17982. }
  17983. std::string request(const char *version, const char *expect_value) const {
  17984. return std::string("POST /p ") + version +
  17985. "\r\n"
  17986. "Host: localhost\r\n"
  17987. "Content-Length: 2\r\n"
  17988. "Connection: close\r\n"
  17989. "Expect: " +
  17990. expect_value +
  17991. "\r\n"
  17992. "\r\n"
  17993. "hi";
  17994. }
  17995. Server svr_;
  17996. int port_ = 0;
  17997. thread thread_;
  17998. };
  17999. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18000. bool got_100 = false;
  18001. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18002. EXPECT_TRUE(got_100);
  18003. }
  18004. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18005. bool got_100 = true;
  18006. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18007. EXPECT_FALSE(got_100);
  18008. }
  18009. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18010. bool got_100 = false;
  18011. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18012. EXPECT_TRUE(got_100);
  18013. }
  18014. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18015. bool got_100 = false;
  18016. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18017. EXPECT_TRUE(got_100);
  18018. }
  18019. // `100 Continue` is sent only when the server starts reading the body, so a
  18020. // request rejected before that never invites the client to send it. The
  18021. // requests below carry the expectation but withhold the body, as a client
  18022. // waiting for `100 Continue` would.
  18023. // A POST that expects `100 Continue` and withholds its two-byte body.
  18024. static std::string expect_headers_only(const std::string &path) {
  18025. return "POST " + path +
  18026. " HTTP/1.1\r\n"
  18027. "Host: localhost\r\n"
  18028. "Content-Length: 2\r\n"
  18029. "Expect: 100-continue\r\n"
  18030. "\r\n";
  18031. }
  18032. class ExpectLazyContinueTest : public ::testing::Test {
  18033. protected:
  18034. void SetUp() override {
  18035. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18036. if (req.path == "/pre-routing") {
  18037. res.status = StatusCode::Unauthorized_401;
  18038. return Server::HandlerResponse::Handled;
  18039. }
  18040. return Server::HandlerResponse::Unhandled;
  18041. });
  18042. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18043. if (req.matched_route == "/pre-request") {
  18044. res.status = StatusCode::Forbidden_403;
  18045. return Server::HandlerResponse::Handled;
  18046. }
  18047. return Server::HandlerResponse::Unhandled;
  18048. });
  18049. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18050. res.set_content("ok", "text/plain");
  18051. });
  18052. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18053. res.set_content("ok", "text/plain");
  18054. });
  18055. svr_.Post("/reader-used", [](const Request &, Response &res,
  18056. const ContentReader &content_reader) {
  18057. std::string body;
  18058. content_reader([&](const char *data, size_t len) {
  18059. body.append(data, len);
  18060. return true;
  18061. });
  18062. res.set_content(body, "text/plain");
  18063. });
  18064. svr_.Post("/reader-unused",
  18065. [](const Request &, Response &res, const ContentReader &) {
  18066. res.set_content("ignored", "text/plain");
  18067. });
  18068. port_ = svr_.bind_to_any_port(HOST);
  18069. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18070. svr_.wait_until_ready();
  18071. }
  18072. void TearDown() override {
  18073. svr_.stop();
  18074. if (thread_.joinable()) { thread_.join(); }
  18075. }
  18076. // Sends `req` and reads until the server closes the connection. Returns
  18077. // false if the read had to wait for the client-side timeout instead.
  18078. bool send_until_closed(const std::string &req, std::string *resp) const {
  18079. auto start = std::chrono::steady_clock::now();
  18080. if (!send_request(3, req, resp, port_)) { return false; }
  18081. auto elapsed = std::chrono::steady_clock::now() - start;
  18082. return elapsed < std::chrono::seconds(2);
  18083. }
  18084. // The final response comes without `100 Continue`, and the server closes
  18085. // the connection since the body may or may not follow.
  18086. void expect_final_without_interim(const std::string &path,
  18087. const char *status_line) const {
  18088. std::string resp;
  18089. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18090. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18091. EXPECT_EQ(0u, resp.find(status_line));
  18092. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18093. }
  18094. Server svr_;
  18095. int port_ = 0;
  18096. thread thread_;
  18097. };
  18098. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18099. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18100. }
  18101. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18102. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18103. }
  18104. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18105. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18106. }
  18107. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18108. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18109. }
  18110. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18111. // The body follows once `100 Continue` has had time to arrive.
  18112. auto req = expect_headers_only("/reader-used");
  18113. req.insert(req.size() - 2, "Connection: close\r\n");
  18114. std::string resp;
  18115. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18116. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18117. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18118. EXPECT_NE(std::string::npos, resp.find("hi"));
  18119. }
  18120. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18121. // Large enough for the client to add `Expect: 100-continue` itself.
  18122. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18123. std::atomic<bool> body_sent{false};
  18124. Client cli(HOST, port_);
  18125. auto res = cli.Post(
  18126. "/pre-request", length,
  18127. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18128. body_sent = true;
  18129. std::string chunk(len, 'x');
  18130. sink.write(chunk.data(), chunk.size());
  18131. return true;
  18132. },
  18133. "application/octet-stream");
  18134. ASSERT_TRUE(res);
  18135. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18136. EXPECT_FALSE(body_sent);
  18137. }
  18138. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18139. Server svr;
  18140. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18141. return StatusCode::ExpectationFailed_417;
  18142. });
  18143. svr.Post("/p", [](const Request &, Response &res) {
  18144. res.set_content("ok", "text/plain");
  18145. });
  18146. auto port = svr.bind_to_any_port(HOST);
  18147. thread t = thread([&] { svr.listen_after_bind(); });
  18148. auto se = detail::scope_exit([&] {
  18149. svr.stop();
  18150. t.join();
  18151. });
  18152. svr.wait_until_ready();
  18153. std::string resp;
  18154. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18155. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18156. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18157. // Exactly one response: the route handler must not run after the 417.
  18158. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18159. }
  18160. #ifndef _WIN32
  18161. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18162. static constexpr char reject[] = "Unauthorized";
  18163. static constexpr char accept[] = "Upload accepted";
  18164. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18165. Server svr;
  18166. svr.set_expect_100_continue_handler(
  18167. [](const Request & /*req*/, Response &res) {
  18168. res.status = StatusCode::Unauthorized_401;
  18169. res.set_content(reject, "text/plain");
  18170. return res.status;
  18171. });
  18172. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18173. res.set_content(accept, "text/plain");
  18174. });
  18175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18176. auto se = detail::scope_exit([&] {
  18177. svr.stop();
  18178. thread.join();
  18179. ASSERT_FALSE(svr.is_running());
  18180. });
  18181. svr.wait_until_ready();
  18182. {
  18183. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18184. curl_easy_init(), &curl_easy_cleanup};
  18185. ASSERT_NE(curl, nullptr);
  18186. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18187. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18188. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18189. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18190. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18191. &curl_slist_free_all};
  18192. ASSERT_NE(list, nullptr);
  18193. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18194. struct read_data {
  18195. uint64_t read_size;
  18196. uint64_t total_size;
  18197. } data = {0, total_size};
  18198. using read_callback_t =
  18199. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18200. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18201. void *userdata) -> size_t {
  18202. read_data *d = (read_data *)userdata;
  18203. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18204. std::fill_n(ptr, size * nmemb, 'A');
  18205. d->read_size += size * nmemb;
  18206. return size * nmemb;
  18207. };
  18208. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18209. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18210. std::vector<char> buffer;
  18211. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18212. using write_callback_t =
  18213. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18214. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18215. void *userdata) -> size_t {
  18216. std::vector<char> *buf = (std::vector<char> *)userdata;
  18217. buf->reserve(buf->size() + size * nmemb + 1);
  18218. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18219. return size * nmemb;
  18220. };
  18221. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18222. {
  18223. const auto res = curl_easy_perform(curl.get());
  18224. ASSERT_EQ(res, CURLE_OK);
  18225. }
  18226. {
  18227. auto response_code = long{};
  18228. const auto res =
  18229. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18230. ASSERT_EQ(res, CURLE_OK);
  18231. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18232. }
  18233. {
  18234. auto dl = curl_off_t{};
  18235. const auto res =
  18236. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18237. ASSERT_EQ(res, CURLE_OK);
  18238. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18239. }
  18240. {
  18241. buffer.push_back('\0');
  18242. ASSERT_STRCASEEQ(buffer.data(), reject);
  18243. }
  18244. }
  18245. }
  18246. #endif
  18247. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18248. // Regression test for #2458.
  18249. //
  18250. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18251. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18252. // ticket can make the client socket spuriously readable during the
  18253. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18254. // the client withholds the body and then blocks reading a response that never
  18255. // comes, failing with `Failed to read connection`.
  18256. //
  18257. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18258. // within the timeout. This raw OpenSSL server deliberately never sends
  18259. // `100 Continue`; the client must still deliver the body and receive 200.
  18260. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18261. signal(SIGPIPE, SIG_IGN);
  18262. const auto port = PORT + 4;
  18263. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18264. ASSERT_NE(srv, INVALID_SOCKET);
  18265. int opt = 1;
  18266. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18267. sockaddr_in addr{};
  18268. addr.sin_family = AF_INET;
  18269. addr.sin_port = htons(static_cast<uint16_t>(port));
  18270. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18271. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18272. ASSERT_EQ(0, ::listen(srv, 1));
  18273. std::atomic<size_t> server_body_bytes{0};
  18274. auto server_thread = std::thread([&] {
  18275. sockaddr_in cli_addr{};
  18276. socklen_t cli_len = sizeof(cli_addr);
  18277. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18278. if (cli == INVALID_SOCKET) { return; }
  18279. // Bound the lifetime of the server side so a buggy client (which never
  18280. // sends the body) cannot make this thread block forever on join.
  18281. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18282. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18283. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18284. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18285. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18286. SSL *ssl = SSL_new(ctx);
  18287. SSL_set_fd(ssl, static_cast<int>(cli));
  18288. if (SSL_accept(ssl) > 0) {
  18289. // Read the request headers. Reading here also flushes the TLS 1.3
  18290. // session tickets to the client. Deliberately do NOT send
  18291. // `100 Continue`.
  18292. std::string buf;
  18293. char tmp[1024];
  18294. while (buf.find("\r\n\r\n") == std::string::npos) {
  18295. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18296. if (n <= 0) { break; }
  18297. buf.append(tmp, static_cast<size_t>(n));
  18298. }
  18299. // A correct client sends the body now; count what arrives.
  18300. auto pos = buf.find("\r\n\r\n");
  18301. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18302. while (body < 4096) {
  18303. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18304. if (n <= 0) { break; }
  18305. body += static_cast<size_t>(n);
  18306. }
  18307. server_body_bytes = body;
  18308. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18309. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18310. SSL_shutdown(ssl);
  18311. }
  18312. SSL_free(ssl);
  18313. detail::close_socket(cli);
  18314. SSL_CTX_free(ctx);
  18315. });
  18316. auto se = detail::scope_exit([&] {
  18317. server_thread.join();
  18318. detail::close_socket(srv);
  18319. });
  18320. SSLClient cli("127.0.0.1", port);
  18321. cli.enable_server_certificate_verification(false);
  18322. cli.set_connection_timeout(5, 0);
  18323. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18324. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18325. std::string body(4096, 'A');
  18326. auto res = cli.Put("/api/test", body, "application/json");
  18327. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18328. EXPECT_EQ(StatusCode::OK_200, res->status);
  18329. EXPECT_EQ(body.size(), server_body_bytes.load());
  18330. }
  18331. #endif
  18332. template <typename S, typename C>
  18333. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18334. svr.Get("/stream", [&](const Request &, Response &res) {
  18335. auto data = new std::string("01234567890123456789");
  18336. res.set_content_provider(
  18337. data->size(), "text/plain",
  18338. [&, data](size_t offset, size_t length, DataSink &sink) {
  18339. const size_t DATA_CHUNK_SIZE = 4;
  18340. const auto &d = *data;
  18341. std::this_thread::sleep_for(std::chrono::seconds(1));
  18342. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18343. return true;
  18344. },
  18345. [data](bool success) {
  18346. EXPECT_FALSE(success);
  18347. delete data;
  18348. });
  18349. });
  18350. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18351. auto i = new size_t(0);
  18352. res.set_content_provider(
  18353. "text/plain",
  18354. [i](size_t, DataSink &sink) {
  18355. if (*i < 5) {
  18356. std::this_thread::sleep_for(std::chrono::seconds(1));
  18357. sink.write("abcd", 4);
  18358. (*i)++;
  18359. } else {
  18360. sink.done();
  18361. }
  18362. return true;
  18363. },
  18364. [i](bool success) {
  18365. EXPECT_FALSE(success);
  18366. delete i;
  18367. });
  18368. });
  18369. svr.Get("/chunked", [&](const Request &, Response &res) {
  18370. auto i = new size_t(0);
  18371. res.set_chunked_content_provider(
  18372. "text/plain",
  18373. [i](size_t, DataSink &sink) {
  18374. if (*i < 5) {
  18375. std::this_thread::sleep_for(std::chrono::seconds(1));
  18376. sink.os << "abcd";
  18377. (*i)++;
  18378. } else {
  18379. sink.done();
  18380. }
  18381. return true;
  18382. },
  18383. [i](bool success) {
  18384. EXPECT_FALSE(success);
  18385. delete i;
  18386. });
  18387. });
  18388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18389. auto se = detail::scope_exit([&] {
  18390. svr.stop();
  18391. listen_thread.join();
  18392. ASSERT_FALSE(svr.is_running());
  18393. });
  18394. svr.wait_until_ready();
  18395. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18396. {
  18397. auto start = std::chrono::steady_clock::now();
  18398. auto res = cli.Get("/stream");
  18399. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18400. std::chrono::steady_clock::now() - start)
  18401. .count();
  18402. ASSERT_FALSE(res);
  18403. EXPECT_EQ(Error::Read, res.error());
  18404. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18405. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18406. }
  18407. {
  18408. auto start = std::chrono::steady_clock::now();
  18409. auto res = cli.Get("/stream_without_length");
  18410. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18411. std::chrono::steady_clock::now() - start)
  18412. .count();
  18413. ASSERT_FALSE(res);
  18414. EXPECT_EQ(Error::Read, res.error());
  18415. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18416. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18417. }
  18418. {
  18419. auto start = std::chrono::steady_clock::now();
  18420. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18421. EXPECT_EQ("abcd", string(data, data_length));
  18422. return true;
  18423. });
  18424. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18425. std::chrono::steady_clock::now() - start)
  18426. .count();
  18427. ASSERT_FALSE(res);
  18428. EXPECT_EQ(Error::Read, res.error());
  18429. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18430. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18431. }
  18432. }
  18433. TEST(MaxTimeoutTest, ContentStream) {
  18434. time_t timeout = 2000;
  18435. time_t threshold = 200;
  18436. Server svr;
  18437. Client cli("localhost", PORT);
  18438. max_timeout_test(svr, cli, timeout, threshold);
  18439. }
  18440. #ifdef CPPHTTPLIB_SSL_ENABLED
  18441. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18442. time_t timeout = 2000;
  18443. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18445. SSLClient cli("localhost", PORT);
  18446. cli.enable_server_certificate_verification(false);
  18447. max_timeout_test(svr, cli, timeout, threshold);
  18448. }
  18449. #endif
  18450. class EventDispatcher {
  18451. public:
  18452. EventDispatcher() {}
  18453. bool wait_event(DataSink *sink) {
  18454. unique_lock<mutex> lk(m_);
  18455. int id = id_;
  18456. // Wait with timeout to prevent hanging if client disconnects
  18457. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18458. [&] { return cid_ == id; })) {
  18459. return false; // Timeout occurred
  18460. }
  18461. sink->write(message_.data(), message_.size());
  18462. return true;
  18463. }
  18464. void send_event(const string &message) {
  18465. lock_guard<mutex> lk(m_);
  18466. cid_ = id_++;
  18467. message_ = message;
  18468. cv_.notify_all();
  18469. }
  18470. private:
  18471. mutex m_;
  18472. condition_variable cv_;
  18473. atomic_int id_{0};
  18474. atomic_int cid_{-1};
  18475. string message_;
  18476. };
  18477. TEST(ClientInThreadTest, Issue2068) {
  18478. EventDispatcher ed;
  18479. Server svr;
  18480. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18481. res.set_chunked_content_provider("text/event-stream",
  18482. [&](size_t /*offset*/, DataSink &sink) {
  18483. return ed.wait_event(&sink);
  18484. });
  18485. });
  18486. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18487. svr.wait_until_ready();
  18488. thread event_thread([&] {
  18489. int id = 0;
  18490. while (svr.is_running()) {
  18491. this_thread::sleep_for(chrono::milliseconds(500));
  18492. std::stringstream ss;
  18493. ss << "data: " << id << "\n\n";
  18494. ed.send_event(ss.str());
  18495. id++;
  18496. }
  18497. });
  18498. auto se = detail::scope_exit([&] {
  18499. svr.stop();
  18500. listen_thread.join();
  18501. event_thread.join();
  18502. ASSERT_FALSE(svr.is_running());
  18503. });
  18504. {
  18505. auto client = detail::make_unique<Client>(HOST, PORT);
  18506. client->set_read_timeout(std::chrono::minutes(10));
  18507. std::atomic<bool> stop{false};
  18508. std::thread t([&] {
  18509. client->Get("/event1",
  18510. [&](const char *, size_t) -> bool { return !stop; });
  18511. });
  18512. std::this_thread::sleep_for(std::chrono::seconds(2));
  18513. stop = true;
  18514. client->stop();
  18515. t.join();
  18516. // Reset client after thread has finished
  18517. client.reset();
  18518. }
  18519. }
  18520. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18521. auto handled = false;
  18522. Server svr;
  18523. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18525. auto se = detail::scope_exit([&] {
  18526. svr.stop();
  18527. t.join();
  18528. ASSERT_FALSE(svr.is_running());
  18529. ASSERT_FALSE(handled);
  18530. });
  18531. svr.wait_until_ready();
  18532. // Two Content-Length headers with different values — must be rejected
  18533. auto req = "POST /test HTTP/1.1\r\n"
  18534. "Content-Length: 5\r\n"
  18535. "Content-Length: 10\r\n"
  18536. "\r\n"
  18537. "hello";
  18538. std::string response;
  18539. ASSERT_TRUE(send_request(1, req, &response));
  18540. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18541. response.substr(0, response.find("\r\n")));
  18542. }
  18543. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18544. auto handled = false;
  18545. Server svr;
  18546. svr.Post("/test", [&](const Request &, Response &res) {
  18547. handled = true;
  18548. res.set_content("ok", "text/plain");
  18549. });
  18550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. t.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. ASSERT_TRUE(handled);
  18556. });
  18557. svr.wait_until_ready();
  18558. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18559. auto req = "POST /test HTTP/1.1\r\n"
  18560. "Host: localhost\r\n"
  18561. "Content-Length: 5\r\n"
  18562. "Content-Length: 5\r\n"
  18563. "\r\n"
  18564. "hello";
  18565. std::string response;
  18566. ASSERT_TRUE(send_request(1, req, &response));
  18567. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18568. }
  18569. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18570. Server svr;
  18571. svr.Get("/test", [](const Request &, Response &res) {
  18572. res.set_content("ok", "text/plain");
  18573. });
  18574. auto port = svr.bind_to_any_port(HOST);
  18575. thread t = thread([&] { svr.listen_after_bind(); });
  18576. auto se = detail::scope_exit([&] {
  18577. svr.stop();
  18578. t.join();
  18579. ASSERT_FALSE(svr.is_running());
  18580. });
  18581. svr.wait_until_ready();
  18582. auto status_line = [&](const std::string &host_lines) {
  18583. std::string res;
  18584. send_request(
  18585. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18586. &res, port);
  18587. return res.substr(0, res.find("\r\n"));
  18588. };
  18589. const char *accepted[] = {
  18590. "Host: localhost\r\n",
  18591. "Host: a.example:8080\r\n",
  18592. "Host: my_service\r\n",
  18593. "Host: [::1]:8080\r\n",
  18594. "Host: [fe80::1%25eth0]\r\n",
  18595. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18596. };
  18597. for (auto host_lines : accepted) {
  18598. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18599. }
  18600. const char *rejected[] = {
  18601. "Host: a.example\r\nHost: b.example\r\n",
  18602. "Host: a.example\r\nHost: a.example\r\n",
  18603. "Host: a@b.example\r\n",
  18604. "Host: a.example/b\r\n",
  18605. "Host: a.example\\b\r\n",
  18606. "Host: a.example?b\r\n",
  18607. "Host: a.example#b\r\n",
  18608. "Host: a.example b.example\r\n",
  18609. };
  18610. for (auto host_lines : rejected) {
  18611. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18612. << host_lines;
  18613. }
  18614. }
  18615. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18616. Server svr;
  18617. svr.Get("/", [](const Request &req, Response &res) {
  18618. EXPECT_EQ(2U, req.trailers.size());
  18619. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18620. // Denied
  18621. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18622. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18623. // Accepted
  18624. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18625. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18626. EXPECT_TRUE(req.has_trailer("X-World"));
  18627. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. });
  18636. svr.wait_until_ready();
  18637. const std::string req = "GET / HTTP/1.1\r\n"
  18638. "Transfer-Encoding: chunked\r\n"
  18639. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18640. "\r\n"
  18641. "0\r\n"
  18642. "Content-Length: 10\r\n"
  18643. "Host: internal.local\r\n"
  18644. "Content-Type: malicious/content\r\n"
  18645. "Cookie: any\r\n"
  18646. "Set-Cookie: any\r\n"
  18647. "X-Forwarded-For: attacker.com\r\n"
  18648. "X-Real-Ip: 1.1.1.1\r\n"
  18649. "X-Hello: hello\r\n"
  18650. "X-World: world\r\n"
  18651. "\r\n";
  18652. std::string res;
  18653. ASSERT_TRUE(send_request(1, req, &res));
  18654. }
  18655. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18656. // several field lines, and the combined value is what has to be parsed. A
  18657. // Trailer field split across lines therefore declares every name it lists;
  18658. // reading only the first line silently drops the trailers the later lines
  18659. // declare. The prohibited-trailer filter still applies to every line.
  18660. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18661. Server svr;
  18662. size_t observed_trailer_count = 0;
  18663. std::string observed_hello;
  18664. std::string observed_world;
  18665. bool observed_content_length = true;
  18666. svr.Get("/", [&](const Request &req, Response &res) {
  18667. observed_trailer_count = req.trailers.size();
  18668. observed_hello = req.get_trailer_value("X-Hello");
  18669. observed_world = req.get_trailer_value("X-World");
  18670. observed_content_length = req.has_trailer("Content-Length");
  18671. res.set_content("ok", "text/plain");
  18672. });
  18673. auto port = svr.bind_to_any_port(HOST);
  18674. thread t = thread([&]() { svr.listen_after_bind(); });
  18675. auto se = detail::scope_exit([&] {
  18676. svr.stop();
  18677. t.join();
  18678. ASSERT_FALSE(svr.is_running());
  18679. });
  18680. svr.wait_until_ready();
  18681. const std::string req = "GET / HTTP/1.1\r\n"
  18682. "Host: localhost\r\n"
  18683. "Transfer-Encoding: chunked\r\n"
  18684. "Trailer: X-Hello\r\n"
  18685. "Trailer: X-World, Content-Length\r\n"
  18686. "\r\n"
  18687. "0\r\n"
  18688. "X-Hello: hello\r\n"
  18689. "X-World: world\r\n"
  18690. "Content-Length: 10\r\n"
  18691. "\r\n";
  18692. std::string res;
  18693. ASSERT_TRUE(send_request(1, req, &res, port));
  18694. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18695. // Accepted: both field lines contribute to the declared set
  18696. EXPECT_EQ(2U, observed_trailer_count);
  18697. EXPECT_EQ(observed_hello, "hello");
  18698. EXPECT_EQ(observed_world, "world");
  18699. // Denied: a prohibited name stays prohibited on a later field line
  18700. EXPECT_FALSE(observed_content_length);
  18701. }
  18702. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18703. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18704. // unbounded run of fields that are never declared, because the counter would
  18705. // only advance for declared fields.
  18706. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18707. Server svr;
  18708. bool handler_called = false;
  18709. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18710. handler_called = true;
  18711. res.set_content("ok", "text/plain");
  18712. });
  18713. auto port = svr.bind_to_any_port(HOST);
  18714. thread t = thread([&]() { svr.listen_after_bind(); });
  18715. auto se = detail::scope_exit([&] {
  18716. svr.stop();
  18717. t.join();
  18718. ASSERT_FALSE(svr.is_running());
  18719. });
  18720. svr.wait_until_ready();
  18721. // Declare nothing, then send far more undeclared trailer fields than the
  18722. // header-count limit. Parsing must stop and reject the request rather than
  18723. // read every line.
  18724. std::string req = "GET / HTTP/1.1\r\n"
  18725. "Transfer-Encoding: chunked\r\n"
  18726. "\r\n"
  18727. "0\r\n";
  18728. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18729. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18730. }
  18731. req += "\r\n";
  18732. std::string res;
  18733. ASSERT_TRUE(send_request(1, req, &res, port));
  18734. // The request is rejected before the handler runs.
  18735. EXPECT_FALSE(handler_called);
  18736. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18737. }
  18738. // The set of declared trailer names is capped so a peer cannot grow it without
  18739. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18740. // declared past the cap is not honored, even if the field is actually sent.
  18741. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18742. Server svr;
  18743. // One name inside the cap and one past it, so the test tracks the cap rather
  18744. // than a fixed count.
  18745. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18746. const std::string within_cap_name = "X-T-0";
  18747. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18748. bool observed_within_cap = false;
  18749. bool observed_past_cap = false;
  18750. svr.Get("/", [&](const Request &req, Response &res) {
  18751. observed_within_cap = req.has_trailer(within_cap_name);
  18752. observed_past_cap = req.has_trailer(past_cap_name);
  18753. res.set_content("ok", "text/plain");
  18754. });
  18755. auto port = svr.bind_to_any_port(HOST);
  18756. thread t = thread([&]() { svr.listen_after_bind(); });
  18757. auto se = detail::scope_exit([&] {
  18758. svr.stop();
  18759. t.join();
  18760. ASSERT_FALSE(svr.is_running());
  18761. });
  18762. svr.wait_until_ready();
  18763. // Declare more trailer names than the cap in a single Trailer field, then
  18764. // actually send the first (within the cap) and the last (past it).
  18765. std::string trailer_decl = "Trailer: ";
  18766. for (int i = 0; i < declared_count; i++) {
  18767. if (i != 0) { trailer_decl += ", "; }
  18768. trailer_decl += "X-T-" + std::to_string(i);
  18769. }
  18770. trailer_decl += "\r\n";
  18771. const std::string req = "GET / HTTP/1.1\r\n"
  18772. "Host: localhost\r\n"
  18773. "Transfer-Encoding: chunked\r\n" +
  18774. trailer_decl +
  18775. "\r\n"
  18776. "0\r\n" +
  18777. within_cap_name + ": a\r\n" + past_cap_name +
  18778. ": b\r\n"
  18779. "\r\n";
  18780. std::string res;
  18781. ASSERT_TRUE(send_request(1, req, &res, port));
  18782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18783. // A name within the cap is honored; one declared past the cap is dropped.
  18784. EXPECT_TRUE(observed_within_cap);
  18785. EXPECT_FALSE(observed_past_cap);
  18786. }
  18787. // A direct client that is not listed in trusted_proxies must not be able to
  18788. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18789. // the peer address on the actual TCP connection determines whether the
  18790. // header is honored.
  18791. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18792. Server svr;
  18793. // Deliberately does NOT include the loopback address the test client
  18794. // actually connects from, so the direct connection is not a trusted proxy.
  18795. svr.set_trusted_proxies({"203.0.113.66"});
  18796. std::string observed_remote_addr;
  18797. svr.Get("/ip", [&](const Request &req, Response &res) {
  18798. observed_remote_addr = req.remote_addr;
  18799. res.set_content("ok", "text/plain");
  18800. });
  18801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18802. auto se = detail::scope_exit([&] {
  18803. svr.stop();
  18804. t.join();
  18805. ASSERT_FALSE(svr.is_running());
  18806. });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18811. EXPECT_EQ(StatusCode::OK_200, res->status);
  18812. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18813. // ignored entirely and the real connection-level address retained.
  18814. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18815. observed_remote_addr == "127.0.0.1");
  18816. }
  18817. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18818. Server svr;
  18819. std::string observed_remote_addr;
  18820. std::string observed_xff;
  18821. svr.Get("/ip", [&](const Request &req, Response &res) {
  18822. observed_remote_addr = req.remote_addr;
  18823. observed_xff = req.get_header_value("X-Forwarded-For");
  18824. res.set_content("ok", "text/plain");
  18825. });
  18826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18827. auto se = detail::scope_exit([&] {
  18828. svr.stop();
  18829. t.join();
  18830. ASSERT_FALSE(svr.is_running());
  18831. });
  18832. svr.wait_until_ready();
  18833. Client cli(HOST, PORT);
  18834. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18836. EXPECT_EQ(StatusCode::OK_200, res->status);
  18837. EXPECT_EQ(observed_xff, "203.0.113.66");
  18838. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18839. observed_remote_addr == "127.0.0.1");
  18840. }
  18841. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18842. Server svr;
  18843. svr.set_trusted_proxies({"203.0.113.66"});
  18844. std::string observed_remote_addr;
  18845. std::string observed_xff;
  18846. svr.Get("/ip", [&](const Request &req, Response &res) {
  18847. observed_remote_addr = req.remote_addr;
  18848. observed_xff = req.get_header_value("X-Forwarded-For");
  18849. res.set_content("ok", "text/plain");
  18850. });
  18851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18852. auto se = detail::scope_exit([&] {
  18853. svr.stop();
  18854. t.join();
  18855. ASSERT_FALSE(svr.is_running());
  18856. });
  18857. svr.wait_until_ready();
  18858. Client cli(HOST, PORT);
  18859. auto res = cli.Get("/ip");
  18860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18861. EXPECT_EQ(StatusCode::OK_200, res->status);
  18862. EXPECT_EQ(observed_xff, "");
  18863. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18864. observed_remote_addr == "127.0.0.1");
  18865. }
  18866. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18867. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18868. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18869. Server svr;
  18870. svr.set_trusted_proxies({"127.0.0.1"});
  18871. svr.Get("/ip", [](const Request &req, Response &res) {
  18872. res.set_content(req.remote_addr, "text/plain");
  18873. });
  18874. auto port = svr.bind_to_any_port("::");
  18875. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18876. thread t = thread([&] { svr.listen_after_bind(); });
  18877. auto se = detail::scope_exit([&] {
  18878. svr.stop();
  18879. t.join();
  18880. ASSERT_FALSE(svr.is_running());
  18881. });
  18882. svr.wait_until_ready();
  18883. Client cli("127.0.0.1", port);
  18884. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18886. EXPECT_EQ("198.51.100.23", res->body);
  18887. }
  18888. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18889. Server svr;
  18890. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18891. svr.Get("/ip", [](const Request &req, Response &res) {
  18892. res.set_content(req.remote_addr, "text/plain");
  18893. });
  18894. auto port = svr.bind_to_any_port(HOST);
  18895. ASSERT_GT(port, 0);
  18896. thread t = thread([&] { svr.listen_after_bind(); });
  18897. auto se = detail::scope_exit([&] {
  18898. svr.stop();
  18899. t.join();
  18900. ASSERT_FALSE(svr.is_running());
  18901. });
  18902. svr.wait_until_ready();
  18903. Client cli(HOST, port);
  18904. auto res = cli.Get(
  18905. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18907. EXPECT_EQ("198.51.100.23", res->body);
  18908. }
  18909. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18910. Server svr;
  18911. // Include the loopback address the test client actually connects from, so
  18912. // the direct connection itself is recognized as the trusted proxy hop.
  18913. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18914. std::string observed_remote_addr;
  18915. std::string observed_xff;
  18916. svr.Get("/ip", [&](const Request &req, Response &res) {
  18917. observed_remote_addr = req.remote_addr;
  18918. observed_xff = req.get_header_value("X-Forwarded-For");
  18919. res.set_content("ok", "text/plain");
  18920. });
  18921. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. Client cli(HOST, PORT);
  18929. auto res = cli.Get(
  18930. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18932. EXPECT_EQ(StatusCode::OK_200, res->status);
  18933. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18934. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18935. }
  18936. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18937. Server svr;
  18938. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18939. std::string observed_remote_addr;
  18940. std::string observed_xff;
  18941. svr.Get("/ip", [&](const Request &req, Response &res) {
  18942. observed_remote_addr = req.remote_addr;
  18943. observed_xff = req.get_header_value("X-Forwarded-For");
  18944. res.set_content("ok", "text/plain");
  18945. });
  18946. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18947. auto se = detail::scope_exit([&] {
  18948. svr.stop();
  18949. t.join();
  18950. ASSERT_FALSE(svr.is_running());
  18951. });
  18952. svr.wait_until_ready();
  18953. Client cli(HOST, PORT);
  18954. auto res = cli.Get(
  18955. "/ip",
  18956. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18958. EXPECT_EQ(StatusCode::OK_200, res->status);
  18959. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18960. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18961. }
  18962. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18963. Server svr;
  18964. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18965. std::string observed_remote_addr;
  18966. std::string observed_xff;
  18967. svr.Get("/ip", [&](const Request &req, Response &res) {
  18968. observed_remote_addr = req.remote_addr;
  18969. observed_xff = req.get_header_value("X-Forwarded-For");
  18970. res.set_content("ok", "text/plain");
  18971. });
  18972. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18973. auto se = detail::scope_exit([&] {
  18974. svr.stop();
  18975. t.join();
  18976. ASSERT_FALSE(svr.is_running());
  18977. });
  18978. svr.wait_until_ready();
  18979. Client cli(HOST, PORT);
  18980. auto res = cli.Get(
  18981. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18983. EXPECT_EQ(StatusCode::OK_200, res->status);
  18984. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18985. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18986. // and must not be selected.
  18987. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18988. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18989. }
  18990. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18991. Server svr;
  18992. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18993. std::string observed_remote_addr;
  18994. svr.Get("/ip", [&](const Request &req, Response &res) {
  18995. observed_remote_addr = req.remote_addr;
  18996. res.set_content("ok", "text/plain");
  18997. });
  18998. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18999. auto se = detail::scope_exit([&] {
  19000. svr.stop();
  19001. t.join();
  19002. ASSERT_FALSE(svr.is_running());
  19003. });
  19004. svr.wait_until_ready();
  19005. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19006. // a forged address and the trusted proxy's own address; the forged value must
  19007. // not win over the address the trusted proxy actually recorded.
  19008. Client cli(HOST, PORT);
  19009. auto res = cli.Get(
  19010. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19012. EXPECT_EQ(StatusCode::OK_200, res->status);
  19013. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19014. }
  19015. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19016. Server svr;
  19017. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19018. std::string observed_remote_addr;
  19019. std::string observed_xff;
  19020. svr.Get("/ip", [&](const Request &req, Response &res) {
  19021. observed_remote_addr = req.remote_addr;
  19022. observed_xff = req.get_header_value("X-Forwarded-For");
  19023. res.set_content("ok", "text/plain");
  19024. });
  19025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19026. auto se = detail::scope_exit([&] {
  19027. svr.stop();
  19028. t.join();
  19029. ASSERT_FALSE(svr.is_running());
  19030. });
  19031. svr.wait_until_ready();
  19032. Client cli(HOST, PORT);
  19033. auto res = cli.Get(
  19034. "/ip",
  19035. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19037. EXPECT_EQ(StatusCode::OK_200, res->status);
  19038. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19039. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19040. }
  19041. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19042. Server svr;
  19043. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19044. std::string observed_remote_addr;
  19045. std::string observed_xff;
  19046. svr.Get("/ip", [&](const Request &req, Response &res) {
  19047. observed_remote_addr = req.remote_addr;
  19048. observed_xff = req.get_header_value("X-Forwarded-For");
  19049. res.set_content("ok", "text/plain");
  19050. });
  19051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19052. auto se = detail::scope_exit([&] {
  19053. svr.stop();
  19054. t.join();
  19055. ASSERT_FALSE(svr.is_running());
  19056. });
  19057. svr.wait_until_ready();
  19058. std::string raw_req =
  19059. "GET /ip HTTP/1.1\r\n"
  19060. "Host: localhost\r\n"
  19061. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19062. "Connection: close\r\n"
  19063. "\r\n";
  19064. std::string out;
  19065. ASSERT_TRUE(send_request(5, raw_req, &out));
  19066. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19067. // Header parser trims surrounding whitespace of the header value
  19068. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19069. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19070. }
  19071. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19072. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19073. // their own X-Forwarded-For as a separate field line rather than extending the
  19074. // one the client sent, so every occurrence has to be taken into account.
  19075. // Reading only the first one hands back the address the client chose.
  19076. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19077. Server svr;
  19078. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19079. std::string observed_remote_addr;
  19080. size_t observed_xff_count = 0;
  19081. svr.Get("/ip", [&](const Request &req, Response &res) {
  19082. observed_remote_addr = req.remote_addr;
  19083. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19084. res.set_content("ok", "text/plain");
  19085. });
  19086. auto port = svr.bind_to_any_port(HOST);
  19087. thread t = thread([&]() { svr.listen_after_bind(); });
  19088. auto se = detail::scope_exit([&] {
  19089. svr.stop();
  19090. t.join();
  19091. ASSERT_FALSE(svr.is_running());
  19092. });
  19093. svr.wait_until_ready();
  19094. // The client supplies the first field line; the trusted proxy appends the
  19095. // address it observed as a second one.
  19096. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19097. "Host: localhost\r\n"
  19098. "X-Forwarded-For: 1.2.3.4\r\n"
  19099. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19100. "Connection: close\r\n"
  19101. "\r\n";
  19102. std::string out;
  19103. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19104. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19105. EXPECT_EQ(observed_xff_count, 2U);
  19106. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19107. // The same chain spread over one field line per hop derives the same client
  19108. // address, i.e. the split and the comma-joined representations agree.
  19109. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19110. "Host: localhost\r\n"
  19111. "X-Forwarded-For: 1.2.3.4\r\n"
  19112. "X-Forwarded-For: 198.51.100.23\r\n"
  19113. "X-Forwarded-For: 192.0.2.45\r\n"
  19114. "Connection: close\r\n"
  19115. "\r\n";
  19116. out.clear();
  19117. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19118. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19119. EXPECT_EQ(observed_xff_count, 3U);
  19120. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19121. }
  19122. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19123. // crash the server (it used to call front() on an empty vector inside
  19124. // get_client_ip). The connection-level remote address must be retained instead.
  19125. static void run_malformed_xff_test(const std::string &xff_value) {
  19126. Server svr;
  19127. svr.set_trusted_proxies({"192.0.2.45"});
  19128. std::string observed_remote_addr;
  19129. svr.Get("/ip", [&](const Request &req, Response &res) {
  19130. observed_remote_addr = req.remote_addr;
  19131. res.set_content("ok", "text/plain");
  19132. });
  19133. int port = 0;
  19134. thread t = thread([&]() {
  19135. port = svr.bind_to_any_port(HOST);
  19136. svr.listen_after_bind();
  19137. });
  19138. auto se = detail::scope_exit([&] {
  19139. svr.stop();
  19140. t.join();
  19141. ASSERT_FALSE(svr.is_running());
  19142. });
  19143. svr.wait_until_ready();
  19144. Client cli(HOST, port);
  19145. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19147. EXPECT_EQ(StatusCode::OK_200, res->status);
  19148. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19149. observed_remote_addr == "127.0.0.1");
  19150. }
  19151. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19152. run_malformed_xff_test("");
  19153. }
  19154. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19155. run_malformed_xff_test(",");
  19156. }
  19157. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19158. run_malformed_xff_test(", , ,");
  19159. }
  19160. // The same rule applies to Accept: a request whose acceptable types are spread
  19161. // over several field lines must be negotiated against all of them.
  19162. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19163. // case-insensitive connection options. Comparing the whole field value against
  19164. // one option misses a client that sends several of them, and misses every
  19165. // casing but the one written in the comparison.
  19166. //
  19167. // Sends req, reads the response, then reuses the same socket for a second
  19168. // request to find out whether the server kept the connection.
  19169. static void probe_connection_reuse(int port, const std::string &req,
  19170. bool *announced_close, bool *reusable) {
  19171. auto error = Error::Success;
  19172. auto sock = detail::create_client_socket(
  19173. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19174. /*connection_timeout_sec=*/5, 0,
  19175. /*read_timeout_sec=*/1, 0,
  19176. /*write_timeout_sec=*/5, 0, std::string(), error);
  19177. ASSERT_NE(sock, INVALID_SOCKET);
  19178. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19179. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19180. "Host: localhost\r\n"
  19181. "Connection: close\r\n"
  19182. "\r\n";
  19183. std::string first_response;
  19184. std::string second_response;
  19185. detail::process_client_socket(
  19186. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19187. [&](Stream &strm) {
  19188. if (strm.write(req.data(), req.size()) !=
  19189. static_cast<ssize_t>(req.size())) {
  19190. return false;
  19191. }
  19192. char buf[512];
  19193. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19194. // Headers plus the two-byte body of the handler below
  19195. while (reader.getline()) {
  19196. first_response += reader.ptr();
  19197. if (first_response.find("ok") != std::string::npos) { break; }
  19198. }
  19199. if (strm.write(second.data(), second.size()) !=
  19200. static_cast<ssize_t>(second.size())) {
  19201. return true;
  19202. }
  19203. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19204. while (reader2.getline()) {
  19205. second_response += reader2.ptr();
  19206. if (second_response.find("ok") != std::string::npos) { break; }
  19207. }
  19208. return true;
  19209. });
  19210. *announced_close =
  19211. first_response.find("Connection: close") != std::string::npos;
  19212. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19213. }
  19214. class ConnectionTokenTest : public ::testing::Test {
  19215. protected:
  19216. void SetUp() override {
  19217. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19218. res.set_content("ok", "text/plain");
  19219. });
  19220. port_ = svr_.bind_to_any_port(HOST);
  19221. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19222. svr_.wait_until_ready();
  19223. }
  19224. void TearDown() override {
  19225. svr_.stop();
  19226. if (thread_.joinable()) { thread_.join(); }
  19227. }
  19228. Server svr_;
  19229. int port_ = 0;
  19230. thread thread_;
  19231. };
  19232. // "close" alongside another option still closes the connection, and the
  19233. // response says so rather than leaving the peer to discover it.
  19234. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19235. bool announced_close = false;
  19236. bool reusable = true;
  19237. probe_connection_reuse(port_,
  19238. "GET /keepalive HTTP/1.1\r\n"
  19239. "Host: localhost\r\n"
  19240. "Connection: keep-alive, close\r\n"
  19241. "\r\n",
  19242. &announced_close, &reusable);
  19243. EXPECT_TRUE(announced_close);
  19244. EXPECT_FALSE(reusable);
  19245. }
  19246. // "close" split over two field lines is the same list, so it is honored too.
  19247. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19248. bool announced_close = false;
  19249. bool reusable = true;
  19250. probe_connection_reuse(port_,
  19251. "GET /keepalive HTTP/1.1\r\n"
  19252. "Host: localhost\r\n"
  19253. "Connection: keep-alive\r\n"
  19254. "Connection: close\r\n"
  19255. "\r\n",
  19256. &announced_close, &reusable);
  19257. EXPECT_TRUE(announced_close);
  19258. EXPECT_FALSE(reusable);
  19259. }
  19260. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19261. // keep-alive in the spelling everyone actually sends keeps its connection.
  19262. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19263. bool announced_close = false;
  19264. bool reusable = false;
  19265. probe_connection_reuse(port_,
  19266. "GET /keepalive HTTP/1.0\r\n"
  19267. "Host: localhost\r\n"
  19268. "Connection: keep-alive\r\n"
  19269. "\r\n",
  19270. &announced_close, &reusable);
  19271. EXPECT_FALSE(announced_close);
  19272. EXPECT_TRUE(reusable);
  19273. }
  19274. // A token the value merely contains is not the token itself.
  19275. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19276. bool announced_close = false;
  19277. bool reusable = false;
  19278. probe_connection_reuse(port_,
  19279. "GET /keepalive HTTP/1.1\r\n"
  19280. "Host: localhost\r\n"
  19281. "Connection: notclose\r\n"
  19282. "\r\n",
  19283. &announced_close, &reusable);
  19284. EXPECT_FALSE(announced_close);
  19285. EXPECT_TRUE(reusable);
  19286. }
  19287. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19288. Server svr;
  19289. std::vector<std::string> observed_types;
  19290. svr.Get("/", [&](const Request &req, Response &res) {
  19291. observed_types = req.accept_content_types;
  19292. res.set_content("ok", "text/plain");
  19293. });
  19294. auto port = svr.bind_to_any_port(HOST);
  19295. thread t = thread([&]() { svr.listen_after_bind(); });
  19296. auto se = detail::scope_exit([&] {
  19297. svr.stop();
  19298. t.join();
  19299. ASSERT_FALSE(svr.is_running());
  19300. });
  19301. svr.wait_until_ready();
  19302. Client cli(HOST, port);
  19303. Headers headers;
  19304. headers.emplace("Accept", "text/plain;q=0.5");
  19305. headers.emplace("Accept", "application/json");
  19306. auto res = cli.Get("/", headers);
  19307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19308. EXPECT_EQ(StatusCode::OK_200, res->status);
  19309. // Sorted by q-value, so the second field line's type comes first
  19310. ASSERT_EQ(2U, observed_types.size());
  19311. EXPECT_EQ("application/json", observed_types[0]);
  19312. EXPECT_EQ("text/plain", observed_types[1]);
  19313. }
  19314. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19315. // empty field line must not contribute a bare comma to the combined value.
  19316. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19317. Server svr;
  19318. std::vector<std::string> observed_types;
  19319. svr.Get("/", [&](const Request &req, Response &res) {
  19320. observed_types = req.accept_content_types;
  19321. res.set_content("ok", "text/plain");
  19322. });
  19323. auto port = svr.bind_to_any_port(HOST);
  19324. thread t = thread([&]() { svr.listen_after_bind(); });
  19325. auto se = detail::scope_exit([&] {
  19326. svr.stop();
  19327. t.join();
  19328. ASSERT_FALSE(svr.is_running());
  19329. });
  19330. svr.wait_until_ready();
  19331. // Empty first field line, then a real one
  19332. std::string raw_req = "GET / HTTP/1.1\r\n"
  19333. "Host: localhost\r\n"
  19334. "Accept:\r\n"
  19335. "Accept: application/json\r\n"
  19336. "Connection: close\r\n"
  19337. "\r\n";
  19338. std::string out;
  19339. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19340. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19341. ASSERT_EQ(1U, observed_types.size());
  19342. EXPECT_EQ("application/json", observed_types[0]);
  19343. }
  19344. // The skip in get_combined_header_value() is what keeps an empty field line
  19345. // from contributing a bare comma. Only a trailing empty field line exercises
  19346. // it: a leading one is already covered by the "combined is still empty" check,
  19347. // and parse_accept_header() now ignores the empty element either way, so the
  19348. // request-level test above can no longer tell the two apart.
  19349. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19350. Headers headers;
  19351. headers.emplace("Accept", "text/html");
  19352. headers.emplace("Accept", "");
  19353. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19354. headers.clear();
  19355. headers.emplace("Accept", "");
  19356. headers.emplace("Accept", "application/json");
  19357. EXPECT_EQ("application/json",
  19358. detail::get_combined_header_value(headers, "Accept"));
  19359. }
  19360. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19361. // An encoding offered on a later Accept-Encoding field line is still offered.
  19362. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19363. Server svr;
  19364. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19365. res.set_content(std::string(1024, 'x'), "text/plain");
  19366. });
  19367. auto port = svr.bind_to_any_port(HOST);
  19368. thread t = thread([&]() { svr.listen_after_bind(); });
  19369. auto se = detail::scope_exit([&] {
  19370. svr.stop();
  19371. t.join();
  19372. ASSERT_FALSE(svr.is_running());
  19373. });
  19374. svr.wait_until_ready();
  19375. Client cli(HOST, port);
  19376. cli.set_decompress(false);
  19377. Headers headers;
  19378. headers.emplace("Accept-Encoding", "identity");
  19379. headers.emplace("Accept-Encoding", "gzip");
  19380. auto res = cli.Get("/", headers);
  19381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19382. EXPECT_EQ(StatusCode::OK_200, res->status);
  19383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19384. }
  19385. #endif
  19386. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19387. // Transfer-Encoding is not its body.
  19388. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19389. Server svr;
  19390. svr.set_payload_max_length(8);
  19391. svr.Post("/test", [](const Request &, Response &res) {
  19392. res.set_content("ok", "text/plain");
  19393. });
  19394. auto port = svr.bind_to_any_port(HOST);
  19395. ASSERT_GT(port, 0);
  19396. thread t = thread([&] { svr.listen_after_bind(); });
  19397. auto se = detail::scope_exit([&] {
  19398. svr.stop();
  19399. t.join();
  19400. ASSERT_FALSE(svr.is_running());
  19401. });
  19402. svr.wait_until_ready();
  19403. std::string resp;
  19404. ASSERT_TRUE(send_request(1,
  19405. "POST /test HTTP/1.1\r\n"
  19406. "Host: localhost\r\n"
  19407. "Connection: close\r\n"
  19408. "\r\n" +
  19409. std::string(16, 'X'),
  19410. &resp, port));
  19411. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19412. }
  19413. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19414. Server svr;
  19415. svr.Post("/post", [&](const Request &req, Response &res) {
  19416. res.set_content(req.body, "text/plain");
  19417. });
  19418. svr.Put("/put", [&](const Request &req, Response &res) {
  19419. res.set_content(req.body, "text/plain");
  19420. });
  19421. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19422. res.set_content(req.body, "text/plain");
  19423. });
  19424. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19425. res.set_content(req.body, "text/plain");
  19426. });
  19427. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19428. auto se = detail::scope_exit([&] {
  19429. svr.stop();
  19430. t.join();
  19431. ASSERT_FALSE(svr.is_running());
  19432. });
  19433. svr.wait_until_ready();
  19434. std::string resp;
  19435. // POST without Content-Length
  19436. ASSERT_TRUE(send_request(5,
  19437. "POST /post HTTP/1.1\r\n"
  19438. "Host: localhost\r\n"
  19439. "Connection: close\r\n"
  19440. "\r\n",
  19441. &resp));
  19442. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19443. // PUT without Content-Length
  19444. resp.clear();
  19445. ASSERT_TRUE(send_request(5,
  19446. "PUT /put HTTP/1.1\r\n"
  19447. "Host: localhost\r\n"
  19448. "Connection: close\r\n"
  19449. "\r\n",
  19450. &resp));
  19451. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19452. // PATCH without Content-Length
  19453. resp.clear();
  19454. ASSERT_TRUE(send_request(5,
  19455. "PATCH /patch HTTP/1.1\r\n"
  19456. "Host: localhost\r\n"
  19457. "Connection: close\r\n"
  19458. "\r\n",
  19459. &resp));
  19460. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19461. // DELETE without Content-Length
  19462. resp.clear();
  19463. ASSERT_TRUE(send_request(5,
  19464. "DELETE /delete HTTP/1.1\r\n"
  19465. "Host: localhost\r\n"
  19466. "Connection: close\r\n"
  19467. "\r\n",
  19468. &resp));
  19469. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19470. }
  19471. //==============================================================================
  19472. // open_stream() Tests
  19473. //==============================================================================
  19474. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19475. std::string result;
  19476. char buf[8192];
  19477. ssize_t n;
  19478. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19479. result.append(buf, static_cast<size_t>(n));
  19480. }
  19481. return result;
  19482. }
  19483. // Mock stream for unit tests
  19484. class MockStream : public Stream {
  19485. public:
  19486. std::string data;
  19487. size_t pos = 0;
  19488. ssize_t error_after = -1; // -1 = no error
  19489. explicit MockStream(const std::string &d, ssize_t err = -1)
  19490. : data(d), error_after(err) {}
  19491. bool is_readable() const override { return true; }
  19492. bool wait_readable() const override { return true; }
  19493. bool wait_writable() const override { return true; }
  19494. ssize_t read(char *ptr, size_t size) override {
  19495. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19496. if (pos >= data.size()) return 0;
  19497. size_t limit =
  19498. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19499. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19500. std::memcpy(ptr, data.data() + pos, to_read);
  19501. pos += to_read;
  19502. return static_cast<ssize_t>(to_read);
  19503. }
  19504. ssize_t write(const char *, size_t) override { return -1; }
  19505. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19506. ip = "127.0.0.1";
  19507. port = 0;
  19508. }
  19509. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19510. ip = "127.0.0.1";
  19511. port = 0;
  19512. }
  19513. socket_t socket() const override { return INVALID_SOCKET; }
  19514. time_t duration() const override { return 0; }
  19515. };
  19516. TEST(StreamHandleTest, Basic) {
  19517. ClientImpl::StreamHandle handle;
  19518. EXPECT_FALSE(handle.is_valid());
  19519. handle.response = detail::make_unique<Response>();
  19520. handle.error = Error::Connection;
  19521. EXPECT_FALSE(handle.is_valid());
  19522. handle.error = Error::Success;
  19523. EXPECT_TRUE(handle.is_valid());
  19524. }
  19525. TEST(BodyReaderTest, Basic) {
  19526. MockStream stream("Hello, World!");
  19527. detail::BodyReader reader;
  19528. reader.stream = &stream;
  19529. reader.content_length = 13;
  19530. char buf[32];
  19531. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19532. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19533. EXPECT_TRUE(reader.eof);
  19534. }
  19535. TEST(BodyReaderTest, NoStream) {
  19536. detail::BodyReader reader;
  19537. char buf[32];
  19538. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19539. EXPECT_EQ(Error::Connection, reader.last_error);
  19540. }
  19541. TEST(BodyReaderTest, Error) {
  19542. MockStream stream("Hello, World!", 5);
  19543. detail::BodyReader reader;
  19544. reader.stream = &stream;
  19545. reader.content_length = 13;
  19546. char buf[32];
  19547. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19548. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19549. EXPECT_EQ(Error::Read, reader.last_error);
  19550. }
  19551. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19552. // Mock-based StreamHandle tests relying on private internals are removed.
  19553. class OpenStreamTest : public ::testing::Test {
  19554. protected:
  19555. void SetUp() override {
  19556. svr_.Get("/hello", [](const Request &, Response &res) {
  19557. res.set_content("Hello World!", "text/plain");
  19558. });
  19559. svr_.Get("/large", [](const Request &, Response &res) {
  19560. res.set_content(std::string(10000, 'X'), "text/plain");
  19561. });
  19562. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19563. res.set_content("Hello World!", "image/jpeg");
  19564. res.set_header("Content-Encoding", "UTF-8");
  19565. });
  19566. svr_.Get("/chunked", [](const Request &, Response &res) {
  19567. res.set_chunked_content_provider("text/plain",
  19568. [](size_t offset, DataSink &sink) {
  19569. if (offset < 15) {
  19570. sink.write("chunk", 5);
  19571. return true;
  19572. }
  19573. sink.done();
  19574. return true;
  19575. });
  19576. });
  19577. svr_.Get("/compressible", [](const Request &, Response &res) {
  19578. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19579. DataSink &sink) {
  19580. if (offset < 100 * 1024) {
  19581. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19582. sink.write(chunk.data(), chunk.size());
  19583. return true;
  19584. }
  19585. sink.done();
  19586. return true;
  19587. });
  19588. });
  19589. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19590. [](const Request & /*req*/, Response &res) {
  19591. auto i = new int(0);
  19592. res.set_header("Trailer", "Content-Length, X-Allowed");
  19593. res.set_chunked_content_provider(
  19594. "text/plain",
  19595. [i](size_t /*offset*/, DataSink &sink) {
  19596. switch (*i) {
  19597. case 0: sink.os << "123"; break;
  19598. case 1: sink.os << "456"; break;
  19599. case 2: sink.os << "789"; break;
  19600. case 3: {
  19601. sink.done_with_trailer(
  19602. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19603. } break;
  19604. }
  19605. (*i)++;
  19606. return true;
  19607. },
  19608. [i](bool success) {
  19609. EXPECT_TRUE(success);
  19610. delete i;
  19611. });
  19612. });
  19613. // Echo headers endpoint for header-related tests
  19614. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19615. std::string body;
  19616. for (const auto &h : req.headers) {
  19617. body.append(h.first);
  19618. body.push_back(':');
  19619. body.append(h.second);
  19620. body.push_back('\n');
  19621. }
  19622. res.set_content(body, "text/plain");
  19623. });
  19624. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19625. std::string body;
  19626. for (const auto &h : req.headers) {
  19627. body.append(h.first);
  19628. body.push_back(':');
  19629. body.append(h.second);
  19630. body.push_back('\n');
  19631. }
  19632. res.set_content(body, "text/plain");
  19633. });
  19634. port_ = svr_.bind_to_any_port("127.0.0.1");
  19635. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19636. svr_.wait_until_ready();
  19637. }
  19638. void TearDown() override {
  19639. svr_.stop();
  19640. if (thread_.joinable()) thread_.join();
  19641. }
  19642. Server svr_;
  19643. std::thread thread_;
  19644. int port_ = 0;
  19645. };
  19646. TEST_F(OpenStreamTest, Basic) {
  19647. Client cli("127.0.0.1", port_);
  19648. auto handle = cli.open_stream("GET", "/hello");
  19649. EXPECT_TRUE(handle.is_valid());
  19650. EXPECT_EQ("Hello World!", read_all(handle));
  19651. }
  19652. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19653. Client cli("127.0.0.1", port_);
  19654. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19655. ASSERT_TRUE(handle.is_valid());
  19656. EXPECT_EQ("Hello World!", read_all(handle));
  19657. }
  19658. TEST_F(OpenStreamTest, SmallBuffer) {
  19659. Client cli("127.0.0.1", port_);
  19660. auto handle = cli.open_stream("GET", "/hello");
  19661. std::string result;
  19662. char buf[4];
  19663. ssize_t n;
  19664. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19665. result.append(buf, static_cast<size_t>(n));
  19666. EXPECT_EQ("Hello World!", result);
  19667. }
  19668. TEST_F(OpenStreamTest, DefaultHeaders) {
  19669. Client cli("127.0.0.1", port_);
  19670. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19671. {
  19672. auto handle = cli.open_stream("GET", "/echo-headers");
  19673. ASSERT_TRUE(handle.is_valid());
  19674. auto body = read_all(handle);
  19675. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19676. std::string::npos);
  19677. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19678. std::string::npos);
  19679. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19680. }
  19681. // open_stream POST with body and no explicit content_type should NOT add
  19682. // text/plain Content-Type (behavior differs from non-streaming path), but
  19683. // should include Content-Length
  19684. {
  19685. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19686. ASSERT_TRUE(handle.is_valid());
  19687. auto body = read_all(handle);
  19688. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19689. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19690. }
  19691. // open_stream POST with explicit Content-Type should preserve it
  19692. {
  19693. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19694. {{"Content-Type", "application/custom"}},
  19695. "{}", "application/custom");
  19696. ASSERT_TRUE(handle.is_valid());
  19697. auto body = read_all(handle);
  19698. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19699. }
  19700. // User-specified User-Agent must not be overwritten for stream API
  19701. {
  19702. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19703. {{"User-Agent", "MyAgent/1.2"}});
  19704. ASSERT_TRUE(handle.is_valid());
  19705. auto body = read_all(handle);
  19706. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19707. }
  19708. }
  19709. TEST_F(OpenStreamTest, Large) {
  19710. Client cli("127.0.0.1", port_);
  19711. auto handle = cli.open_stream("GET", "/large");
  19712. EXPECT_EQ(10000u, read_all(handle).size());
  19713. }
  19714. TEST_F(OpenStreamTest, ConnectionError) {
  19715. Client cli("127.0.0.1", 9999);
  19716. auto handle = cli.open_stream("GET", "/hello");
  19717. EXPECT_FALSE(handle.is_valid());
  19718. }
  19719. TEST_F(OpenStreamTest, Chunked) {
  19720. Client cli("127.0.0.1", port_);
  19721. auto handle = cli.open_stream("GET", "/chunked");
  19722. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19723. "Transfer-Encoding") == "chunked");
  19724. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19725. }
  19726. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19727. Client cli("127.0.0.1", port_);
  19728. auto handle =
  19729. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19730. ASSERT_TRUE(handle.is_valid());
  19731. // Consume body to allow trailers to be received/parsed
  19732. auto body = read_all(handle);
  19733. // Explicitly parse trailers (ensure trailers are available for assertion)
  19734. handle.parse_trailers_if_needed();
  19735. EXPECT_EQ(std::string("123456789"), body);
  19736. // The response should include a Trailer header declaring both names
  19737. ASSERT_TRUE(handle.response);
  19738. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19739. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19740. handle.response->get_header_value("Trailer"));
  19741. // Prohibited trailer must not be present
  19742. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19743. // Allowed trailer should be present
  19744. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19745. EXPECT_EQ(std::string("yes"),
  19746. handle.response->get_trailer_value("X-Allowed"));
  19747. // Verify trailers are NOT present as regular headers
  19748. EXPECT_EQ(std::string(""),
  19749. handle.response->get_header_value("Content-Length"));
  19750. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19751. }
  19752. // Accepts one connection on an OS-assigned port, which it hands over through
  19753. // port_promise, reads the request head and sends back response. after_send,
  19754. // if given, runs on the connection before it is closed.
  19755. static std::thread
  19756. serve_single_response(std::promise<int> &port_promise,
  19757. const std::string &response,
  19758. std::function<void(socket_t)> after_send = nullptr) {
  19759. return std::thread([&port_promise, response, after_send] {
  19760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19761. default_socket_options(srv);
  19762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19764. sockaddr_in addr{};
  19765. addr.sin_family = AF_INET;
  19766. addr.sin_port = htons(0); // Let OS assign a free port
  19767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19768. int opt = 1;
  19769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19770. #ifdef _WIN32
  19771. reinterpret_cast<const char *>(&opt),
  19772. #else
  19773. &opt,
  19774. #endif
  19775. sizeof(opt));
  19776. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19777. ::listen(srv, 1) != 0) {
  19778. port_promise.set_value(-1);
  19779. detail::close_socket(srv);
  19780. return;
  19781. }
  19782. socklen_t addr_len = sizeof(addr);
  19783. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19784. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19785. sockaddr_in cli_addr{};
  19786. socklen_t cli_len = sizeof(cli_addr);
  19787. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19788. if (cli != INVALID_SOCKET) {
  19789. // Read the complete HTTP request (until the blank line that terminates
  19790. // headers) before sending the response. If the server closes the socket
  19791. // while the client's request data is still unread in the kernel receive
  19792. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19793. // connection on both sides: it discards the client's receive buffer
  19794. // (which already holds our response) and causes any in-progress write on
  19795. // the client to fail with ECONNRESET. Reading all request data first
  19796. // ensures close() emits a graceful FIN.
  19797. {
  19798. char rbuf[256];
  19799. std::string req;
  19800. while (req.find("\r\n\r\n") == std::string::npos) {
  19801. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19802. if (n <= 0) { break; }
  19803. req.append(rbuf, static_cast<size_t>(n));
  19804. }
  19805. }
  19806. ::send(cli,
  19807. #ifdef _WIN32
  19808. static_cast<const char *>(response.c_str()),
  19809. static_cast<int>(response.size()),
  19810. #else
  19811. response.c_str(), response.size(),
  19812. #endif
  19813. 0);
  19814. if (after_send) { after_send(cli); }
  19815. detail::close_socket(cli);
  19816. }
  19817. detail::close_socket(srv);
  19818. });
  19819. }
  19820. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19821. #ifndef _WIN32
  19822. signal(SIGPIPE, SIG_IGN);
  19823. #endif
  19824. std::promise<int> port_promise;
  19825. auto port_future = port_promise.get_future();
  19826. auto server_thread =
  19827. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19828. "Content-Type: text/plain\r\n"
  19829. "Content-Length: not-a-number\r\n"
  19830. "Connection: close\r\n"
  19831. "\r\n"
  19832. "hello");
  19833. auto port = port_future.get();
  19834. ASSERT_GT(port, 0);
  19835. Client cli("127.0.0.1", port);
  19836. auto handle = cli.open_stream("GET", "/");
  19837. EXPECT_FALSE(handle.is_valid());
  19838. server_thread.join();
  19839. }
  19840. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19841. #ifndef _WIN32
  19842. signal(SIGPIPE, SIG_IGN);
  19843. #endif
  19844. std::promise<int> port_promise;
  19845. auto port_future = port_promise.get_future();
  19846. auto server_thread = serve_single_response(
  19847. port_promise, "HTTP/1.1 200 OK\r\n"
  19848. "Content-Type: text/plain\r\n"
  19849. "Content-Length: 99999999999999999999999999\r\n"
  19850. "Connection: close\r\n"
  19851. "\r\n"
  19852. "hello");
  19853. auto port = port_future.get();
  19854. ASSERT_GT(port, 0);
  19855. // Historically std::stoull would throw std::out_of_range here and crash
  19856. // the process, then parsing silently clamped to a bogus framing length and
  19857. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19858. // so the stream fails to open, matching the not-a-number case above. The
  19859. // process still must NOT terminate.
  19860. Client cli("127.0.0.1", port);
  19861. auto handle = cli.open_stream("GET", "/");
  19862. EXPECT_FALSE(handle.is_valid());
  19863. server_thread.join();
  19864. }
  19865. // Serves `response` to the single request `fn` makes with a fresh client.
  19866. template <typename Fn>
  19867. static void with_single_response(const std::string &response, Fn fn) {
  19868. #ifndef _WIN32
  19869. signal(SIGPIPE, SIG_IGN);
  19870. #endif
  19871. std::promise<int> port_promise;
  19872. auto port_future = port_promise.get_future();
  19873. auto server_thread = serve_single_response(port_promise, response);
  19874. auto se = detail::scope_exit([&] { server_thread.join(); });
  19875. auto port = port_future.get();
  19876. ASSERT_GT(port, 0);
  19877. Client cli("127.0.0.1", port);
  19878. fn(cli);
  19879. }
  19880. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19881. // Neither Content-Length nor chunked: the body ends at the close
  19882. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19883. "Connection: close\r\n"
  19884. "\r\n"
  19885. "hello";
  19886. with_single_response(close_delimited, [](Client &cli) {
  19887. auto handle = cli.open_stream("GET", "/");
  19888. ASSERT_TRUE(handle.is_valid());
  19889. EXPECT_EQ("hello", read_all(handle));
  19890. EXPECT_FALSE(handle.has_read_error());
  19891. });
  19892. // A close before the end of the Content-Length is still an error
  19893. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19894. "Content-Length: 10\r\n"
  19895. "\r\n"
  19896. "hello";
  19897. with_single_response(short_content_length, [](Client &cli) {
  19898. auto handle = cli.open_stream("GET", "/");
  19899. ASSERT_TRUE(handle.is_valid());
  19900. read_all(handle);
  19901. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19902. });
  19903. // So is a close before the last chunk
  19904. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19905. "Transfer-Encoding: chunked\r\n"
  19906. "\r\n"
  19907. "5\r\nhello\r\n";
  19908. with_single_response(short_chunked, [](Client &cli) {
  19909. auto handle = cli.open_stream("GET", "/");
  19910. ASSERT_TRUE(handle.is_valid());
  19911. read_all(handle);
  19912. EXPECT_TRUE(handle.has_read_error());
  19913. });
  19914. }
  19915. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19916. const char *responses[] = {
  19917. "HTTP/1.1 103 Early Hints\r\n"
  19918. "Link: </style.css>; rel=preload\r\n"
  19919. "\r\n"
  19920. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19921. "HTTP/1.1 100 Continue\r\n"
  19922. "X-Note: interim\r\n"
  19923. "\r\n"
  19924. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19925. };
  19926. for (auto response : responses) {
  19927. with_single_response(response, [](Client &cli) {
  19928. auto res = cli.Get("/");
  19929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19930. EXPECT_EQ(StatusCode::OK_200, res->status);
  19931. EXPECT_EQ("ok", res->body);
  19932. });
  19933. }
  19934. }
  19935. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19936. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19937. const std::string final_response =
  19938. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19939. std::string interims;
  19940. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19941. interims += interim;
  19942. }
  19943. with_single_response(interims + final_response, [](Client &cli) {
  19944. auto res = cli.Get("/");
  19945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19946. EXPECT_EQ("ok", res->body);
  19947. });
  19948. with_single_response(interims + interim + final_response, [](Client &cli) {
  19949. auto res = cli.Get("/");
  19950. ASSERT_FALSE(res);
  19951. EXPECT_EQ(Error::Read, res.error());
  19952. });
  19953. }
  19954. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19955. #ifndef _WIN32
  19956. signal(SIGPIPE, SIG_IGN);
  19957. #endif
  19958. // The server answers the head without asking for the body. Bytes it then
  19959. // reads on the connection would be taken for the body the request declared.
  19960. auto closed_by_client = false;
  19961. std::promise<int> port_promise;
  19962. auto server_thread = serve_single_response(
  19963. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19964. [&](socket_t sock) {
  19965. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19966. char buf[256];
  19967. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19968. });
  19969. Client cli("127.0.0.1", port_promise.get_future().get());
  19970. cli.set_keep_alive(true);
  19971. cli.set_read_timeout(1, 0);
  19972. // Long enough for the client to send Expect: 100-continue.
  19973. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19975. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19976. cli.Get("/second");
  19977. server_thread.join();
  19978. EXPECT_TRUE(closed_by_client);
  19979. }
  19980. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19981. // Long enough for the client to send Expect: 100-continue
  19982. with_single_response(
  19983. "HTTP/1.1 103 Early Hints\r\n"
  19984. "Link: </style.css>; rel=preload\r\n"
  19985. "\r\n"
  19986. "HTTP/1.1 401 Unauthorized\r\n"
  19987. "Content-Length: 0\r\n\r\n",
  19988. [](Client &cli) {
  19989. cli.set_read_timeout(2, 0);
  19990. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19992. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19993. });
  19994. }
  19995. #ifdef CPPHTTPLIB_SSL_ENABLED
  19996. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19997. #ifndef _WIN32
  19998. signal(SIGPIPE, SIG_IGN);
  19999. #endif
  20000. auto reused = false;
  20001. std::promise<int> port_promise;
  20002. auto server_thread = serve_single_response(
  20003. port_promise,
  20004. "HTTP/1.1 401 Unauthorized\r\n"
  20005. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20006. "Content-Length: 0\r\n\r\n",
  20007. [&](socket_t sock) {
  20008. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20009. char buf[256];
  20010. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20011. });
  20012. Client cli("127.0.0.1", port_promise.get_future().get());
  20013. cli.set_keep_alive(true);
  20014. cli.set_digest_auth("user", "pass");
  20015. cli.set_read_timeout(1, 0);
  20016. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20017. server_thread.join();
  20018. EXPECT_FALSE(reused);
  20019. }
  20020. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20021. // Any other answer to CONNECT would read as the origin's response.
  20022. struct {
  20023. const char *response;
  20024. bool passed_on;
  20025. } cases[] = {
  20026. {"HTTP/1.1 201 Created\r\n"
  20027. "Set-Cookie: session=from-proxy\r\n"
  20028. "Content-Length: 0\r\n\r\n",
  20029. false},
  20030. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20031. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20032. "Content-Length: 0\r\n\r\n",
  20033. true},
  20034. };
  20035. for (const auto &c : cases) {
  20036. std::promise<int> port_promise;
  20037. auto server_thread = serve_single_response(port_promise, c.response);
  20038. SSLClient cli("example.com", 443);
  20039. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20040. auto res = cli.Get("/");
  20041. server_thread.join();
  20042. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20043. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20044. if (res) {
  20045. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20046. }
  20047. }
  20048. }
  20049. #endif
  20050. // Records the client's error logger calls as "error METHOD path", or
  20051. // "error null" for a call without a request
  20052. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20053. return [&log](const Error &err, const Request *req) {
  20054. log.push_back(to_string(err) + " " +
  20055. (req ? req->method + " " + req->path : "null"));
  20056. };
  20057. }
  20058. // A failed request is reported once, with the request the caller made
  20059. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20060. Server svr;
  20061. svr.Get("/big", [](const Request &, Response &res) {
  20062. res.set_content(std::string(100000, 'b'), "text/plain");
  20063. });
  20064. auto port = svr.bind_to_any_port(HOST);
  20065. std::thread t([&]() { svr.listen_after_bind(); });
  20066. auto se = detail::scope_exit([&] {
  20067. svr.stop();
  20068. t.join();
  20069. });
  20070. svr.wait_until_ready();
  20071. Client cli(HOST, port);
  20072. std::vector<std::string> log;
  20073. cli.set_error_logger(record_errors(log));
  20074. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20075. cli.Get("/big", [](const char *, size_t) { return false; });
  20076. EXPECT_EQ(expected, log);
  20077. log.clear();
  20078. cli.Get("/big", [](size_t, size_t) { return false; });
  20079. EXPECT_EQ(expected, log);
  20080. }
  20081. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20082. // Fails while the body is read
  20083. auto broken = [](const Request &, Response &res) {
  20084. res.set_content_provider(10, "text/plain",
  20085. [](size_t, size_t, DataSink &) { return false; });
  20086. };
  20087. Server other;
  20088. other.Get("/broken", broken);
  20089. auto other_port = other.bind_to_any_port(HOST);
  20090. std::thread other_t([&]() { other.listen_after_bind(); });
  20091. auto other_se = detail::scope_exit([&] {
  20092. other.stop();
  20093. other_t.join();
  20094. });
  20095. other.wait_until_ready();
  20096. Server svr;
  20097. svr.Get("/broken", broken);
  20098. svr.Get("/same-origin",
  20099. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20100. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20101. res.set_redirect("http://" + std::string(HOST) + ":" +
  20102. std::to_string(other_port) + "/broken");
  20103. });
  20104. auto port = svr.bind_to_any_port(HOST);
  20105. std::thread t([&]() { svr.listen_after_bind(); });
  20106. auto se = detail::scope_exit([&] {
  20107. svr.stop();
  20108. t.join();
  20109. });
  20110. svr.wait_until_ready();
  20111. Client cli(HOST, port);
  20112. cli.set_follow_location(true);
  20113. std::vector<std::string> log;
  20114. cli.set_error_logger(record_errors(log));
  20115. for (auto path : {"/same-origin", "/cross-origin"}) {
  20116. log.clear();
  20117. auto res = cli.Get(path);
  20118. ASSERT_FALSE(res);
  20119. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20120. log);
  20121. }
  20122. }
  20123. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20124. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20125. std::vector<std::string> log;
  20126. cli.set_error_logger(record_errors(log));
  20127. auto handle = cli.open_stream("GET", "/x");
  20128. EXPECT_FALSE(handle.is_valid());
  20129. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20130. log);
  20131. });
  20132. }
  20133. #ifdef CPPHTTPLIB_SSL_ENABLED
  20134. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20135. // Not a TLS server, so the handshake fails. It waits for a request line in
  20136. // the handshake bytes, so a short read timeout lets it close quickly.
  20137. Server svr;
  20138. svr.set_read_timeout(0, 100000);
  20139. svr.Get("/x", [](const Request &, Response &res) {
  20140. res.set_content("x", "text/plain");
  20141. });
  20142. auto port = svr.bind_to_any_port(HOST);
  20143. std::thread t([&]() { svr.listen_after_bind(); });
  20144. auto se = detail::scope_exit([&] {
  20145. svr.stop();
  20146. t.join();
  20147. });
  20148. svr.wait_until_ready();
  20149. std::vector<std::string> log;
  20150. SSLClient cli(HOST, port);
  20151. cli.enable_server_certificate_verification(false);
  20152. cli.set_error_logger(record_errors(log));
  20153. auto res = cli.Get("/x");
  20154. ASSERT_FALSE(res);
  20155. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20156. log.clear();
  20157. auto handle = cli.open_stream("GET", "/x");
  20158. EXPECT_FALSE(handle.is_valid());
  20159. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20160. log.clear();
  20161. SSLClient no_ca(HOST, port);
  20162. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20163. no_ca.set_error_logger(record_errors(log));
  20164. res = no_ca.Get("/x");
  20165. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20166. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20167. }
  20168. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20169. #ifndef _WIN32
  20170. signal(SIGPIPE, SIG_IGN);
  20171. #endif
  20172. // Refused, answered with a challenge, or closed without an answer
  20173. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20174. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20175. "Content-Length: 0\r\n\r\n",
  20176. ""}) {
  20177. std::promise<int> port_promise;
  20178. auto server_thread = serve_single_response(port_promise, response);
  20179. SSLClient cli("example.com", 443);
  20180. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20181. std::vector<std::string> log;
  20182. cli.set_error_logger(record_errors(log));
  20183. auto res = cli.Get("/");
  20184. server_thread.join();
  20185. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20186. << response;
  20187. }
  20188. }
  20189. #endif
  20190. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20191. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20192. // the chunked coding and drop Content-Length, so a front-end that trusts
  20193. // Content-Length would disagree about where the body ends (response
  20194. // smuggling). The client must reject such a response.
  20195. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20196. for (const char *te : {"chunked", "gzip, chunked"}) {
  20197. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20198. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20199. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20200. "5\r\nhello\r\n0\r\n\r\n";
  20201. with_single_response(response, [&](Client &cli) {
  20202. auto res = cli.Get("/");
  20203. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20204. EXPECT_EQ(Error::Read, res.error()) << te;
  20205. });
  20206. with_single_response(response, [&](Client &cli) {
  20207. auto handle = cli.open_stream("GET", "/");
  20208. EXPECT_FALSE(handle.is_valid()) << te;
  20209. EXPECT_EQ(Error::Read, handle.error) << te;
  20210. });
  20211. }
  20212. }
  20213. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20214. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20215. // closing the connection (unlike a request, which must be rejected).
  20216. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20217. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20218. "Transfer-Encoding: chunked\r\n"
  20219. "Connection: close\r\n"
  20220. "\r\n"
  20221. "5\r\nhello\r\n0\r\n\r\n",
  20222. "HTTP/1.1 200 OK\r\n"
  20223. "Transfer-Encoding: gzip\r\n"
  20224. "Connection: close\r\n"
  20225. "\r\n"
  20226. "hello"}) {
  20227. with_single_response(response, [&](Client &cli) {
  20228. auto res = cli.Get("/");
  20229. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20230. EXPECT_EQ("hello", res->body);
  20231. });
  20232. with_single_response(response, [&](Client &cli) {
  20233. auto handle = cli.open_stream("GET", "/");
  20234. ASSERT_TRUE(handle.is_valid()) << response;
  20235. EXPECT_EQ("hello", read_all(handle));
  20236. });
  20237. }
  20238. }
  20239. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20240. // framing headers describe nothing to read and must not be rejected.
  20241. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20242. const std::string framing = "Content-Length: 5\r\n"
  20243. "Transfer-Encoding: chunked\r\n"
  20244. "Connection: close\r\n"
  20245. "\r\n";
  20246. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20247. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20248. });
  20249. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20250. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20251. });
  20252. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20253. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20254. with_single_response(response, [&](Client &cli) {
  20255. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20256. });
  20257. with_single_response(response, [&](Client &cli) {
  20258. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20259. });
  20260. }
  20261. }
  20262. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20263. // header section, so a stream opened on one has nothing to read, whatever
  20264. // framing or coding headers it carries.
  20265. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20266. struct Case {
  20267. const char *method;
  20268. const char *status;
  20269. };
  20270. // A reader of the declared body reports an early close when nothing
  20271. // follows, and hands back what does.
  20272. struct Framing {
  20273. const char *headers;
  20274. const char *after;
  20275. };
  20276. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20277. Case{"GET", "304 Not Modified"}}) {
  20278. for (const auto &f :
  20279. {Framing{"Content-Length: 5\r\n", ""},
  20280. Framing{"Content-Length: 5\r\n", "hello"},
  20281. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20282. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20283. // Not decoded, so a build without Brotli opens it too
  20284. Framing{"Content-Encoding: br\r\n", ""}}) {
  20285. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20286. "Connection: close\r\n"
  20287. "\r\n" +
  20288. f.after;
  20289. with_single_response(response, [&](Client &cli) {
  20290. auto handle = cli.open_stream(c.method, "/");
  20291. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20292. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20293. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20294. });
  20295. }
  20296. }
  20297. }
  20298. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20299. // response, is faulty framing, so the connection is not reused after it.
  20300. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20301. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20302. "Content-Length: 0\r\n"
  20303. "Transfer-Encoding: chunked\r\n"
  20304. "\r\n"
  20305. "5\r\nhello\r\n0\r\n\r\n",
  20306. "HTTP/1.0 200 Connection established\r\n"
  20307. "Connection: keep-alive\r\n"
  20308. "Transfer-Encoding: chunked\r\n"
  20309. "\r\n"
  20310. "5\r\nhello\r\n0\r\n\r\n"}) {
  20311. with_single_response(response, [&](Client &cli) {
  20312. cli.set_keep_alive(true);
  20313. auto res = cli.Get("/");
  20314. ASSERT_TRUE(res) << response;
  20315. EXPECT_EQ("hello", res->body);
  20316. EXPECT_FALSE(cli.is_socket_open()) << response;
  20317. });
  20318. }
  20319. }
  20320. // A payload max length of 0 means no limit, however the body is framed.
  20321. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20322. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20323. "Transfer-Encoding: chunked\r\n"
  20324. "\r\n"
  20325. "5\r\nhello\r\n0\r\n\r\n",
  20326. "HTTP/1.1 200 OK\r\n"
  20327. "Connection: close\r\n"
  20328. "\r\n"
  20329. "hello"}) {
  20330. with_single_response(response, [&](Client &cli) {
  20331. cli.set_payload_max_length(0);
  20332. auto res = cli.Get("/");
  20333. ASSERT_TRUE(res) << response;
  20334. EXPECT_EQ("hello", res->body) << response;
  20335. });
  20336. }
  20337. }
  20338. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20339. Server svr;
  20340. svr.set_payload_max_length(0);
  20341. svr.Post("/echo", [](const Request &req, Response &res) {
  20342. res.set_content(req.body, "text/plain");
  20343. });
  20344. auto port = svr.bind_to_any_port(HOST);
  20345. thread t = thread([&] { svr.listen_after_bind(); });
  20346. auto se = detail::scope_exit([&] {
  20347. svr.stop();
  20348. t.join();
  20349. ASSERT_FALSE(svr.is_running());
  20350. });
  20351. svr.wait_until_ready();
  20352. Client cli(HOST, port);
  20353. auto res = cli.Post(
  20354. "/echo",
  20355. [](size_t /*offset*/, DataSink &sink) {
  20356. sink.write("hello", 5);
  20357. sink.done();
  20358. return true;
  20359. },
  20360. "text/plain");
  20361. ASSERT_TRUE(res);
  20362. EXPECT_EQ(StatusCode::OK_200, res->status);
  20363. EXPECT_EQ("hello", res->body);
  20364. }
  20365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20366. TEST_F(OpenStreamTest, Gzip) {
  20367. Client cli("127.0.0.1", port_);
  20368. auto handle = cli.open_stream("GET", "/compressible", {},
  20369. {{"Accept-Encoding", "gzip"}});
  20370. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20371. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20372. }
  20373. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20374. Client cli("127.0.0.1", port_);
  20375. auto handle =
  20376. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20377. {{"Accept-Encoding", "gzip"}});
  20378. ASSERT_TRUE(handle.is_valid());
  20379. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20380. EXPECT_EQ("123456789", read_all(handle));
  20381. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20382. }
  20383. #endif
  20384. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20385. TEST_F(OpenStreamTest, Brotli) {
  20386. Client cli("127.0.0.1", port_);
  20387. auto handle =
  20388. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20389. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20390. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20391. }
  20392. #endif
  20393. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20394. TEST_F(OpenStreamTest, Zstd) {
  20395. Client cli("127.0.0.1", port_);
  20396. auto handle = cli.open_stream("GET", "/compressible", {},
  20397. {{"Accept-Encoding", "zstd"}});
  20398. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20399. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20400. }
  20401. #endif
  20402. #ifdef CPPHTTPLIB_SSL_ENABLED
  20403. class SSLOpenStreamTest : public ::testing::Test {
  20404. protected:
  20405. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20406. void SetUp() override {
  20407. svr_.Get("/hello", [](const Request &, Response &res) {
  20408. res.set_content("Hello SSL World!", "text/plain");
  20409. });
  20410. svr_.Get("/chunked", [](const Request &, Response &res) {
  20411. res.set_chunked_content_provider("text/plain",
  20412. [](size_t offset, DataSink &sink) {
  20413. if (offset < 15) {
  20414. sink.write("chunk", 5);
  20415. return true;
  20416. }
  20417. sink.done();
  20418. return true;
  20419. });
  20420. });
  20421. svr_.Post("/echo", [](const Request &req, Response &res) {
  20422. res.set_content(req.body, req.get_header_value("Content-Type"));
  20423. });
  20424. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20425. std::string body = req.body;
  20426. res.set_chunked_content_provider(
  20427. "text/plain", [body](size_t offset, DataSink &sink) {
  20428. if (offset < body.size()) {
  20429. sink.write(body.data() + offset, body.size() - offset);
  20430. }
  20431. sink.done();
  20432. return true;
  20433. });
  20434. });
  20435. port_ = svr_.bind_to_any_port("127.0.0.1");
  20436. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20437. svr_.wait_until_ready();
  20438. }
  20439. void TearDown() override {
  20440. svr_.stop();
  20441. if (thread_.joinable()) thread_.join();
  20442. }
  20443. SSLServer svr_;
  20444. std::thread thread_;
  20445. int port_ = 0;
  20446. };
  20447. TEST_F(SSLOpenStreamTest, Basic) {
  20448. SSLClient cli("127.0.0.1", port_);
  20449. cli.enable_server_certificate_verification(false);
  20450. auto handle = cli.open_stream("GET", "/hello");
  20451. ASSERT_TRUE(handle.is_valid());
  20452. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20453. }
  20454. TEST_F(SSLOpenStreamTest, Chunked) {
  20455. SSLClient cli("127.0.0.1", port_);
  20456. cli.enable_server_certificate_verification(false);
  20457. auto handle = cli.open_stream("GET", "/chunked");
  20458. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20459. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20460. "Transfer-Encoding") == "chunked");
  20461. auto body = read_all(handle);
  20462. EXPECT_EQ("chunkchunkchunk", body);
  20463. }
  20464. TEST_F(SSLOpenStreamTest, Post) {
  20465. SSLClient cli("127.0.0.1", port_);
  20466. cli.enable_server_certificate_verification(false);
  20467. auto handle =
  20468. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20469. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20470. EXPECT_EQ(200, handle.response->status);
  20471. auto body = read_all(handle);
  20472. EXPECT_EQ("Hello SSL POST", body);
  20473. }
  20474. TEST_F(SSLOpenStreamTest, PostChunked) {
  20475. SSLClient cli("127.0.0.1", port_);
  20476. cli.enable_server_certificate_verification(false);
  20477. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20478. "Chunked SSL Data", "text/plain");
  20479. ASSERT_TRUE(handle.is_valid());
  20480. EXPECT_EQ(200, handle.response->status);
  20481. auto body = read_all(handle);
  20482. EXPECT_EQ("Chunked SSL Data", body);
  20483. }
  20484. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20485. // Content-Length is terminated by the server closing the connection. When the
  20486. // SSL peer sends a close_notify after the body, the client must treat it as a
  20487. // clean EOF and return a successful response rather than an error.
  20488. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20490. ASSERT_TRUE(svr.is_valid());
  20491. svr.set_keep_alive_max_count(1);
  20492. const std::string expected_body = "Hello from connection-close response!";
  20493. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20494. res.set_content_provider("text/plain",
  20495. [&](size_t offset, DataSink &sink) -> bool {
  20496. if (offset < expected_body.size()) {
  20497. sink.write(expected_body.data() + offset,
  20498. expected_body.size() - offset);
  20499. }
  20500. sink.done();
  20501. return true;
  20502. });
  20503. });
  20504. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20505. auto se = detail::scope_exit([&] {
  20506. svr.stop();
  20507. listen_thread.join();
  20508. ASSERT_FALSE(svr.is_running());
  20509. });
  20510. svr.wait_until_ready();
  20511. SSLClient cli(HOST, PORT);
  20512. cli.enable_server_certificate_verification(false);
  20513. auto res = cli.Get("/no-content-length");
  20514. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20515. EXPECT_EQ(StatusCode::OK_200, res->status);
  20516. EXPECT_EQ(expected_body, res->body);
  20517. }
  20518. #endif // CPPHTTPLIB_SSL_ENABLED
  20519. //==============================================================================
  20520. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20521. // results for various scenarios.
  20522. //==============================================================================
  20523. TEST(ParityTest, GetVsOpenStream) {
  20524. Server svr;
  20525. const std::string path = "/parity";
  20526. const std::string content = "Parity test content: hello world";
  20527. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20528. res.set_content(content, "text/plain");
  20529. });
  20530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20531. auto se = detail::scope_exit([&] {
  20532. svr.stop();
  20533. t.join();
  20534. ASSERT_FALSE(svr.is_running());
  20535. });
  20536. svr.wait_until_ready();
  20537. Client cli(HOST, PORT);
  20538. // Non-stream path
  20539. auto r1 = cli.Get(path);
  20540. ASSERT_TRUE(r1);
  20541. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20542. // Stream path
  20543. auto h = cli.open_stream("GET", path);
  20544. ASSERT_TRUE(h.is_valid());
  20545. EXPECT_EQ(r1->body, read_all(h));
  20546. }
  20547. // Helper to compress data with provided compressor type T
  20548. template <typename Compressor>
  20549. static std::string compress_payload_for_parity(const std::string &in) {
  20550. std::string out;
  20551. Compressor compressor;
  20552. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20553. [&](const char *data, size_t n) {
  20554. out.append(data, n);
  20555. return true;
  20556. });
  20557. EXPECT_TRUE(ok);
  20558. return out;
  20559. }
  20560. // Helper function for compression parity tests
  20561. template <typename Compressor>
  20562. static void test_compression_parity(const std::string &original,
  20563. const std::string &path,
  20564. const std::string &encoding) {
  20565. const std::string compressed =
  20566. compress_payload_for_parity<Compressor>(original);
  20567. Server svr;
  20568. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20569. res.set_content(compressed, "application/octet-stream");
  20570. res.set_header("Content-Encoding", encoding);
  20571. });
  20572. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20573. auto se = detail::scope_exit([&] {
  20574. svr.stop();
  20575. t.join();
  20576. ASSERT_FALSE(svr.is_running());
  20577. });
  20578. svr.wait_until_ready();
  20579. Client cli(HOST, PORT);
  20580. // Non-streaming
  20581. {
  20582. auto res = cli.Get(path);
  20583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20584. EXPECT_EQ(StatusCode::OK_200, res->status);
  20585. EXPECT_EQ(original, res->body);
  20586. }
  20587. // Streaming
  20588. {
  20589. auto h = cli.open_stream("GET", path);
  20590. ASSERT_TRUE(h.is_valid());
  20591. EXPECT_EQ(original, read_all(h));
  20592. }
  20593. }
  20594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20595. TEST(ParityTest, Gzip) {
  20596. test_compression_parity<detail::gzip_compressor>(
  20597. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20598. }
  20599. #endif
  20600. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20601. TEST(ParityTest, Brotli) {
  20602. test_compression_parity<detail::brotli_compressor>(
  20603. "Hello, brotli parity test payload", "/parity-br", "br");
  20604. }
  20605. #endif
  20606. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20607. TEST(ParityTest, Zstd) {
  20608. test_compression_parity<detail::zstd_compressor>(
  20609. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20610. }
  20611. #endif
  20612. //==============================================================================
  20613. // New Stream API Tests
  20614. //==============================================================================
  20615. inline std::string read_body(httplib::stream::Result &result) {
  20616. std::string body;
  20617. while (result.next()) {
  20618. body.append(result.data(), result.size());
  20619. }
  20620. return body;
  20621. }
  20622. TEST(ClientConnectionTest, Basic) {
  20623. httplib::ClientConnection conn;
  20624. EXPECT_FALSE(conn.is_open());
  20625. conn.sock = 1;
  20626. EXPECT_TRUE(conn.is_open());
  20627. httplib::ClientConnection conn2(std::move(conn));
  20628. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20629. conn2.sock = INVALID_SOCKET;
  20630. }
  20631. // Unified test server for all stream::* tests
  20632. class StreamApiTest : public ::testing::Test {
  20633. protected:
  20634. void SetUp() override {
  20635. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20636. res.set_content("Hello World!", "text/plain");
  20637. });
  20638. svr_.Get("/echo-params",
  20639. [](const httplib::Request &req, httplib::Response &res) {
  20640. std::string r;
  20641. for (const auto &p : req.params) {
  20642. if (!r.empty()) r += "&";
  20643. r += p.first + "=" + p.second;
  20644. }
  20645. res.set_content(r, "text/plain");
  20646. });
  20647. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20648. res.set_content(req.body, req.get_header_value("Content-Type"));
  20649. });
  20650. svr_.Post("/echo-headers",
  20651. [](const httplib::Request &req, httplib::Response &res) {
  20652. std::string r;
  20653. for (const auto &h : req.headers)
  20654. r += h.first + ": " + h.second + "\n";
  20655. res.set_content(r, "text/plain");
  20656. });
  20657. svr_.Post("/echo-params",
  20658. [](const httplib::Request &req, httplib::Response &res) {
  20659. std::string r = "params:";
  20660. for (const auto &p : req.params)
  20661. r += p.first + "=" + p.second + ";";
  20662. res.set_content(r + " body:" + req.body, "text/plain");
  20663. });
  20664. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20665. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20666. });
  20667. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20668. res.set_content("PUT:" + req.body, "text/plain");
  20669. });
  20670. svr_.Patch("/echo",
  20671. [](const httplib::Request &req, httplib::Response &res) {
  20672. res.set_content("PATCH:" + req.body, "text/plain");
  20673. });
  20674. svr_.Delete(
  20675. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20676. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20677. "text/plain");
  20678. });
  20679. svr_.Get("/head-test",
  20680. [](const httplib::Request &, httplib::Response &res) {
  20681. res.set_content("body for HEAD", "text/plain");
  20682. });
  20683. svr_.Options("/options",
  20684. [](const httplib::Request &, httplib::Response &res) {
  20685. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20686. });
  20687. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20688. svr_.wait_until_ready();
  20689. }
  20690. void TearDown() override {
  20691. svr_.stop();
  20692. if (thread_.joinable()) thread_.join();
  20693. }
  20694. httplib::Server svr_;
  20695. std::thread thread_;
  20696. };
  20697. // stream::Get tests
  20698. TEST_F(StreamApiTest, GetBasic) {
  20699. httplib::Client cli(HOST, PORT);
  20700. auto result = httplib::stream::Get(cli, "/hello");
  20701. ASSERT_TRUE(result.is_valid());
  20702. EXPECT_EQ(200, result.status());
  20703. EXPECT_EQ("Hello World!", read_body(result));
  20704. }
  20705. TEST_F(StreamApiTest, GetWithParams) {
  20706. httplib::Client cli(HOST, PORT);
  20707. httplib::Params params{{"foo", "bar"}};
  20708. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20709. ASSERT_TRUE(result.is_valid());
  20710. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20711. }
  20712. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20713. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20714. httplib::Client cli(HOST, PORT);
  20715. cli.set_payload_max_length(0);
  20716. auto result = httplib::stream::Get(cli, "/hello");
  20717. ASSERT_TRUE(result.is_valid());
  20718. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20719. EXPECT_EQ("Hello World!", read_body(result));
  20720. }
  20721. #endif
  20722. TEST_F(StreamApiTest, GetConnectionError) {
  20723. httplib::Client cli(HOST, 9999);
  20724. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20725. }
  20726. TEST_F(StreamApiTest, Get404) {
  20727. httplib::Client cli(HOST, PORT);
  20728. auto result = httplib::stream::Get(cli, "/nonexistent");
  20729. EXPECT_TRUE(result.is_valid());
  20730. EXPECT_EQ(404, result.status());
  20731. }
  20732. // stream::Post tests
  20733. TEST_F(StreamApiTest, PostBasic) {
  20734. httplib::Client cli(HOST, PORT);
  20735. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20736. "application/json");
  20737. ASSERT_TRUE(result.is_valid());
  20738. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20739. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20740. }
  20741. TEST_F(StreamApiTest, PostWithHeaders) {
  20742. httplib::Client cli(HOST, PORT);
  20743. httplib::Headers headers{{"X-Custom", "value"}};
  20744. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20745. "text/plain");
  20746. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20747. }
  20748. TEST_F(StreamApiTest, PostWithParams) {
  20749. httplib::Client cli(HOST, PORT);
  20750. httplib::Params params{{"k", "v"}};
  20751. auto result =
  20752. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20753. auto body = read_body(result);
  20754. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20755. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20756. }
  20757. TEST_F(StreamApiTest, PostLarge) {
  20758. httplib::Client cli(HOST, PORT);
  20759. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20760. size_t total = 0;
  20761. while (result.next()) {
  20762. total += result.size();
  20763. }
  20764. EXPECT_EQ(100u * 1024u, total);
  20765. }
  20766. // stream::Put/Patch tests
  20767. TEST_F(StreamApiTest, PutAndPatch) {
  20768. httplib::Client cli(HOST, PORT);
  20769. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20770. EXPECT_EQ("PUT:test", read_body(put));
  20771. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20772. EXPECT_EQ("PATCH:test", read_body(patch));
  20773. }
  20774. // stream::Delete tests
  20775. TEST_F(StreamApiTest, Delete) {
  20776. httplib::Client cli(HOST, PORT);
  20777. auto del1 = httplib::stream::Delete(cli, "/resource");
  20778. EXPECT_EQ("Deleted", read_body(del1));
  20779. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20780. EXPECT_EQ("Deleted:data", read_body(del2));
  20781. }
  20782. // stream::Head/Options tests
  20783. TEST_F(StreamApiTest, HeadAndOptions) {
  20784. httplib::Client cli(HOST, PORT);
  20785. auto head = httplib::stream::Head(cli, "/head-test");
  20786. EXPECT_TRUE(head.is_valid());
  20787. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20788. auto opts = httplib::stream::Options(cli, "/options");
  20789. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20790. }
  20791. // SSL stream::* tests
  20792. #ifdef CPPHTTPLIB_SSL_ENABLED
  20793. class SSLStreamApiTest : public ::testing::Test {
  20794. protected:
  20795. void SetUp() override {
  20796. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20797. res.set_content("Hello SSL!", "text/plain");
  20798. });
  20799. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20800. res.set_content(req.body, "text/plain");
  20801. });
  20802. port_ = svr_.bind_to_any_port("127.0.0.1");
  20803. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20804. svr_.wait_until_ready();
  20805. }
  20806. void TearDown() override {
  20807. svr_.stop();
  20808. if (thread_.joinable()) thread_.join();
  20809. }
  20810. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20811. std::thread thread_;
  20812. int port_ = 0;
  20813. };
  20814. TEST_F(SSLStreamApiTest, GetAndPost) {
  20815. httplib::SSLClient cli("127.0.0.1", port_);
  20816. cli.enable_server_certificate_verification(false);
  20817. auto get = httplib::stream::Get(cli, "/hello");
  20818. EXPECT_EQ("Hello SSL!", read_body(get));
  20819. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20820. EXPECT_EQ("test", read_body(post));
  20821. }
  20822. #endif
  20823. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20824. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20825. // BodyReader
  20826. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20827. // Test that read timeout during streaming is detected
  20828. // Use a large content-length response where server delays mid-stream
  20829. Server svr;
  20830. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20831. // Send a large response with delay in the middle
  20832. res.set_content_provider(
  20833. 1000, // content_length
  20834. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20835. if (offset < 100) {
  20836. // Send first 100 bytes immediately
  20837. std::string data(100, 'A');
  20838. sink.write(data.c_str(), data.size());
  20839. return true;
  20840. }
  20841. // Then delay longer than client timeout
  20842. std::this_thread::sleep_for(std::chrono::seconds(3));
  20843. std::string data(900, 'B');
  20844. sink.write(data.c_str(), data.size());
  20845. return true;
  20846. });
  20847. });
  20848. auto port = 8091;
  20849. std::thread t([&]() { svr.listen("localhost", port); });
  20850. svr.wait_until_ready();
  20851. Client cli("localhost", port);
  20852. cli.set_read_timeout(1, 0); // 1 second timeout
  20853. auto handle = cli.open_stream("GET", "/slow-stream");
  20854. ASSERT_TRUE(handle.is_valid());
  20855. char buf[256];
  20856. ssize_t total = 0;
  20857. ssize_t n;
  20858. bool got_error = false;
  20859. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20860. total += n;
  20861. }
  20862. if (n < 0) {
  20863. got_error = true;
  20864. // Should be timeout or read error
  20865. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20866. handle.get_read_error() == Error::Read)
  20867. << "Actual error: " << to_string(handle.get_read_error());
  20868. }
  20869. // Either we got an error, or we got less data than expected
  20870. EXPECT_TRUE(got_error || total < 1000)
  20871. << "Expected timeout but got all " << total << " bytes";
  20872. svr.stop();
  20873. t.join();
  20874. }
  20875. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20876. // Test connection closed detection via BodyReader
  20877. Server svr;
  20878. std::atomic<bool> close_now{false};
  20879. svr.Get("/will-close", [&](const Request &, Response &res) {
  20880. res.set_content_provider(
  20881. 10000, // Large content_length that we won't fully send
  20882. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20883. if (offset < 100) {
  20884. std::string data(100, 'X');
  20885. sink.write(data.c_str(), data.size());
  20886. return true;
  20887. }
  20888. // Wait for signal then abort
  20889. while (!close_now) {
  20890. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20891. }
  20892. return false; // Abort - server will close connection
  20893. });
  20894. });
  20895. auto port = 8092;
  20896. std::thread t([&]() { svr.listen("localhost", port); });
  20897. svr.wait_until_ready();
  20898. Client cli("localhost", port);
  20899. auto handle = cli.open_stream("GET", "/will-close");
  20900. ASSERT_TRUE(handle.is_valid());
  20901. char buf[256];
  20902. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20903. EXPECT_GT(n, 0) << "First read should succeed";
  20904. // Signal server to close
  20905. close_now = true;
  20906. // Keep reading until error or EOF
  20907. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20908. // Keep reading
  20909. }
  20910. // Should get an error since content_length wasn't satisfied
  20911. if (n < 0) {
  20912. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20913. handle.get_read_error() == Error::Read)
  20914. << "Actual error: " << to_string(handle.get_read_error());
  20915. }
  20916. svr.stop();
  20917. t.join();
  20918. }
  20919. #ifdef CPPHTTPLIB_SSL_ENABLED
  20920. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20921. // Test that read timeout during SSL streaming is detected
  20922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20923. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20924. res.set_content_provider(
  20925. 1000, "text/plain",
  20926. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20927. if (offset < 100) {
  20928. std::string data(100, 'A');
  20929. sink.write(data.c_str(), data.size());
  20930. return true;
  20931. }
  20932. std::this_thread::sleep_for(std::chrono::seconds(3));
  20933. std::string data(900, 'B');
  20934. sink.write(data.c_str(), data.size());
  20935. return true;
  20936. });
  20937. });
  20938. auto port = 8093;
  20939. std::thread t([&]() { svr.listen("localhost", port); });
  20940. svr.wait_until_ready();
  20941. SSLClient cli("localhost", port);
  20942. cli.enable_server_certificate_verification(false);
  20943. cli.set_read_timeout(1, 0); // 1 second timeout
  20944. auto handle = cli.open_stream("GET", "/slow-stream");
  20945. ASSERT_TRUE(handle.is_valid());
  20946. char buf[256];
  20947. ssize_t total = 0;
  20948. ssize_t n;
  20949. bool got_error = false;
  20950. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20951. total += n;
  20952. }
  20953. if (n < 0) {
  20954. got_error = true;
  20955. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20956. handle.get_read_error() == Error::Read)
  20957. << "Actual error: " << to_string(handle.get_read_error());
  20958. }
  20959. EXPECT_TRUE(got_error || total < 1000)
  20960. << "Expected timeout but got all " << total << " bytes";
  20961. svr.stop();
  20962. t.join();
  20963. }
  20964. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20965. // Test SSL connection closed detection
  20966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20967. std::atomic<bool> close_now{false};
  20968. svr.Get("/will-close", [&](const Request &, Response &res) {
  20969. res.set_content_provider(
  20970. 10000, "text/plain",
  20971. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20972. if (offset < 100) {
  20973. std::string data(100, 'X');
  20974. sink.write(data.c_str(), data.size());
  20975. return true;
  20976. }
  20977. while (!close_now) {
  20978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20979. }
  20980. return false;
  20981. });
  20982. });
  20983. auto port = 8094;
  20984. std::thread t([&]() { svr.listen("localhost", port); });
  20985. svr.wait_until_ready();
  20986. SSLClient cli("localhost", port);
  20987. cli.enable_server_certificate_verification(false);
  20988. auto handle = cli.open_stream("GET", "/will-close");
  20989. ASSERT_TRUE(handle.is_valid());
  20990. char buf[256];
  20991. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20992. EXPECT_GT(n, 0);
  20993. // Signal server to close
  20994. close_now = true;
  20995. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20996. // Keep reading
  20997. }
  20998. if (n < 0) {
  20999. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21000. handle.get_read_error() == Error::Read)
  21001. << "Actual error: " << to_string(handle.get_read_error());
  21002. }
  21003. svr.stop();
  21004. t.join();
  21005. }
  21006. #endif
  21007. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21008. using namespace httplib;
  21009. // Create a test file
  21010. const char *fname = "etag_testfile.txt";
  21011. const char *content = "etag-content";
  21012. {
  21013. std::ofstream ofs(fname);
  21014. ofs << content;
  21015. ASSERT_TRUE(ofs.good());
  21016. }
  21017. Server svr;
  21018. svr.set_mount_point("/static", ".");
  21019. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21020. svr.wait_until_ready();
  21021. Client cli(HOST, PORT);
  21022. // First request: should get 200 with ETag header
  21023. auto res1 = cli.Get("/static/etag_testfile.txt");
  21024. ASSERT_TRUE(res1);
  21025. ASSERT_EQ(200, res1->status);
  21026. ASSERT_TRUE(res1->has_header("ETag"));
  21027. std::string etag = res1->get_header_value("ETag");
  21028. EXPECT_FALSE(etag.empty());
  21029. // Verify ETag format: W/"hex-hex"
  21030. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21031. EXPECT_EQ('W', etag[0]);
  21032. EXPECT_EQ('/', etag[1]);
  21033. EXPECT_EQ('"', etag[2]);
  21034. EXPECT_EQ('"', etag.back());
  21035. // Exact match: expect 304 Not Modified
  21036. Headers h2 = {{"If-None-Match", etag}};
  21037. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21038. ASSERT_TRUE(res2);
  21039. EXPECT_EQ(304, res2->status);
  21040. // Wildcard match: expect 304 Not Modified
  21041. Headers h3 = {{"If-None-Match", "*"}};
  21042. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21043. ASSERT_TRUE(res3);
  21044. EXPECT_EQ(304, res3->status);
  21045. // Non-matching ETag: expect 200
  21046. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21047. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21048. ASSERT_TRUE(res4);
  21049. EXPECT_EQ(200, res4->status);
  21050. // Multiple ETags with one matching: expect 304
  21051. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21052. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21053. ASSERT_TRUE(res5);
  21054. EXPECT_EQ(304, res5->status);
  21055. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21056. // that equivalent to the single comma-separated list above, so the match on
  21057. // the second line must still be found.
  21058. Headers h6;
  21059. h6.emplace("If-None-Match", "W/\"other\"");
  21060. h6.emplace("If-None-Match", etag);
  21061. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21062. ASSERT_TRUE(res6);
  21063. EXPECT_EQ(304, res6->status);
  21064. svr.stop();
  21065. t.join();
  21066. std::remove(fname);
  21067. }
  21068. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21069. using namespace httplib;
  21070. Server svr;
  21071. svr.set_mount_point("/static", ".");
  21072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21073. svr.wait_until_ready();
  21074. Client cli(HOST, PORT);
  21075. // Send If-None-Match: * to a non-existent file
  21076. Headers h = {{"If-None-Match", "*"}};
  21077. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21079. EXPECT_EQ(404, res->status);
  21080. svr.stop();
  21081. t.join();
  21082. }
  21083. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21084. using namespace httplib;
  21085. // Create a test file
  21086. const char *fname = "etag_boundary_testfile.txt";
  21087. const char *content = "boundary-test";
  21088. {
  21089. std::ofstream ofs(fname);
  21090. ofs << content;
  21091. ASSERT_TRUE(ofs.good());
  21092. }
  21093. Server svr;
  21094. svr.set_mount_point("/static", ".");
  21095. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21096. svr.wait_until_ready();
  21097. Client cli(HOST, PORT);
  21098. // Get the actual ETag
  21099. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21100. ASSERT_TRUE(res1);
  21101. ASSERT_EQ(200, res1->status);
  21102. ASSERT_TRUE(res1->has_header("ETag"));
  21103. std::string etag = res1->get_header_value("ETag");
  21104. // Test 1: Very long ETag value (longer than actual ETag)
  21105. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21106. Headers h1 = {{"If-None-Match", "W/"
  21107. "\"very-long-etag-value-that-is-much-longer-"
  21108. "than-the-actual-etag-value\""}};
  21109. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21110. ASSERT_TRUE(res2);
  21111. EXPECT_EQ(200, res2->status); // Should not match
  21112. // Test 2: Long string followed by wildcard
  21113. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21114. // string)
  21115. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21116. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21117. ASSERT_TRUE(res3);
  21118. EXPECT_EQ(304, res3->status); // Should match on "*"
  21119. // Test 3: Wildcard followed by long string
  21120. // Should match on "*" immediately and return 304
  21121. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21122. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21123. ASSERT_TRUE(res4);
  21124. EXPECT_EQ(304, res4->status); // Should match on "*"
  21125. // Test 4: Multiple long non-matching values
  21126. // Should NOT match and return 200 (test that all comparisons are safe)
  21127. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21128. "W/\"second-long-non-matching-value\", "
  21129. "W/\"third-long-non-matching-value\""}};
  21130. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21131. ASSERT_TRUE(res5);
  21132. EXPECT_EQ(200, res5->status); // Should not match
  21133. // Test 5: Single character that is not "*" (edge case)
  21134. Headers h5 = {{"If-None-Match", "X"}};
  21135. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21136. ASSERT_TRUE(res6);
  21137. EXPECT_EQ(200, res6->status); // Should not match
  21138. svr.stop();
  21139. t.join();
  21140. std::remove(fname);
  21141. }
  21142. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21143. using namespace httplib;
  21144. // Create a test file
  21145. const char *fname = "ims_testfile.txt";
  21146. const char *content = "if-modified-since-test";
  21147. {
  21148. std::ofstream ofs(fname);
  21149. ofs << content;
  21150. ASSERT_TRUE(ofs.good());
  21151. }
  21152. Server svr;
  21153. svr.set_mount_point("/static", ".");
  21154. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21155. svr.wait_until_ready();
  21156. Client cli(HOST, PORT);
  21157. // First request: should get 200 with Last-Modified header
  21158. auto res1 = cli.Get("/static/ims_testfile.txt");
  21159. ASSERT_TRUE(res1);
  21160. ASSERT_EQ(200, res1->status);
  21161. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21162. std::string last_modified = res1->get_header_value("Last-Modified");
  21163. EXPECT_FALSE(last_modified.empty());
  21164. // If-Modified-Since with same time: expect 304
  21165. Headers h2 = {{"If-Modified-Since", last_modified}};
  21166. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21167. ASSERT_TRUE(res2);
  21168. EXPECT_EQ(304, res2->status);
  21169. // If-Modified-Since with future time: expect 304
  21170. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21171. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21172. ASSERT_TRUE(res3);
  21173. EXPECT_EQ(304, res3->status);
  21174. // If-Modified-Since with past time: expect 200
  21175. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21176. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21177. ASSERT_TRUE(res4);
  21178. EXPECT_EQ(200, res4->status);
  21179. // If-None-Match takes precedence over If-Modified-Since
  21180. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21181. ASSERT_TRUE(res1->has_header("ETag"));
  21182. std::string etag = res1->get_header_value("ETag");
  21183. Headers h5 = {{"If-None-Match", etag},
  21184. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21185. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21186. ASSERT_TRUE(res5);
  21187. EXPECT_EQ(304, res5->status);
  21188. svr.stop();
  21189. t.join();
  21190. std::remove(fname);
  21191. }
  21192. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21193. using namespace httplib;
  21194. Server svr;
  21195. // Endpoint that returns compressible content
  21196. svr.Get("/compressible", [](const Request &, Response &res) {
  21197. // Return a large enough body to trigger compression
  21198. std::string body(1000, 'a');
  21199. res.set_content(body, "text/plain");
  21200. });
  21201. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21202. svr.wait_until_ready();
  21203. Client cli(HOST, PORT);
  21204. // Request with gzip support: should get Vary header when compressed
  21205. cli.set_compress(true);
  21206. auto res1 = cli.Get("/compressible");
  21207. ASSERT_TRUE(res1);
  21208. EXPECT_EQ(200, res1->status);
  21209. // If Content-Encoding is set, Vary should also be set
  21210. if (res1->has_header("Content-Encoding")) {
  21211. EXPECT_TRUE(res1->has_header("Vary"));
  21212. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21213. }
  21214. // Request without Accept-Encoding header: should not have compression
  21215. Headers h_no_compress;
  21216. auto res2 = cli.Get("/compressible", h_no_compress);
  21217. ASSERT_TRUE(res2);
  21218. EXPECT_EQ(200, res2->status);
  21219. // Verify Vary header is present when compression is applied
  21220. // (the exact behavior depends on server configuration)
  21221. svr.stop();
  21222. t.join();
  21223. }
  21224. TEST(ETagTest, IfRangeWithETag) {
  21225. using namespace httplib;
  21226. // Create a test file with known content
  21227. const char *fname = "if_range_testfile.txt";
  21228. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21229. {
  21230. std::ofstream ofs(fname);
  21231. ofs << content;
  21232. ASSERT_TRUE(ofs.good());
  21233. }
  21234. Server svr;
  21235. svr.set_mount_point("/static", ".");
  21236. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21237. svr.wait_until_ready();
  21238. Client cli(HOST, PORT);
  21239. // First request: get ETag
  21240. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21241. ASSERT_TRUE(res1);
  21242. ASSERT_EQ(200, res1->status);
  21243. ASSERT_TRUE(res1->has_header("ETag"));
  21244. std::string etag = res1->get_header_value("ETag");
  21245. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21246. // Since our server generates weak ETags (W/"..."), If-Range with our
  21247. // ETag should NOT result in partial content - it should return full content.
  21248. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21249. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21250. ASSERT_TRUE(res2);
  21251. // Weak ETag in If-Range -> full content (200), not partial (206)
  21252. EXPECT_EQ(200, res2->status);
  21253. EXPECT_EQ(content, res2->body);
  21254. EXPECT_FALSE(res2->has_header("Content-Range"));
  21255. // Range request with non-matching If-Range (ETag): should get 200 (full
  21256. // content)
  21257. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21258. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21259. ASSERT_TRUE(res3);
  21260. EXPECT_EQ(200, res3->status);
  21261. EXPECT_EQ(content, res3->body);
  21262. EXPECT_FALSE(res3->has_header("Content-Range"));
  21263. // Range request with strong ETag (hypothetical - our server doesn't generate
  21264. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21265. // should return full content)
  21266. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21267. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21268. ASSERT_TRUE(res4);
  21269. EXPECT_EQ(200, res4->status);
  21270. EXPECT_EQ(content, res4->body);
  21271. EXPECT_FALSE(res4->has_header("Content-Range"));
  21272. svr.stop();
  21273. t.join();
  21274. std::remove(fname);
  21275. }
  21276. TEST(ETagTest, IfRangeWithDate) {
  21277. using namespace httplib;
  21278. // Create a test file
  21279. const char *fname = "if_range_date_testfile.txt";
  21280. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21281. {
  21282. std::ofstream ofs(fname);
  21283. ofs << content;
  21284. ASSERT_TRUE(ofs.good());
  21285. }
  21286. Server svr;
  21287. svr.set_mount_point("/static", ".");
  21288. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21289. svr.wait_until_ready();
  21290. Client cli(HOST, PORT);
  21291. // First request: get Last-Modified
  21292. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21293. ASSERT_TRUE(res1);
  21294. ASSERT_EQ(200, res1->status);
  21295. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21296. std::string last_modified = res1->get_header_value("Last-Modified");
  21297. // Range request with matching If-Range (date): should get 206
  21298. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21299. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21300. ASSERT_TRUE(res2);
  21301. EXPECT_EQ(206, res2->status);
  21302. EXPECT_EQ("FGHIJ", res2->body);
  21303. // Range request with old If-Range date: should get 200 (full content)
  21304. Headers h3 = {{"Range", "bytes=5-9"},
  21305. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21306. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21307. ASSERT_TRUE(res3);
  21308. EXPECT_EQ(200, res3->status);
  21309. EXPECT_EQ(content, res3->body);
  21310. // Range request with future If-Range date: should get 206
  21311. Headers h4 = {{"Range", "bytes=0-4"},
  21312. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21313. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21314. ASSERT_TRUE(res4);
  21315. EXPECT_EQ(206, res4->status);
  21316. EXPECT_EQ("ABCDE", res4->body);
  21317. svr.stop();
  21318. t.join();
  21319. std::remove(fname);
  21320. }
  21321. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21322. using namespace httplib;
  21323. const char *fname = "etag_malformed.txt";
  21324. const char *content = "malformed-etag";
  21325. {
  21326. std::ofstream ofs(fname);
  21327. ofs << content;
  21328. ASSERT_TRUE(ofs.good());
  21329. }
  21330. Server svr;
  21331. svr.set_mount_point("/static", ".");
  21332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21333. svr.wait_until_ready();
  21334. Client cli(HOST, PORT);
  21335. // baseline: should get 200 and an ETag
  21336. auto res1 = cli.Get("/static/etag_malformed.txt");
  21337. ASSERT_TRUE(res1);
  21338. ASSERT_EQ(200, res1->status);
  21339. ASSERT_TRUE(res1->has_header("ETag"));
  21340. // Malformed ETag value (missing quotes) should be treated as non-matching
  21341. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21342. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21343. ASSERT_TRUE(res_bad);
  21344. EXPECT_EQ(200, res_bad->status);
  21345. // Whitespace-only header value should be considered invalid / non-matching
  21346. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21347. "Host: localhost\r\n"
  21348. "If-None-Match: \r\n"
  21349. "Connection: close\r\n"
  21350. "\r\n";
  21351. std::string out;
  21352. ASSERT_TRUE(send_request(5, raw_req, &out));
  21353. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21354. svr.stop();
  21355. t.join();
  21356. std::remove(fname);
  21357. }
  21358. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21359. using namespace httplib;
  21360. const char *fname = "ims_invalid_format.txt";
  21361. const char *content = "ims-bad-format";
  21362. {
  21363. std::ofstream ofs(fname);
  21364. ofs << content;
  21365. ASSERT_TRUE(ofs.good());
  21366. }
  21367. Server svr;
  21368. svr.set_mount_point("/static", ".");
  21369. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21370. svr.wait_until_ready();
  21371. Client cli(HOST, PORT);
  21372. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21373. ASSERT_TRUE(res1);
  21374. ASSERT_EQ(200, res1->status);
  21375. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21376. // If-Modified-Since with invalid format should not result in 304
  21377. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21378. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21379. ASSERT_TRUE(res_bad);
  21380. EXPECT_EQ(200, res_bad->status);
  21381. // If-Range with invalid date format should be treated as mismatch -> full
  21382. // content (200)
  21383. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21384. {"If-Range", "invalid-date"}};
  21385. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21386. ASSERT_TRUE(res_ifrange);
  21387. EXPECT_EQ(200, res_ifrange->status);
  21388. svr.stop();
  21389. t.join();
  21390. std::remove(fname);
  21391. }
  21392. TEST(ETagTest, IfRangeWithMalformedETag) {
  21393. using namespace httplib;
  21394. const char *fname = "ifrange_malformed.txt";
  21395. const std::string content = "0123456789";
  21396. {
  21397. std::ofstream ofs(fname);
  21398. ofs << content;
  21399. ASSERT_TRUE(ofs.good());
  21400. }
  21401. Server svr;
  21402. svr.set_mount_point("/static", ".");
  21403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21404. svr.wait_until_ready();
  21405. Client cli(HOST, PORT);
  21406. // First request: get ETag
  21407. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21408. ASSERT_TRUE(res1);
  21409. ASSERT_EQ(200, res1->status);
  21410. ASSERT_TRUE(res1->has_header("ETag"));
  21411. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21412. // full content (200)
  21413. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21414. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21415. ASSERT_TRUE(res2);
  21416. EXPECT_EQ(200, res2->status);
  21417. EXPECT_EQ(content, res2->body);
  21418. svr.stop();
  21419. t.join();
  21420. std::remove(fname);
  21421. }
  21422. TEST(ETagTest, ExtremeLargeDateValues) {
  21423. using namespace httplib;
  21424. const char *fname = "ims_extreme_date.txt";
  21425. const char *content = "ims-extreme-date";
  21426. {
  21427. std::ofstream ofs(fname);
  21428. ofs << content;
  21429. ASSERT_TRUE(ofs.good());
  21430. }
  21431. Server svr;
  21432. svr.set_mount_point("/static", ".");
  21433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21434. svr.wait_until_ready();
  21435. Client cli(HOST, PORT);
  21436. auto res1 = cli.Get(std::string("/static/") + fname);
  21437. ASSERT_TRUE(res1);
  21438. ASSERT_EQ(200, res1->status);
  21439. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21440. // Extremely large year that may overflow date parsing routines.
  21441. Headers h_large_date = {
  21442. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21443. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21444. ASSERT_TRUE(res_bad);
  21445. // Expect server to treat this as invalid/mismatch and return full content
  21446. EXPECT_EQ(200, res_bad->status);
  21447. // If-Range with extremely large date should be treated as mismatch -> full
  21448. // content (200)
  21449. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21450. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21451. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21452. ASSERT_TRUE(res_ifrange);
  21453. EXPECT_EQ(200, res_ifrange->status);
  21454. svr.stop();
  21455. t.join();
  21456. std::remove(fname);
  21457. }
  21458. TEST(ETagTest, NegativeFileModificationTime) {
  21459. using namespace httplib;
  21460. const char *fname = "ims_negative_mtime.txt";
  21461. const std::string content = "negative-mtime";
  21462. {
  21463. std::ofstream ofs(fname);
  21464. ofs << content;
  21465. ASSERT_TRUE(ofs.good());
  21466. }
  21467. // Try to set file mtime to a negative value. This may fail on some
  21468. // platforms/filesystems; if it fails, the test will still verify server
  21469. // behaves safely by performing a regular conditional request.
  21470. #if defined(__APPLE__) || defined(__linux__)
  21471. bool set_negative = false;
  21472. do {
  21473. struct timeval times[2];
  21474. // access time: now
  21475. times[0].tv_sec = time(nullptr);
  21476. times[0].tv_usec = 0;
  21477. // modification time: negative (e.g., -1)
  21478. times[1].tv_sec = -1;
  21479. times[1].tv_usec = 0;
  21480. if (utimes(fname, times) == 0) { set_negative = true; }
  21481. } while (0);
  21482. #else
  21483. bool set_negative = false;
  21484. #endif
  21485. Server svr;
  21486. svr.set_mount_point("/static", ".");
  21487. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21488. svr.wait_until_ready();
  21489. Client cli(HOST, PORT);
  21490. auto res1 = cli.Get(std::string("/static/") + fname);
  21491. ASSERT_TRUE(res1);
  21492. ASSERT_EQ(200, res1->status);
  21493. bool has_last_modified = res1->has_header("Last-Modified");
  21494. std::string last_modified;
  21495. if (has_last_modified) {
  21496. last_modified = res1->get_header_value("Last-Modified");
  21497. }
  21498. if (set_negative) {
  21499. // If we successfully set a negative mtime, ensure server returns a
  21500. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21501. // with an old date and ensure server handles it without crash.
  21502. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21503. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21504. ASSERT_TRUE(res2);
  21505. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21506. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21507. } else {
  21508. // Could not set negative mtime on this platform; fall back to verifying
  21509. // that normal invalid/malformed dates are treated safely (non-304).
  21510. Headers h_bad_date = {
  21511. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21512. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21513. ASSERT_TRUE(res_bad);
  21514. EXPECT_EQ(200, res_bad->status);
  21515. }
  21516. svr.stop();
  21517. t.join();
  21518. std::remove(fname);
  21519. }
  21520. //==============================================================================
  21521. // Integration Tests with Server
  21522. //==============================================================================
  21523. class SSEIntegrationTest : public ::testing::Test {
  21524. protected:
  21525. void SetUp() override {
  21526. stop_server_.store(false);
  21527. events_.clear();
  21528. server_ = httplib::detail::make_unique<Server>();
  21529. setup_server();
  21530. start_server();
  21531. }
  21532. void TearDown() override {
  21533. stop_server_.store(true);
  21534. event_cv_.notify_all();
  21535. server_->stop();
  21536. if (server_thread_.joinable()) { server_thread_.join(); }
  21537. }
  21538. void setup_server() {
  21539. // Simple SSE endpoint
  21540. server_->Get("/events", [this](const Request &req, Response &res) {
  21541. auto last_id = req.get_header_value("Last-Event-ID");
  21542. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21543. res.set_chunked_content_provider(
  21544. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21545. std::unique_lock<std::mutex> lock(event_mutex_);
  21546. if (event_cv_.wait_for(
  21547. lock, std::chrono::milliseconds(200), [this] {
  21548. return !events_.empty() || stop_server_.load();
  21549. })) {
  21550. if (stop_server_.load()) { return false; }
  21551. if (!events_.empty()) {
  21552. std::string event = events_.front();
  21553. events_.erase(events_.begin());
  21554. sink.write(event.data(), event.size());
  21555. return true;
  21556. }
  21557. }
  21558. return !stop_server_.load();
  21559. });
  21560. });
  21561. // Endpoint that returns error
  21562. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21563. res.status = 500;
  21564. res.set_content("Internal Server Error", "text/plain");
  21565. });
  21566. // Endpoint for custom event types
  21567. server_->Get("/custom-events", [](const Request &, Response &res) {
  21568. res.set_chunked_content_provider(
  21569. "text/event-stream", [](size_t offset, DataSink &sink) {
  21570. if (offset == 0) {
  21571. std::string event = "event: update\ndata: updated\n\n"
  21572. "event: delete\ndata: deleted\n\n";
  21573. sink.write(event.data(), event.size());
  21574. }
  21575. return false; // End stream after sending
  21576. });
  21577. });
  21578. }
  21579. void start_server() {
  21580. port_ = server_->bind_to_any_port(HOST);
  21581. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21582. // Wait for server to start
  21583. while (!server_->is_running()) {
  21584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21585. }
  21586. }
  21587. int get_port() const { return port_; }
  21588. void send_event(const std::string &event) {
  21589. std::lock_guard<std::mutex> lock(event_mutex_);
  21590. events_.push_back(event);
  21591. event_cv_.notify_all();
  21592. }
  21593. std::unique_ptr<Server> server_;
  21594. std::thread server_thread_;
  21595. std::mutex event_mutex_;
  21596. std::condition_variable event_cv_;
  21597. std::vector<std::string> events_;
  21598. std::atomic<bool> stop_server_{false};
  21599. std::string last_received_event_id_;
  21600. int port_ = 0;
  21601. };
  21602. //==============================================================================
  21603. // SSE Parsing Tests
  21604. //==============================================================================
  21605. class SSEParsingTest : public SSEIntegrationTest {
  21606. protected:
  21607. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21608. // A trailing sentinel event tells when the whole stream has been parsed.
  21609. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21610. auto body = stream + "event: end\ndata: end\n\n";
  21611. server_->Get("/parse", [body](const Request &, Response &res) {
  21612. res.set_content(body, "text/event-stream");
  21613. });
  21614. return collect("/parse");
  21615. }
  21616. // Runs SSEClient against path until an "end" event arrives and returns the
  21617. // messages dispatched before it
  21618. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21619. Client client(HOST, get_port());
  21620. sse::SSEClient sse(client, path);
  21621. std::mutex mutex;
  21622. std::condition_variable cv;
  21623. std::vector<sse::SSEMessage> messages;
  21624. auto done = false;
  21625. sse.on_message([&](const sse::SSEMessage &msg) {
  21626. std::lock_guard<std::mutex> lock(mutex);
  21627. // Ignore a replay from a reconnect that races with stop()
  21628. if (!done) { messages.push_back(msg); }
  21629. });
  21630. sse.on_event("end", [&](const sse::SSEMessage &) {
  21631. std::lock_guard<std::mutex> lock(mutex);
  21632. done = true;
  21633. cv.notify_all();
  21634. });
  21635. sse.set_reconnect_interval(100);
  21636. sse.start_async();
  21637. {
  21638. std::unique_lock<std::mutex> lock(mutex);
  21639. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21640. }
  21641. sse.stop();
  21642. EXPECT_TRUE(done);
  21643. return messages;
  21644. }
  21645. };
  21646. TEST_F(SSEParsingTest, SingleLineData) {
  21647. auto msgs = parse("data: hello\n\n");
  21648. ASSERT_EQ(msgs.size(), 1u);
  21649. EXPECT_EQ(msgs[0].data, "hello");
  21650. EXPECT_EQ(msgs[0].event, "message");
  21651. }
  21652. TEST_F(SSEParsingTest, MultiLineData) {
  21653. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21654. ASSERT_EQ(msgs.size(), 1u);
  21655. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21656. }
  21657. TEST_F(SSEParsingTest, CustomEventType) {
  21658. auto msgs = parse("event: update\ndata: payload\n\n");
  21659. ASSERT_EQ(msgs.size(), 1u);
  21660. EXPECT_EQ(msgs[0].event, "update");
  21661. EXPECT_EQ(msgs[0].data, "payload");
  21662. }
  21663. TEST_F(SSEParsingTest, EventIdHandling) {
  21664. auto msgs = parse("id: 12345\ndata: test\n\n");
  21665. ASSERT_EQ(msgs.size(), 1u);
  21666. EXPECT_EQ(msgs[0].id, "12345");
  21667. }
  21668. TEST_F(SSEParsingTest, EmptyEventId) {
  21669. auto msgs = parse("id:\ndata: test\n\n");
  21670. ASSERT_EQ(msgs.size(), 1u);
  21671. EXPECT_EQ(msgs[0].id, "");
  21672. }
  21673. TEST_F(SSEParsingTest, CommentsIgnored) {
  21674. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21675. ASSERT_EQ(msgs.size(), 1u);
  21676. EXPECT_EQ(msgs[0].data, "hello");
  21677. EXPECT_EQ(msgs[0].event, "message");
  21678. }
  21679. TEST_F(SSEParsingTest, ColonInValue) {
  21680. auto msgs = parse("data: hello:world:test\n\n");
  21681. ASSERT_EQ(msgs.size(), 1u);
  21682. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21683. }
  21684. TEST_F(SSEParsingTest, FieldNameOnly) {
  21685. // A line without a colon is a field name with an empty value
  21686. auto msgs = parse("data\n\n");
  21687. ASSERT_EQ(msgs.size(), 1u);
  21688. EXPECT_EQ(msgs[0].data, "");
  21689. }
  21690. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21691. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21692. ASSERT_EQ(msgs.size(), 1u);
  21693. EXPECT_EQ(msgs[0].event, "update");
  21694. EXPECT_EQ(msgs[0].data, "hello");
  21695. }
  21696. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21697. auto msgs = parse("data\r\n\r\n");
  21698. ASSERT_EQ(msgs.size(), 1u);
  21699. EXPECT_EQ(msgs[0].data, "");
  21700. }
  21701. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21702. auto msgs = parse("event: update\rdata: hello\r\r");
  21703. ASSERT_EQ(msgs.size(), 1u);
  21704. EXPECT_EQ(msgs[0].event, "update");
  21705. EXPECT_EQ(msgs[0].data, "hello");
  21706. }
  21707. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21708. // Chunk boundaries fall inside every \r\n and right before the first one
  21709. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21710. "\n\r", "\nevent: end\ndata: end\n\n"};
  21711. server_->Get("/split", [chunks](const Request &, Response &res) {
  21712. auto i = std::make_shared<size_t>(0);
  21713. res.set_chunked_content_provider(
  21714. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21715. if (*i == chunks.size()) {
  21716. sink.done();
  21717. } else {
  21718. sink.write(chunks[*i].data(), chunks[*i].size());
  21719. (*i)++;
  21720. }
  21721. return true;
  21722. });
  21723. });
  21724. auto msgs = collect("/split");
  21725. ASSERT_EQ(msgs.size(), 1u);
  21726. EXPECT_EQ(msgs[0].event, "update");
  21727. EXPECT_EQ(msgs[0].data, "hello");
  21728. }
  21729. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21730. // Only a BOM at the start of the stream is ignored
  21731. auto msgs = parse("\xEF\xBB\xBF"
  21732. "data: first\n\n"
  21733. "\xEF\xBB\xBF"
  21734. "data: second\n\n");
  21735. ASSERT_EQ(msgs.size(), 1u);
  21736. EXPECT_EQ(msgs[0].data, "first");
  21737. }
  21738. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21739. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21740. ASSERT_EQ(msgs.size(), 1u);
  21741. EXPECT_EQ(msgs[0].data, "hello");
  21742. EXPECT_EQ(msgs[0].event, "message");
  21743. }
  21744. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21745. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21746. ASSERT_EQ(msgs.size(), 2u);
  21747. EXPECT_EQ(msgs[0].data, "hello");
  21748. EXPECT_EQ(msgs[1].data, "hello");
  21749. }
  21750. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21751. // An event without data is not dispatched, and its type must not leak
  21752. // into the next event
  21753. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21754. ASSERT_EQ(msgs.size(), 1u);
  21755. EXPECT_EQ(msgs[0].event, "message");
  21756. EXPECT_EQ(msgs[0].data, "hello");
  21757. }
  21758. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21759. // Also when the empty field replaces an earlier type
  21760. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21761. ASSERT_EQ(msgs.size(), 2u);
  21762. EXPECT_EQ(msgs[0].event, "message");
  21763. EXPECT_EQ(msgs[1].event, "message");
  21764. }
  21765. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21766. // The first connection sends only an id; the second echoes back the
  21767. // Last-Event-ID it was reconnected with
  21768. std::atomic<int> connection_count{0};
  21769. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21770. if (connection_count++ == 0) {
  21771. res.set_content("id: 42\n\n", "text/event-stream");
  21772. } else {
  21773. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21774. "\n\nevent: end\ndata: end\n\n",
  21775. "text/event-stream");
  21776. }
  21777. });
  21778. auto msgs = collect("/id-only");
  21779. ASSERT_EQ(msgs.size(), 1u);
  21780. EXPECT_EQ(msgs[0].data, "42");
  21781. }
  21782. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21783. // The first connection sets an id and then clears it with an empty one; the
  21784. // second reports whether it was reconnected with a Last-Event-ID
  21785. std::atomic<int> connection_count{0};
  21786. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21787. if (connection_count++ == 0) {
  21788. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21789. "text/event-stream");
  21790. } else {
  21791. res.set_content(
  21792. std::string("data: ") +
  21793. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21794. "\n\nevent: end\ndata: end\n\n",
  21795. "text/event-stream");
  21796. }
  21797. });
  21798. auto msgs = collect("/id-clear");
  21799. ASSERT_EQ(msgs.size(), 3u);
  21800. EXPECT_EQ(msgs[0].id, "1");
  21801. EXPECT_EQ(msgs[1].id, "");
  21802. EXPECT_EQ(msgs[2].data, "not sent");
  21803. }
  21804. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21805. // The first connection sets an id and then sends ids that cannot be carried
  21806. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21807. // with
  21808. std::atomic<int> connection_count{0};
  21809. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21810. if (connection_count++ == 0) {
  21811. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21812. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21813. "text/event-stream");
  21814. } else {
  21815. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21816. "\n\nevent: end\ndata: end\n\n",
  21817. "text/event-stream");
  21818. }
  21819. });
  21820. auto msgs = collect("/id-unsendable");
  21821. ASSERT_EQ(msgs.size(), 1u);
  21822. EXPECT_EQ(msgs[0].data, "42");
  21823. }
  21824. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21825. auto msgs = parse("event: notification\nid: evt-42\n"
  21826. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21827. ASSERT_EQ(msgs.size(), 1u);
  21828. EXPECT_EQ(msgs[0].event, "notification");
  21829. EXPECT_EQ(msgs[0].id, "evt-42");
  21830. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21831. }
  21832. TEST(SSEMessageTest, Clear) {
  21833. sse::SSEMessage msg;
  21834. msg.event = "custom";
  21835. msg.data = "some data";
  21836. msg.id = "123";
  21837. msg.clear();
  21838. EXPECT_EQ(msg.event, "message");
  21839. EXPECT_EQ(msg.data, "");
  21840. EXPECT_EQ(msg.id, "");
  21841. }
  21842. //==============================================================================
  21843. // SSE Integration Tests
  21844. //==============================================================================
  21845. // Test: Successful connection and on_open callback
  21846. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21847. // Add a simple endpoint that sends one event and closes
  21848. server_->Get("/simple-event", [](const Request &, Response &res) {
  21849. res.set_chunked_content_provider(
  21850. "text/event-stream", [](size_t offset, DataSink &sink) {
  21851. if (offset == 0) {
  21852. std::string event = "data: hello\n\n";
  21853. sink.write(event.data(), event.size());
  21854. }
  21855. return false; // Close stream after sending
  21856. });
  21857. });
  21858. Client client("localhost", get_port());
  21859. sse::SSEClient sse(client, "/simple-event");
  21860. std::atomic<bool> open_called{false};
  21861. std::atomic<bool> message_received{false};
  21862. sse.on_open([&open_called]() { open_called.store(true); });
  21863. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21864. if (msg.data == "hello") { message_received.store(true); }
  21865. });
  21866. sse.set_reconnect_interval(100);
  21867. sse.set_max_reconnect_attempts(1);
  21868. // Start async
  21869. sse.start_async();
  21870. // Wait for message to be processed
  21871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21872. sse.stop();
  21873. EXPECT_TRUE(open_called.load());
  21874. EXPECT_TRUE(message_received.load());
  21875. }
  21876. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21877. // A data line that never ends.
  21878. server_->Get("/endless-line", [](const Request &, Response &res) {
  21879. res.set_chunked_content_provider(
  21880. "text/event-stream", [](size_t offset, DataSink &sink) {
  21881. if (offset == 0) { sink.write("data: ", 6); }
  21882. std::string chunk(64 * 1024, 'A');
  21883. return sink.write(chunk.data(), chunk.size());
  21884. });
  21885. });
  21886. Client client("localhost", get_port());
  21887. sse::SSEClient sse(client, "/endless-line");
  21888. std::atomic<bool> too_long{false};
  21889. sse.on_error([&](Error err) {
  21890. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21891. });
  21892. sse.set_max_reconnect_attempts(1);
  21893. sse.start_async();
  21894. for (int i = 0; i < 500 && !too_long; i++) {
  21895. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21896. }
  21897. sse.stop();
  21898. EXPECT_TRUE(too_long);
  21899. }
  21900. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21901. // Far more in all than the client's payload limit below.
  21902. server_->Get("/many-events", [](const Request &, Response &res) {
  21903. res.set_chunked_content_provider(
  21904. "text/event-stream", [](size_t offset, DataSink &sink) {
  21905. if (offset == 0) {
  21906. std::string events;
  21907. for (int i = 0; i < 1000; i++) {
  21908. events += "data: message\n\n";
  21909. }
  21910. sink.write(events.data(), events.size());
  21911. }
  21912. return false;
  21913. });
  21914. });
  21915. Client client("localhost", get_port());
  21916. client.set_payload_max_length(1024);
  21917. sse::SSEClient sse(client, "/many-events");
  21918. std::atomic<int> messages{0};
  21919. std::atomic<bool> too_large{false};
  21920. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21921. sse.on_error([&](Error err) {
  21922. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21923. });
  21924. sse.set_max_reconnect_attempts(1);
  21925. sse.start_async();
  21926. for (int i = 0; i < 500 && messages < 1000; i++) {
  21927. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21928. }
  21929. sse.stop();
  21930. EXPECT_GE(messages.load(), 1000);
  21931. EXPECT_FALSE(too_large);
  21932. }
  21933. // Test: on_message callback
  21934. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21935. // Endpoint that sends multiple events then closes
  21936. server_->Get("/multi-event", [](const Request &, Response &res) {
  21937. res.set_chunked_content_provider(
  21938. "text/event-stream", [](size_t offset, DataSink &sink) {
  21939. if (offset == 0) {
  21940. std::string events = "data: message1\n\ndata: message2\n\n";
  21941. sink.write(events.data(), events.size());
  21942. }
  21943. return false;
  21944. });
  21945. });
  21946. Client client("localhost", get_port());
  21947. sse::SSEClient sse(client, "/multi-event");
  21948. std::vector<std::string> received_messages;
  21949. std::mutex messages_mutex;
  21950. sse.on_message([&](const sse::SSEMessage &msg) {
  21951. std::lock_guard<std::mutex> lock(messages_mutex);
  21952. received_messages.push_back(msg.data);
  21953. });
  21954. sse.set_reconnect_interval(100);
  21955. sse.set_max_reconnect_attempts(1);
  21956. sse.start_async();
  21957. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21958. sse.stop();
  21959. std::lock_guard<std::mutex> lock(messages_mutex);
  21960. EXPECT_GE(received_messages.size(), 2u);
  21961. if (received_messages.size() >= 2) {
  21962. EXPECT_EQ(received_messages[0], "message1");
  21963. EXPECT_EQ(received_messages[1], "message2");
  21964. }
  21965. }
  21966. // Test: on_event for specific types
  21967. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21968. Client client("localhost", get_port());
  21969. sse::SSEClient sse(client, "/custom-events");
  21970. std::atomic<bool> update_received{false};
  21971. std::atomic<bool> delete_received{false};
  21972. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21973. if (msg.data == "updated") { update_received.store(true); }
  21974. });
  21975. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21976. if (msg.data == "deleted") { delete_received.store(true); }
  21977. });
  21978. sse.set_max_reconnect_attempts(1);
  21979. sse.start_async();
  21980. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21981. sse.stop();
  21982. EXPECT_TRUE(update_received.load());
  21983. EXPECT_TRUE(delete_received.load());
  21984. }
  21985. // Test: on_error callback on connection failure
  21986. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21987. // Connect to a non-existent port
  21988. Client client("localhost", 59999);
  21989. sse::SSEClient sse(client, "/events");
  21990. std::atomic<bool> error_called{false};
  21991. Error received_error = Error::Success;
  21992. sse.on_error([&](Error err) {
  21993. error_called.store(true);
  21994. received_error = err;
  21995. });
  21996. sse.set_reconnect_interval(50);
  21997. sse.set_max_reconnect_attempts(1);
  21998. sse.start_async();
  21999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22000. sse.stop();
  22001. EXPECT_TRUE(error_called.load());
  22002. EXPECT_NE(received_error, Error::Success);
  22003. }
  22004. // Test: Last-Event-ID header sent on reconnect
  22005. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22006. // Endpoint that sends event with ID
  22007. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22008. res.set_chunked_content_provider(
  22009. "text/event-stream", [](size_t offset, DataSink &sink) {
  22010. if (offset == 0) {
  22011. std::string event = "id: evt-123\ndata: test\n\n";
  22012. sink.write(event.data(), event.size());
  22013. }
  22014. return false;
  22015. });
  22016. });
  22017. Client client("localhost", get_port());
  22018. sse::SSEClient sse(client, "/event-with-id");
  22019. std::atomic<bool> id_received{false};
  22020. sse.on_message([&](const sse::SSEMessage &msg) {
  22021. if (!msg.id.empty()) { id_received.store(true); }
  22022. });
  22023. sse.set_reconnect_interval(100);
  22024. sse.set_max_reconnect_attempts(1);
  22025. sse.start_async();
  22026. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22027. sse.stop();
  22028. EXPECT_TRUE(id_received.load());
  22029. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22030. }
  22031. // Test: Manual stop
  22032. TEST_F(SSEIntegrationTest, ManualStop) {
  22033. // Endpoint that sends one event and stays open briefly. The server outlives
  22034. // this test body, so the provider uses the fixture's flag, not a local.
  22035. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22036. res.set_chunked_content_provider(
  22037. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22038. if (offset == 0) {
  22039. std::string event = "data: connected\n\n";
  22040. sink.write(event.data(), event.size());
  22041. }
  22042. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22043. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22044. }
  22045. return false;
  22046. });
  22047. });
  22048. Client client("localhost", get_port());
  22049. sse::SSEClient sse(client, "/stay-open");
  22050. std::atomic<bool> connected{false};
  22051. sse.on_open([&connected]() { connected.store(true); });
  22052. sse.set_reconnect_interval(100);
  22053. sse.set_max_reconnect_attempts(1);
  22054. sse.start_async();
  22055. // Wait for connection to establish
  22056. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22057. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22058. }
  22059. EXPECT_TRUE(connected.load());
  22060. EXPECT_TRUE(sse.is_connected());
  22061. // Signal handler to stop
  22062. stop_server_.store(true);
  22063. // Stop SSE client
  22064. sse.stop();
  22065. EXPECT_FALSE(sse.is_connected());
  22066. }
  22067. // Sends one event, then nothing until stop is set
  22068. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22069. return [&stop](const Request &, Response &res) {
  22070. res.set_chunked_content_provider(
  22071. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22072. if (offset == 0) {
  22073. std::string event = "data: hello\n\n";
  22074. sink.write(event.data(), event.size());
  22075. }
  22076. while (!stop.load()) {
  22077. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22078. }
  22079. return false;
  22080. });
  22081. };
  22082. }
  22083. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22084. static void check_stop_interrupts_blocked_read(Client &client) {
  22085. client.set_read_timeout(30, 0);
  22086. for (auto by_destructor : {false, true}) {
  22087. std::atomic<bool> received{false};
  22088. std::chrono::steady_clock::time_point start;
  22089. {
  22090. sse::SSEClient sse(client, "/idle-stream");
  22091. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22092. sse.start_async();
  22093. for (int i = 0; i < 500 && !received.load(); ++i) {
  22094. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22095. }
  22096. ASSERT_TRUE(received.load());
  22097. // Let the client block in the next read
  22098. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22099. start = std::chrono::steady_clock::now();
  22100. if (!by_destructor) { sse.stop(); }
  22101. }
  22102. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22103. std::chrono::seconds(2));
  22104. }
  22105. }
  22106. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22107. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22108. Client client("localhost", get_port());
  22109. check_stop_interrupts_blocked_read(client);
  22110. }
  22111. #ifdef CPPHTTPLIB_SSL_ENABLED
  22112. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22114. std::atomic<bool> done{false};
  22115. svr.Get("/idle-stream", idle_event_stream(done));
  22116. auto port = svr.bind_to_any_port(HOST);
  22117. std::thread t([&] { svr.listen_after_bind(); });
  22118. auto se = detail::scope_exit([&] {
  22119. done.store(true);
  22120. svr.stop();
  22121. t.join();
  22122. });
  22123. svr.wait_until_ready();
  22124. Client client("https://localhost:" + std::to_string(port));
  22125. client.enable_server_certificate_verification(false);
  22126. check_stop_interrupts_blocked_read(client);
  22127. }
  22128. #endif
  22129. // Test: SSEClient with custom headers
  22130. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22131. // Setup a server endpoint that checks for custom header
  22132. std::atomic<bool> header_received{false};
  22133. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22134. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22135. header_received.store(true);
  22136. }
  22137. res.set_chunked_content_provider("text/event-stream",
  22138. [](size_t, DataSink &) { return false; });
  22139. });
  22140. Client client("localhost", get_port());
  22141. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22142. sse::SSEClient sse(client, "/header-check", headers);
  22143. sse.set_max_reconnect_attempts(1);
  22144. sse.start_async();
  22145. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22146. sse.stop();
  22147. EXPECT_TRUE(header_received.load());
  22148. }
  22149. // Test: Reconnect interval configuration
  22150. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22151. Client client("localhost", get_port());
  22152. sse::SSEClient sse(client, "/events");
  22153. auto &result = sse.set_reconnect_interval(500);
  22154. // Builder pattern should return reference to self
  22155. EXPECT_EQ(&result, &sse);
  22156. }
  22157. // Test: Max reconnect attempts
  22158. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22159. // Connect to non-existent port to force reconnects
  22160. Client client("localhost", 59998);
  22161. sse::SSEClient sse(client, "/events");
  22162. std::atomic<int> error_count{0};
  22163. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22164. sse.set_reconnect_interval(50);
  22165. sse.set_max_reconnect_attempts(2);
  22166. auto start = std::chrono::steady_clock::now();
  22167. sse.start(); // Blocking call
  22168. auto end = std::chrono::steady_clock::now();
  22169. // Should have stopped after 2 failed attempts
  22170. EXPECT_GE(error_count.load(), 2);
  22171. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22172. auto duration =
  22173. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22174. #ifdef _WIN32
  22175. // Windows is much slower for socket connection failures
  22176. EXPECT_LT(duration.count(), 7000);
  22177. #else
  22178. EXPECT_LT(duration.count(), 1000);
  22179. #endif
  22180. }
  22181. // Test: Multi-line data in integration
  22182. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22183. // Endpoint with multi-line data
  22184. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22185. res.set_chunked_content_provider(
  22186. "text/event-stream", [](size_t offset, DataSink &sink) {
  22187. if (offset == 0) {
  22188. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22189. sink.write(event.data(), event.size());
  22190. }
  22191. return false;
  22192. });
  22193. });
  22194. Client client("localhost", get_port());
  22195. sse::SSEClient sse(client, "/multiline-data");
  22196. std::string received_data;
  22197. std::mutex data_mutex;
  22198. sse.on_message([&](const sse::SSEMessage &msg) {
  22199. std::lock_guard<std::mutex> lock(data_mutex);
  22200. received_data = msg.data;
  22201. });
  22202. sse.set_reconnect_interval(100);
  22203. sse.set_max_reconnect_attempts(1);
  22204. sse.start_async();
  22205. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22206. sse.stop();
  22207. std::lock_guard<std::mutex> lock(data_mutex);
  22208. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22209. }
  22210. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22211. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22212. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22213. DataSink &sink) {
  22214. if (offset == 0) {
  22215. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22216. sink.write(events.data(), events.size());
  22217. }
  22218. return false;
  22219. });
  22220. });
  22221. Client client("localhost", get_port());
  22222. sse::SSEClient sse(client, "/empty-data-lines");
  22223. std::mutex mutex;
  22224. std::condition_variable cv;
  22225. std::vector<std::string> received;
  22226. sse.on_message([&](const sse::SSEMessage &msg) {
  22227. std::lock_guard<std::mutex> lock(mutex);
  22228. received.push_back(msg.data);
  22229. cv.notify_all();
  22230. });
  22231. sse.set_max_reconnect_attempts(1);
  22232. sse.start_async();
  22233. {
  22234. std::unique_lock<std::mutex> lock(mutex);
  22235. cv.wait_for(lock, std::chrono::seconds(2),
  22236. [&] { return received.size() >= 3; });
  22237. }
  22238. sse.stop();
  22239. ASSERT_GE(received.size(), 3u);
  22240. EXPECT_EQ(received[0], "");
  22241. EXPECT_EQ(received[1], "\nhello");
  22242. EXPECT_EQ(received[2], "");
  22243. }
  22244. // Test: Auto-reconnect after server disconnection
  22245. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22246. std::atomic<int> connection_count{0};
  22247. std::atomic<int> message_count{0};
  22248. // Endpoint that sends one event and closes, forcing reconnect
  22249. server_->Get("/reconnect-test",
  22250. [&connection_count](const Request &, Response &res) {
  22251. connection_count.fetch_add(1);
  22252. res.set_chunked_content_provider(
  22253. "text/event-stream", [](size_t offset, DataSink &sink) {
  22254. if (offset == 0) {
  22255. std::string event = "data: hello\n\n";
  22256. sink.write(event.data(), event.size());
  22257. }
  22258. return false; // Close connection after sending
  22259. });
  22260. });
  22261. Client client("localhost", get_port());
  22262. sse::SSEClient sse(client, "/reconnect-test");
  22263. sse.on_message([&message_count](const sse::SSEMessage &) {
  22264. message_count.fetch_add(1);
  22265. });
  22266. sse.set_reconnect_interval(100);
  22267. sse.set_max_reconnect_attempts(3);
  22268. sse.start_async();
  22269. // Wait long enough for multiple reconnects
  22270. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22271. sse.stop();
  22272. // Should have connected multiple times (initial + reconnects)
  22273. EXPECT_GE(connection_count.load(), 2);
  22274. // Should have received messages from multiple connections
  22275. EXPECT_GE(message_count.load(), 2);
  22276. }
  22277. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22278. std::atomic<int> connection_count{0};
  22279. // Neither Content-Length nor chunked: the close ends the stream
  22280. server_->Get("/close-delimited",
  22281. [&connection_count](const Request &, Response &res) {
  22282. connection_count.fetch_add(1);
  22283. res.set_content_provider(
  22284. "text/event-stream", [](size_t offset, DataSink &sink) {
  22285. if (offset == 0) {
  22286. std::string event = "data: hello\n\n";
  22287. sink.write(event.data(), event.size());
  22288. } else {
  22289. sink.done();
  22290. }
  22291. return true;
  22292. });
  22293. });
  22294. Client client("localhost", get_port());
  22295. sse::SSEClient sse(client, "/close-delimited");
  22296. std::atomic<int> error_count{0};
  22297. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22298. sse.set_reconnect_interval(100);
  22299. sse.start_async();
  22300. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22301. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22302. }
  22303. sse.stop();
  22304. // Reconnects as after any end of the stream, but reports no error
  22305. EXPECT_GE(connection_count.load(), 2);
  22306. EXPECT_EQ(0, error_count.load());
  22307. }
  22308. // Test: A retry field that is not all ASCII digits is ignored
  22309. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22310. std::atomic<int> connection_count{0};
  22311. server_->Get("/bad-retry",
  22312. [&connection_count](const Request &, Response &res) {
  22313. connection_count.fetch_add(1);
  22314. res.set_chunked_content_provider(
  22315. "text/event-stream", [](size_t offset, DataSink &sink) {
  22316. if (offset == 0) {
  22317. std::string event = "retry: -1\ndata: hello\n\n";
  22318. sink.write(event.data(), event.size());
  22319. }
  22320. return false;
  22321. });
  22322. });
  22323. Client client("localhost", get_port());
  22324. sse::SSEClient sse(client, "/bad-retry");
  22325. sse.set_reconnect_interval(10000);
  22326. sse.start_async();
  22327. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22328. sse.stop();
  22329. EXPECT_EQ(connection_count.load(), 1);
  22330. }
  22331. // Test: A retry field of all ASCII digits sets the reconnection time
  22332. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22333. std::mutex mutex;
  22334. std::condition_variable cv;
  22335. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22336. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22337. {
  22338. std::lock_guard<std::mutex> lock(mutex);
  22339. connected_at.push_back(std::chrono::steady_clock::now());
  22340. cv.notify_all();
  22341. }
  22342. res.set_chunked_content_provider(
  22343. "text/event-stream", [](size_t offset, DataSink &sink) {
  22344. if (offset == 0) {
  22345. std::string event = "retry: 0\ndata: hello\n\n";
  22346. sink.write(event.data(), event.size());
  22347. }
  22348. return false;
  22349. });
  22350. });
  22351. Client client("localhost", get_port());
  22352. sse::SSEClient sse(client, "/zero-retry");
  22353. sse.set_reconnect_interval(10000);
  22354. sse.start_async();
  22355. {
  22356. std::unique_lock<std::mutex> lock(mutex);
  22357. cv.wait_for(lock, std::chrono::seconds(5),
  22358. [&] { return connected_at.size() >= 2; });
  22359. }
  22360. sse.stop();
  22361. // The server-supplied interval is applied, but never below 100ms, so
  22362. // "retry: 0" does not cause a busy reconnect loop
  22363. std::lock_guard<std::mutex> lock(mutex);
  22364. ASSERT_GE(connected_at.size(), 2u);
  22365. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22366. connected_at[1] - connected_at[0])
  22367. .count();
  22368. EXPECT_GE(interval_ms, 100);
  22369. }
  22370. // Test: Last-Event-ID sent on reconnect
  22371. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22372. std::atomic<int> connection_count{0};
  22373. std::vector<std::string> received_last_event_ids;
  22374. std::mutex id_mutex;
  22375. // Endpoint that checks Last-Event-ID header and sends event with ID
  22376. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22377. int conn = connection_count.fetch_add(1);
  22378. // Capture the Last-Event-ID header from each connection
  22379. {
  22380. std::lock_guard<std::mutex> lock(id_mutex);
  22381. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22382. }
  22383. res.set_chunked_content_provider(
  22384. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22385. if (offset == 0) {
  22386. std::string event =
  22387. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22388. sink.write(event.data(), event.size());
  22389. }
  22390. return false;
  22391. });
  22392. });
  22393. Client client("localhost", get_port());
  22394. sse::SSEClient sse(client, "/reconnect-with-id");
  22395. sse.set_reconnect_interval(100);
  22396. sse.set_max_reconnect_attempts(3);
  22397. sse.start_async();
  22398. // Wait for at least 2 connections
  22399. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22400. sse.stop();
  22401. // Verify behavior
  22402. std::lock_guard<std::mutex> lock(id_mutex);
  22403. EXPECT_GE(received_last_event_ids.size(), 2u);
  22404. // First connection should have no Last-Event-ID
  22405. if (!received_last_event_ids.empty()) {
  22406. EXPECT_EQ(received_last_event_ids[0], "");
  22407. }
  22408. // Second connection should have Last-Event-ID from first connection
  22409. if (received_last_event_ids.size() >= 2) {
  22410. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22411. }
  22412. }
  22413. // Test: set_headers updates headers used on reconnect
  22414. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22415. std::vector<std::string> received_tokens;
  22416. std::mutex token_mutex;
  22417. // Endpoint that captures Authorization header
  22418. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22419. {
  22420. std::lock_guard<std::mutex> lock(token_mutex);
  22421. received_tokens.push_back(req.get_header_value("Authorization"));
  22422. }
  22423. res.set_chunked_content_provider(
  22424. "text/event-stream", [](size_t offset, DataSink &sink) {
  22425. if (offset == 0) {
  22426. std::string event = "data: hello\n\n";
  22427. sink.write(event.data(), event.size());
  22428. }
  22429. return false; // Close connection to trigger reconnect
  22430. });
  22431. });
  22432. Client client("localhost", get_port());
  22433. Headers headers = {{"Authorization", "Bearer old-token"}};
  22434. sse::SSEClient sse(client, "/auth-check", headers);
  22435. // Update headers on each successful connection
  22436. sse.on_open(
  22437. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22438. sse.set_reconnect_interval(100);
  22439. sse.set_max_reconnect_attempts(3);
  22440. sse.start_async();
  22441. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22442. sse.stop();
  22443. std::lock_guard<std::mutex> lock(token_mutex);
  22444. ASSERT_GE(received_tokens.size(), 2u);
  22445. // First connection uses original header
  22446. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22447. // Second connection uses updated header from set_headers
  22448. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22449. }
  22450. // Test: 401 allows reconnection (so on_error can refresh headers)
  22451. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22452. std::atomic<int> connection_count{0};
  22453. // Endpoint: returns 401 on first attempt, 200 on second
  22454. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22455. int conn = connection_count.fetch_add(1);
  22456. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22457. res.status = StatusCode::Unauthorized_401;
  22458. res.set_content("Unauthorized", "text/plain");
  22459. return;
  22460. }
  22461. res.set_chunked_content_provider(
  22462. "text/event-stream", [](size_t offset, DataSink &sink) {
  22463. if (offset == 0) {
  22464. std::string event = "data: authenticated\n\n";
  22465. sink.write(event.data(), event.size());
  22466. }
  22467. return false;
  22468. });
  22469. });
  22470. Client client("localhost", get_port());
  22471. Headers headers = {{"Authorization", "Bearer expired"}};
  22472. sse::SSEClient sse(client, "/auth-retry", headers);
  22473. std::atomic<bool> message_received{false};
  22474. // Refresh token on error
  22475. sse.on_error(
  22476. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22477. sse.on_message([&](const sse::SSEMessage &msg) {
  22478. if (msg.data == "authenticated") { message_received.store(true); }
  22479. });
  22480. sse.set_reconnect_interval(100);
  22481. sse.set_max_reconnect_attempts(3);
  22482. sse.start_async();
  22483. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22484. sse.stop();
  22485. // Should have reconnected after 401 and succeeded with new token
  22486. EXPECT_GE(connection_count.load(), 2);
  22487. EXPECT_TRUE(message_received.load());
  22488. }
  22489. TEST(Issue2318Test, EmptyHostString) {
  22490. {
  22491. httplib::Client cli_empty("", PORT);
  22492. auto res = cli_empty.Get("/");
  22493. ASSERT_FALSE(res);
  22494. EXPECT_EQ(httplib::Error::Connection, res.error());
  22495. }
  22496. {
  22497. httplib::Client cli(" ", PORT);
  22498. auto res = cli.Get("/");
  22499. ASSERT_FALSE(res);
  22500. EXPECT_EQ(httplib::Error::Connection, res.error());
  22501. }
  22502. }
  22503. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22504. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22505. Server svr;
  22506. // Set a small payload limit (1KB)
  22507. svr.set_payload_max_length(1024);
  22508. svr.Post("/test", [&](const Request &req, Response &res) {
  22509. res.set_content("Body size: " + std::to_string(req.body.size()),
  22510. "text/plain");
  22511. });
  22512. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22513. auto se = detail::scope_exit([&] {
  22514. svr.stop();
  22515. listen_thread.join();
  22516. });
  22517. svr.wait_until_ready();
  22518. // Create data that compresses well but exceeds limit when decompressed
  22519. // 8KB of repeated null bytes compresses to a very small size
  22520. std::string original_data(8 * 1024, '\0');
  22521. // Compress the data using gzip
  22522. std::string compressed_data;
  22523. detail::gzip_compressor compressor;
  22524. compressor.compress(original_data.data(), original_data.size(), true,
  22525. [&](const char *data, size_t size) {
  22526. compressed_data.append(data, size);
  22527. return true;
  22528. });
  22529. // Verify compression worked (compressed should be much smaller)
  22530. ASSERT_LT(compressed_data.size(), original_data.size());
  22531. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22532. // Send compressed data with Content-Encoding: gzip
  22533. Client cli(HOST, PORT);
  22534. Headers headers = {{"Content-Encoding", "gzip"}};
  22535. auto res =
  22536. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22537. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22539. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22540. }
  22541. #endif
  22542. // ============================================================================
  22543. // OpenSSL-Specific Tests
  22544. // ============================================================================
  22545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22546. X509 *readCertificate(const std::string &strFileName) {
  22547. std::ifstream inStream(strFileName);
  22548. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22549. std::istreambuf_iterator<char>());
  22550. if (strCertPEM.empty()) return (nullptr);
  22551. BIO *pbCert = BIO_new(BIO_s_mem());
  22552. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22553. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22554. BIO_free(pbCert);
  22555. return (pCert);
  22556. }
  22557. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22558. std::ifstream inStream(strFileName);
  22559. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22560. std::istreambuf_iterator<char>());
  22561. if (strPrivateKeyPEM.empty()) return (nullptr);
  22562. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22563. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22564. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22565. BIO_free(pbPrivKey);
  22566. return (pPrivateKey);
  22567. }
  22568. TEST(BindServerTest, UpdateCerts) {
  22569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22570. int port = svr.bind_to_any_port("0.0.0.0");
  22571. ASSERT_TRUE(svr.is_valid());
  22572. ASSERT_TRUE(port > 0);
  22573. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22574. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22575. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22576. ASSERT_TRUE(cert != nullptr);
  22577. ASSERT_TRUE(ca_cert != nullptr);
  22578. ASSERT_TRUE(key != nullptr);
  22579. X509_STORE *cert_store = X509_STORE_new();
  22580. X509_STORE_add_cert(cert_store, ca_cert);
  22581. // svr.update_certs(cert, key, cert_store); // deprecated
  22582. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22583. CLIENT_CA_CERT_FILE);
  22584. ASSERT_TRUE(svr.is_valid());
  22585. svr.stop();
  22586. X509_STORE_free(cert_store);
  22587. X509_free(cert);
  22588. X509_free(ca_cert);
  22589. EVP_PKEY_free(key);
  22590. }
  22591. // Test that update_certs() updates client CA list correctly
  22592. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22593. // Start with file-based constructor
  22594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22595. ASSERT_TRUE(svr.is_valid());
  22596. // Initially no client CA list should be set
  22597. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22598. ASSERT_TRUE(ssl_ctx != nullptr);
  22599. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22600. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22601. // Now update with client CA (PEM string)
  22602. std::string cert_pem, key_pem, ca_pem;
  22603. read_file(SERVER_CERT_FILE, cert_pem);
  22604. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22605. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22606. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22607. ASSERT_TRUE(svr.is_valid());
  22608. // Now client CA list should be set
  22609. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22610. ASSERT_TRUE(ca_list_after != nullptr);
  22611. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22612. }
  22613. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22614. // Test that the file-path SSLServer constructor properly sets the client CA
  22615. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22617. ASSERT_TRUE(svr.is_valid());
  22618. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22619. ASSERT_TRUE(ssl_ctx != nullptr);
  22620. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22621. ASSERT_TRUE(ca_list != nullptr);
  22622. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22623. }
  22624. #endif
  22625. // ============================================================================
  22626. // MbedTLS-Specific Tests
  22627. // ============================================================================
  22628. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22629. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22630. using namespace httplib::tls;
  22631. // Track if callback was invoked
  22632. bool callback_invoked = false;
  22633. // The callback receives void* ctx which is actually MbedTlsContext*
  22634. // We can access the mbedtls_ssl_config via the context
  22635. auto setup_callback = [&callback_invoked](void *ctx) {
  22636. callback_invoked = true;
  22637. // Cast to MbedTlsContext* to access the ssl config
  22638. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22639. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22640. // Use static variables to hold certificate data (simplified for test)
  22641. static mbedtls_x509_crt own_cert;
  22642. static mbedtls_pk_context own_key;
  22643. static mbedtls_x509_crt ca_chain;
  22644. static bool initialized = false;
  22645. if (!initialized) {
  22646. mbedtls_x509_crt_init(&own_cert);
  22647. mbedtls_pk_init(&own_key);
  22648. mbedtls_x509_crt_init(&ca_chain);
  22649. // Load server certificate
  22650. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22651. return false;
  22652. }
  22653. // Load server private key.
  22654. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22655. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22656. #if MBEDTLS_VERSION_MAJOR == 3
  22657. ,
  22658. mbedtls_ctr_drbg_random, nullptr
  22659. #endif
  22660. ) != 0) {
  22661. return false;
  22662. }
  22663. // Load CA chain for client verification
  22664. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22665. return false;
  22666. }
  22667. initialized = true;
  22668. }
  22669. // Configure the SSL config
  22670. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22671. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22672. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22673. // Set minimum TLS version using mbedTLS native API
  22674. #if MBEDTLS_VERSION_MAJOR >= 3
  22675. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22676. #else
  22677. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22678. MBEDTLS_SSL_MINOR_VERSION_3);
  22679. #endif
  22680. return true;
  22681. };
  22682. SSLServer svr(setup_callback);
  22683. ASSERT_TRUE(svr.is_valid());
  22684. ASSERT_TRUE(callback_invoked);
  22685. svr.Get("/test", [&](const Request &req, Response &res) {
  22686. res.set_content("test", "text/plain");
  22687. auto cert = req.peer_cert();
  22688. ASSERT_TRUE(static_cast<bool>(cert));
  22689. auto common_name = cert.subject_cn();
  22690. EXPECT_EQ("Common Name", common_name);
  22691. });
  22692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22693. auto se = detail::scope_exit([&] {
  22694. svr.stop();
  22695. t.join();
  22696. ASSERT_FALSE(svr.is_running());
  22697. });
  22698. svr.wait_until_ready();
  22699. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22700. cli.enable_server_certificate_verification(false);
  22701. cli.set_connection_timeout(30);
  22702. auto res = cli.Get("/test");
  22703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22704. ASSERT_EQ(StatusCode::OK_200, res->status);
  22705. }
  22706. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22707. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22708. // keep-alive SSL session, which reads through that config in
  22709. // mbedtls_ssl_close_notify.
  22710. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22712. ASSERT_TRUE(svr.is_valid());
  22713. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22714. res.set_content("test", "text/plain");
  22715. });
  22716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22717. auto se = detail::scope_exit([&] {
  22718. svr.stop();
  22719. t.join();
  22720. ASSERT_FALSE(svr.is_running());
  22721. });
  22722. svr.wait_until_ready();
  22723. {
  22724. SSLClient cli(HOST, PORT);
  22725. cli.enable_server_certificate_verification(false);
  22726. cli.set_keep_alive(true);
  22727. auto res = cli.Get("/test");
  22728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22729. ASSERT_EQ(StatusCode::OK_200, res->status);
  22730. // cli is destructed here with the keep-alive SSL session still open.
  22731. }
  22732. }
  22733. #endif
  22734. // WebSocket Tests
  22735. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22736. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22737. // defining the meaning of these bits has been negotiated.
  22738. auto make_frame = [](uint8_t first_byte) {
  22739. std::string frame;
  22740. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22741. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22742. frame += "Hello";
  22743. return frame;
  22744. };
  22745. // RSV1 set (0x40)
  22746. {
  22747. detail::BufferStream strm;
  22748. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22749. ws::Opcode opcode;
  22750. std::string payload;
  22751. bool fin;
  22752. EXPECT_EQ(
  22753. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22754. ws::impl::FrameRead::Fail);
  22755. }
  22756. // RSV2 set (0x20)
  22757. {
  22758. detail::BufferStream strm;
  22759. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22760. ws::Opcode opcode;
  22761. std::string payload;
  22762. bool fin;
  22763. EXPECT_EQ(
  22764. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22765. ws::impl::FrameRead::Fail);
  22766. }
  22767. // RSV3 set (0x10)
  22768. {
  22769. detail::BufferStream strm;
  22770. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22771. ws::Opcode opcode;
  22772. std::string payload;
  22773. bool fin;
  22774. EXPECT_EQ(
  22775. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22776. ws::impl::FrameRead::Fail);
  22777. }
  22778. // No RSV bits set - should succeed
  22779. {
  22780. detail::BufferStream strm;
  22781. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22782. ws::Opcode opcode;
  22783. std::string payload;
  22784. bool fin;
  22785. EXPECT_EQ(
  22786. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22787. ws::impl::FrameRead::Ok);
  22788. EXPECT_EQ(ws::Opcode::Text, opcode);
  22789. EXPECT_EQ("Hello", payload);
  22790. EXPECT_TRUE(fin);
  22791. }
  22792. }
  22793. TEST(WebSocketTest, ControlFrameValidation) {
  22794. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22795. // payload length <= 125.
  22796. // Ping with FIN=0 - must be rejected
  22797. {
  22798. detail::BufferStream strm;
  22799. std::string frame;
  22800. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22801. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22802. strm.write(frame.data(), frame.size());
  22803. ws::Opcode opcode;
  22804. std::string payload;
  22805. bool fin;
  22806. EXPECT_EQ(
  22807. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22808. ws::impl::FrameRead::Fail);
  22809. }
  22810. // Close with FIN=0 - must be rejected
  22811. {
  22812. detail::BufferStream strm;
  22813. std::string frame;
  22814. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22815. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22816. strm.write(frame.data(), frame.size());
  22817. ws::Opcode opcode;
  22818. std::string payload;
  22819. bool fin;
  22820. EXPECT_EQ(
  22821. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22822. ws::impl::FrameRead::Fail);
  22823. }
  22824. // Ping with payload_len=126 (extended length) - must be rejected
  22825. {
  22826. detail::BufferStream strm;
  22827. std::string frame;
  22828. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22829. frame += static_cast<char>(126); // payload_len=126 (>125)
  22830. frame += static_cast<char>(0x00); // extended length high byte
  22831. frame += static_cast<char>(126); // extended length low byte
  22832. frame += std::string(126, 'x');
  22833. strm.write(frame.data(), frame.size());
  22834. ws::Opcode opcode;
  22835. std::string payload;
  22836. bool fin;
  22837. EXPECT_EQ(
  22838. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22839. ws::impl::FrameRead::Fail);
  22840. }
  22841. // Ping with FIN=1 and payload_len=125 - should succeed
  22842. {
  22843. detail::BufferStream strm;
  22844. std::string frame;
  22845. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22846. frame += static_cast<char>(125); // payload_len=125
  22847. frame += std::string(125, 'x');
  22848. strm.write(frame.data(), frame.size());
  22849. ws::Opcode opcode;
  22850. std::string payload;
  22851. bool fin;
  22852. EXPECT_EQ(
  22853. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22854. ws::impl::FrameRead::Ok);
  22855. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22856. EXPECT_EQ(125u, payload.size());
  22857. EXPECT_TRUE(fin);
  22858. }
  22859. }
  22860. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22861. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22862. // length MUST be 0.
  22863. // MSB set - must be rejected
  22864. {
  22865. detail::BufferStream strm;
  22866. std::string frame;
  22867. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22868. frame += static_cast<char>(127); // 64-bit extended length
  22869. frame += static_cast<char>(0x80); // MSB set (invalid)
  22870. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22871. strm.write(frame.data(), frame.size());
  22872. ws::Opcode opcode;
  22873. std::string payload;
  22874. bool fin;
  22875. EXPECT_EQ(
  22876. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22877. ws::impl::FrameRead::Fail);
  22878. }
  22879. // MSB clear - should pass length parsing (will be rejected by max_len,
  22880. // but that's a different check; use a small length to verify)
  22881. {
  22882. detail::BufferStream strm;
  22883. std::string frame;
  22884. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22885. frame += static_cast<char>(127); // 64-bit extended length
  22886. frame += std::string(7, '\0'); // high bytes = 0
  22887. frame += static_cast<char>(0x03); // length = 3
  22888. frame += "abc";
  22889. strm.write(frame.data(), frame.size());
  22890. ws::Opcode opcode;
  22891. std::string payload;
  22892. bool fin;
  22893. EXPECT_EQ(
  22894. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22895. ws::impl::FrameRead::Ok);
  22896. EXPECT_EQ(ws::Opcode::Text, opcode);
  22897. EXPECT_EQ("abc", payload);
  22898. }
  22899. }
  22900. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22901. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22902. // Valid UTF-8
  22903. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22904. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22905. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22906. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22907. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22908. // Invalid UTF-8
  22909. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22910. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22911. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22912. EXPECT_FALSE(
  22913. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22914. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22915. }
  22916. TEST(WebSocketTest, ConnectAndDisconnect) {
  22917. Server svr;
  22918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22919. std::string msg;
  22920. while (ws.read(msg)) {}
  22921. });
  22922. auto port = svr.bind_to_any_port(HOST);
  22923. std::thread t([&]() { svr.listen_after_bind(); });
  22924. svr.wait_until_ready();
  22925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22926. auto res = client.connect();
  22927. ASSERT_TRUE(res);
  22928. EXPECT_EQ(Error::Success, res.error());
  22929. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22930. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22931. EXPECT_TRUE(client.is_open());
  22932. client.close();
  22933. EXPECT_FALSE(client.is_open());
  22934. svr.stop();
  22935. t.join();
  22936. }
  22937. TEST(WebSocketTest, ValidURL) {
  22938. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22939. EXPECT_TRUE(ws1.is_valid());
  22940. ws::WebSocketClient ws2("ws://example.com/path");
  22941. EXPECT_TRUE(ws2.is_valid());
  22942. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22943. EXPECT_TRUE(ws3.is_valid());
  22944. #ifdef CPPHTTPLIB_SSL_ENABLED
  22945. ws::WebSocketClient wss1("wss://example.com/path");
  22946. EXPECT_TRUE(wss1.is_valid());
  22947. ws::WebSocketClient wss2("wss://example.com:443/path");
  22948. EXPECT_TRUE(wss2.is_valid());
  22949. #endif
  22950. }
  22951. TEST(WebSocketTest, InvalidURL) {
  22952. // No scheme
  22953. ws::WebSocketClient ws1("localhost:8080/path");
  22954. EXPECT_FALSE(ws1.is_valid());
  22955. // No path
  22956. ws::WebSocketClient ws2("ws://localhost:8080");
  22957. EXPECT_FALSE(ws2.is_valid());
  22958. // Empty string
  22959. ws::WebSocketClient ws3("");
  22960. EXPECT_FALSE(ws3.is_valid());
  22961. // Missing host
  22962. ws::WebSocketClient ws4("ws://:8080/path");
  22963. EXPECT_FALSE(ws4.is_valid());
  22964. // Port number overflow — should not crash
  22965. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22966. EXPECT_FALSE(ws5.is_valid());
  22967. // Port out of range
  22968. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22969. EXPECT_FALSE(ws6.is_valid());
  22970. }
  22971. TEST(WebSocketTest, UnsupportedScheme) {
  22972. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22973. ws::WebSocketClient ws1("http://localhost:8080/path");
  22974. EXPECT_FALSE(ws1.is_valid());
  22975. ws::WebSocketClient ws2("https://localhost:8080/path");
  22976. EXPECT_FALSE(ws2.is_valid());
  22977. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22978. EXPECT_FALSE(ws3.is_valid());
  22979. #else
  22980. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22981. std::invalid_argument);
  22982. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22983. std::invalid_argument);
  22984. #endif
  22985. }
  22986. TEST(WebSocketTest, ConnectWhenInvalid) {
  22987. ws::WebSocketClient ws("not a valid url");
  22988. EXPECT_FALSE(ws.is_valid());
  22989. auto res = ws.connect();
  22990. EXPECT_FALSE(res);
  22991. EXPECT_EQ(Error::Connection, res.error());
  22992. EXPECT_EQ(-1, res.status());
  22993. }
  22994. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22995. // Grab a port that is free, then close it again so nothing listens there
  22996. Server svr;
  22997. auto port = svr.bind_to_any_port(HOST);
  22998. svr.stop();
  22999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23000. auto res = client.connect();
  23001. ASSERT_FALSE(res);
  23002. EXPECT_EQ(Error::Connection, res.error());
  23003. EXPECT_EQ(-1, res.status());
  23004. }
  23005. TEST(WebSocketTest, DefaultPort) {
  23006. ws::WebSocketClient ws1("ws://example.com/path");
  23007. EXPECT_TRUE(ws1.is_valid());
  23008. // ws:// defaults to port 80 (verified by successful parse)
  23009. #ifdef CPPHTTPLIB_SSL_ENABLED
  23010. ws::WebSocketClient ws2("wss://example.com/path");
  23011. EXPECT_TRUE(ws2.is_valid());
  23012. // wss:// defaults to port 443 (verified by successful parse)
  23013. #endif
  23014. }
  23015. TEST(WebSocketTest, IPv6LiteralAddress) {
  23016. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23017. EXPECT_TRUE(ws1.is_valid());
  23018. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23019. EXPECT_TRUE(ws2.is_valid());
  23020. }
  23021. TEST(WebSocketTest, ComplexPath) {
  23022. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23023. EXPECT_TRUE(ws1.is_valid());
  23024. ws::WebSocketClient ws2("ws://localhost:8080/");
  23025. EXPECT_TRUE(ws2.is_valid());
  23026. }
  23027. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23028. Server svr;
  23029. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23030. std::string msg;
  23031. while (ws.read(msg)) {}
  23032. });
  23033. auto port = svr.bind_to_any_port(HOST);
  23034. std::thread t([&]() { svr.listen_after_bind(); });
  23035. svr.wait_until_ready();
  23036. auto another_host = "example.com";
  23037. auto wrong_ip = "192.0.2.1";
  23038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23039. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23040. ASSERT_TRUE(client.connect());
  23041. EXPECT_TRUE(client.is_open());
  23042. client.close();
  23043. svr.stop();
  23044. t.join();
  23045. }
  23046. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23047. Server svr;
  23048. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23049. std::string msg;
  23050. while (ws.read(msg)) {}
  23051. });
  23052. auto port = svr.bind_to_any_port(HOST);
  23053. std::thread t([&]() { svr.listen_after_bind(); });
  23054. svr.wait_until_ready();
  23055. auto wrong_ip = "192.0.2.1";
  23056. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23057. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23058. client.set_connection_timeout(1);
  23059. client.set_read_timeout(1);
  23060. client.set_write_timeout(1);
  23061. EXPECT_FALSE(client.connect());
  23062. EXPECT_FALSE(client.is_open());
  23063. svr.stop();
  23064. t.join();
  23065. }
  23066. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23067. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23068. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23069. // (RFC 6761) is only a map key and the Host header value.
  23070. auto host = "target.invalid";
  23071. Server svr;
  23072. std::string received_host;
  23073. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23074. received_host = req.get_header_value("Host");
  23075. std::string msg;
  23076. while (ws.read(msg)) {}
  23077. });
  23078. auto port = svr.bind_to_any_port(HOST);
  23079. std::thread t([&]() { svr.listen_after_bind(); });
  23080. // ASSERT_* below returns from the test body, which would leave t joinable
  23081. // and make ~thread call std::terminate.
  23082. auto se = detail::scope_exit([&] {
  23083. svr.stop();
  23084. if (t.joinable()) { t.join(); }
  23085. });
  23086. svr.wait_until_ready();
  23087. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23088. std::to_string(port) + "/ws");
  23089. client.set_hostname_addr_map({{host, HOST}});
  23090. ASSERT_TRUE(client.connect());
  23091. EXPECT_TRUE(client.is_open());
  23092. client.close();
  23093. svr.stop();
  23094. t.join();
  23095. // The mapping only redirects the connection; the identity stays host_.
  23096. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23097. }
  23098. class WebSocketIntegrationTest : public ::testing::Test {
  23099. protected:
  23100. void SetUp() override {
  23101. server_ = httplib::detail::make_unique<Server>();
  23102. setup_server();
  23103. start_server();
  23104. }
  23105. void TearDown() override {
  23106. server_->stop();
  23107. if (server_thread_.joinable()) { server_thread_.join(); }
  23108. }
  23109. void setup_server() {
  23110. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23111. std::string msg;
  23112. ws::ReadResult ret;
  23113. while ((ret = ws.read(msg))) {
  23114. if (ret == ws::Binary) {
  23115. ws.send(msg.data(), msg.size());
  23116. } else {
  23117. ws.send(msg);
  23118. }
  23119. }
  23120. });
  23121. server_->WebSocket("/ws-echo-string",
  23122. [](const Request &, ws::WebSocket &ws) {
  23123. std::string msg;
  23124. while (ws.read(msg)) {
  23125. ws.send("echo: " + msg);
  23126. }
  23127. });
  23128. server_->WebSocket(
  23129. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23130. // Echo back request metadata
  23131. ws.send("path:" + req.path);
  23132. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23133. std::string msg;
  23134. while (ws.read(msg)) {}
  23135. });
  23136. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23137. std::string msg;
  23138. ws.read(msg); // wait for a message
  23139. ws.close();
  23140. });
  23141. server_->WebSocket("/ws-close-status",
  23142. [](const Request &, ws::WebSocket &ws) {
  23143. std::string msg;
  23144. ws.read(msg); // wait for a message
  23145. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23146. });
  23147. server_->WebSocket(
  23148. "/ws-subprotocol",
  23149. [](const Request &, ws::WebSocket &ws) {
  23150. std::string msg;
  23151. while (ws.read(msg)) {
  23152. ws.send(msg);
  23153. }
  23154. },
  23155. [](const std::vector<std::string> &protocols) -> std::string {
  23156. for (const auto &p : protocols) {
  23157. if (p == "graphql-ws") { return p; }
  23158. }
  23159. return "";
  23160. });
  23161. server_->WebSocket(
  23162. "/ws-subprotocol-unoffered",
  23163. [](const Request &, ws::WebSocket &ws) {
  23164. std::string msg;
  23165. while (ws.read(msg)) {
  23166. ws.send(msg);
  23167. }
  23168. },
  23169. [](const std::vector<std::string> &) -> std::string {
  23170. return "admin";
  23171. });
  23172. }
  23173. void start_server() {
  23174. port_ = server_->bind_to_any_port(HOST);
  23175. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23176. server_->wait_until_ready();
  23177. }
  23178. std::unique_ptr<Server> server_;
  23179. std::thread server_thread_;
  23180. int port_ = 0;
  23181. };
  23182. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23183. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23184. "/ws-echo");
  23185. ASSERT_TRUE(client.connect());
  23186. ASSERT_TRUE(client.is_open());
  23187. ASSERT_TRUE(client.send("Hello WebSocket"));
  23188. std::string msg;
  23189. EXPECT_EQ(ws::Text, client.read(msg));
  23190. EXPECT_EQ("Hello WebSocket", msg);
  23191. client.close();
  23192. }
  23193. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23194. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23195. "/ws-echo");
  23196. ASSERT_TRUE(client.connect());
  23197. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23198. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23199. std::string msg;
  23200. EXPECT_EQ(ws::Binary, client.read(msg));
  23201. EXPECT_EQ(binary_data, msg);
  23202. client.close();
  23203. }
  23204. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23206. "/ws-echo");
  23207. ASSERT_TRUE(client.connect());
  23208. for (int i = 0; i < 10; i++) {
  23209. auto text = "message " + std::to_string(i);
  23210. ASSERT_TRUE(client.send(text));
  23211. std::string msg;
  23212. ASSERT_TRUE(client.read(msg));
  23213. EXPECT_EQ(text, msg);
  23214. }
  23215. client.close();
  23216. }
  23217. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23219. "/ws-close");
  23220. ASSERT_TRUE(client.connect());
  23221. // Send a message to trigger the server to close
  23222. ASSERT_TRUE(client.send("trigger close"));
  23223. // The server will close, so read should return false
  23224. std::string msg;
  23225. EXPECT_FALSE(client.read(msg));
  23226. EXPECT_FALSE(client.is_open());
  23227. }
  23228. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23230. "/ws-echo");
  23231. ASSERT_TRUE(client.connect());
  23232. // 128KB message
  23233. std::string large_data(128 * 1024, 'X');
  23234. ASSERT_TRUE(client.send(large_data));
  23235. std::string msg;
  23236. ASSERT_TRUE(client.read(msg));
  23237. EXPECT_EQ(large_data, msg);
  23238. client.close();
  23239. }
  23240. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23242. "/ws-echo");
  23243. ASSERT_TRUE(client.connect());
  23244. const int num_threads = 4;
  23245. std::vector<std::thread> threads;
  23246. std::atomic<int> send_count{0};
  23247. for (int t = 0; t < num_threads; t++) {
  23248. threads.emplace_back([&client, &send_count, t]() {
  23249. for (int i = 0; i < 5; i++) {
  23250. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23251. if (client.send(text)) { send_count++; }
  23252. }
  23253. });
  23254. }
  23255. for (auto &th : threads) {
  23256. th.join();
  23257. }
  23258. int received = 0;
  23259. std::string msg;
  23260. while (received < send_count.load()) {
  23261. if (!client.read(msg)) { break; }
  23262. received++;
  23263. }
  23264. EXPECT_EQ(send_count.load(), received);
  23265. client.close();
  23266. }
  23267. TEST_F(WebSocketIntegrationTest, ReadString) {
  23268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23269. "/ws-echo-string");
  23270. ASSERT_TRUE(client.connect());
  23271. ASSERT_TRUE(client.send("hello"));
  23272. std::string msg;
  23273. ASSERT_TRUE(client.read(msg));
  23274. EXPECT_EQ("echo: hello", msg);
  23275. ASSERT_TRUE(client.send("world"));
  23276. ASSERT_TRUE(client.read(msg));
  23277. EXPECT_EQ("echo: world", msg);
  23278. client.close();
  23279. }
  23280. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23281. Headers headers = {{"X-Test-Header", "test-value"}};
  23282. ws::WebSocketClient client(
  23283. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23284. ASSERT_TRUE(client.connect());
  23285. std::string msg;
  23286. ASSERT_TRUE(client.read(msg));
  23287. EXPECT_EQ("path:/ws-request-info", msg);
  23288. ASSERT_TRUE(client.read(msg));
  23289. EXPECT_EQ("header:test-value", msg);
  23290. client.close();
  23291. }
  23292. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23294. "/ws-echo");
  23295. client.set_read_timeout(1, 0); // 1 second
  23296. ASSERT_TRUE(client.connect());
  23297. // Don't send anything — server echo handler waits for a message, so read()
  23298. // should time out. The connection survives it: nothing was consumed.
  23299. std::string msg;
  23300. EXPECT_EQ(client.read(msg), ws::Timeout);
  23301. EXPECT_TRUE(client.is_open());
  23302. // And it is still usable afterwards.
  23303. EXPECT_TRUE(client.send("after timeout"));
  23304. EXPECT_EQ(client.read(msg), ws::Text);
  23305. EXPECT_EQ(msg, "after timeout");
  23306. }
  23307. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23309. "/ws-echo");
  23310. client.set_read_timeout(1, 0);
  23311. ASSERT_TRUE(client.connect());
  23312. ASSERT_TRUE(client.send("first"));
  23313. std::string msg;
  23314. ASSERT_EQ(client.read(msg), ws::Text);
  23315. ASSERT_EQ(msg, "first");
  23316. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23317. // not be used with a read timeout: it would reprocess the previous message.
  23318. EXPECT_EQ(client.read(msg), ws::Timeout);
  23319. EXPECT_EQ(msg, "first");
  23320. }
  23321. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23322. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23323. "/ws-echo");
  23324. ASSERT_TRUE(client.connect());
  23325. // Setting it once the connection is open reaches the live stream, not just
  23326. // the seed for the next connect().
  23327. client.set_read_timeout(1, 0);
  23328. std::string msg;
  23329. EXPECT_EQ(client.read(msg), ws::Timeout);
  23330. EXPECT_TRUE(client.is_open());
  23331. }
  23332. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23334. "/ws-echo");
  23335. client.set_read_timeout(5, 0);
  23336. ASSERT_TRUE(client.connect());
  23337. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23338. // The server should reject it and close the connection.
  23339. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23340. client.send(oversized);
  23341. // The server's read() should have failed due to payload limit,
  23342. // so our read() should return false (connection closed).
  23343. std::string msg;
  23344. EXPECT_FALSE(client.read(msg));
  23345. }
  23346. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23347. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23348. "/ws-echo");
  23349. client.set_read_timeout(10, 0);
  23350. ASSERT_TRUE(client.connect());
  23351. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23352. // This should succeed.
  23353. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23354. ASSERT_TRUE(client.send(at_limit));
  23355. std::string msg;
  23356. ASSERT_TRUE(client.read(msg));
  23357. EXPECT_EQ(at_limit.size(), msg.size());
  23358. client.close();
  23359. }
  23360. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23362. "/nonexistent");
  23363. auto res = client.connect();
  23364. EXPECT_FALSE(res);
  23365. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23366. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23367. EXPECT_FALSE(client.is_open());
  23368. }
  23369. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23371. "/ws-echo");
  23372. ASSERT_TRUE(client.connect());
  23373. ASSERT_TRUE(client.send(""));
  23374. std::string msg;
  23375. EXPECT_EQ(ws::Text, client.read(msg));
  23376. EXPECT_EQ("", msg);
  23377. client.close();
  23378. }
  23379. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23381. "/ws-echo");
  23382. // First connection
  23383. ASSERT_TRUE(client.connect());
  23384. ASSERT_TRUE(client.send("first"));
  23385. std::string msg;
  23386. ASSERT_TRUE(client.read(msg));
  23387. EXPECT_EQ("first", msg);
  23388. client.close();
  23389. EXPECT_FALSE(client.is_open());
  23390. // Reconnect using the same client object
  23391. ASSERT_TRUE(client.connect());
  23392. ASSERT_TRUE(client.is_open());
  23393. ASSERT_TRUE(client.send("second"));
  23394. ASSERT_TRUE(client.read(msg));
  23395. EXPECT_EQ("second", msg);
  23396. client.close();
  23397. }
  23398. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23400. "/ws-close-status");
  23401. ASSERT_TRUE(client.connect());
  23402. // Trigger the server to close with GoingAway status
  23403. ASSERT_TRUE(client.send("trigger"));
  23404. // read() should return false after receiving the close frame
  23405. std::string msg;
  23406. EXPECT_FALSE(client.read(msg));
  23407. EXPECT_FALSE(client.is_open());
  23408. }
  23409. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23411. "/ws-echo");
  23412. ASSERT_TRUE(client.connect());
  23413. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23414. EXPECT_FALSE(client.is_open());
  23415. }
  23416. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23417. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23418. ws::WebSocketClient client(
  23419. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23420. ASSERT_TRUE(client.connect());
  23421. // Server should have selected graphql-ws
  23422. EXPECT_EQ("graphql-ws", client.subprotocol());
  23423. client.close();
  23424. }
  23425. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23426. Headers headers;
  23427. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23428. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23429. ws::WebSocketClient client(
  23430. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23431. ASSERT_TRUE(client.connect());
  23432. // The offer on the second field line counts too, so graphql-ws is selected
  23433. EXPECT_EQ("graphql-ws", client.subprotocol());
  23434. client.close();
  23435. }
  23436. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23437. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23438. ws::WebSocketClient client(
  23439. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23440. ASSERT_TRUE(client.connect());
  23441. // Server should not have selected any subprotocol
  23442. EXPECT_TRUE(client.subprotocol().empty());
  23443. client.close();
  23444. }
  23445. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23446. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23448. "/ws-subprotocol-unoffered",
  23449. headers);
  23450. ASSERT_TRUE(client.connect());
  23451. EXPECT_TRUE(client.subprotocol().empty());
  23452. client.close();
  23453. }
  23454. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23455. // Connect without requesting any subprotocol
  23456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23457. "/ws-subprotocol");
  23458. ASSERT_TRUE(client.connect());
  23459. EXPECT_TRUE(client.subprotocol().empty());
  23460. client.close();
  23461. }
  23462. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23464. "/ws-echo");
  23465. client.set_tcp_nodelay(true);
  23466. client.set_connection_timeout(3, 0);
  23467. bool socket_options_called = false;
  23468. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23469. ASSERT_TRUE(client.connect());
  23470. ASSERT_TRUE(client.is_open());
  23471. EXPECT_TRUE(socket_options_called);
  23472. ASSERT_TRUE(client.send("hello"));
  23473. std::string msg;
  23474. auto result = client.read(msg);
  23475. EXPECT_EQ(result, ws::ReadResult::Text);
  23476. EXPECT_EQ(msg, "hello");
  23477. client.close();
  23478. }
  23479. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23481. "/ws-echo");
  23482. client.set_connection_timeout(std::chrono::seconds(3));
  23483. client.set_write_timeout(std::chrono::seconds(3));
  23484. // A sub-second remainder exercises the seconds/microseconds split.
  23485. client.set_read_timeout(std::chrono::milliseconds(1500));
  23486. ASSERT_TRUE(client.connect());
  23487. auto start = std::chrono::steady_clock::now();
  23488. std::string msg;
  23489. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23490. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23491. std::chrono::steady_clock::now() - start)
  23492. .count();
  23493. // Above 1s so that dropping the microseconds half of the split fails here.
  23494. // Ignoring the setter altogether would not reach this line at all: a client
  23495. // waits forever by default.
  23496. EXPECT_GE(elapsed, 1400);
  23497. EXPECT_LT(elapsed, 30000);
  23498. }
  23499. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23500. Server svr;
  23501. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23502. if (!req.has_header("Authorization")) {
  23503. res.status = StatusCode::Unauthorized_401;
  23504. res.set_content("Unauthorized", "text/plain");
  23505. return Server::HandlerResponse::Handled;
  23506. }
  23507. return Server::HandlerResponse::Unhandled;
  23508. });
  23509. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23510. std::string msg;
  23511. while (ws.read(msg)) {
  23512. ws.send(msg);
  23513. }
  23514. });
  23515. auto port = svr.bind_to_any_port("localhost");
  23516. std::thread t([&]() { svr.listen_after_bind(); });
  23517. svr.wait_until_ready();
  23518. // Without Authorization header - should be rejected before upgrade
  23519. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23520. EXPECT_FALSE(client1.connect());
  23521. // The rejection is framed like any other HTTP response
  23522. {
  23523. Client cli("localhost", port);
  23524. Headers headers = {{"Upgrade", "websocket"},
  23525. {"Connection", "Upgrade"},
  23526. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23527. {"Sec-WebSocket-Version", "13"}};
  23528. auto res = cli.Get("/ws", headers);
  23529. ASSERT_TRUE(res);
  23530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23531. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23532. EXPECT_EQ("Unauthorized", res->body);
  23533. }
  23534. // With Authorization header - should succeed
  23535. Headers headers = {{"Authorization", "Bearer token123"}};
  23536. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23537. headers);
  23538. ASSERT_TRUE(client2.connect());
  23539. ASSERT_TRUE(client2.send("hello"));
  23540. std::string msg;
  23541. ASSERT_TRUE(client2.read(msg));
  23542. EXPECT_EQ("hello", msg);
  23543. client2.close();
  23544. svr.stop();
  23545. t.join();
  23546. }
  23547. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23548. Server svr;
  23549. std::atomic<int> pre_routing_calls{0};
  23550. std::atomic<int> pre_request_calls{0};
  23551. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23552. pre_routing_calls++;
  23553. if (req.path == "/handled") {
  23554. res.set_content("handled", "text/plain");
  23555. return Server::HandlerResponse::Handled;
  23556. }
  23557. return Server::HandlerResponse::Unhandled;
  23558. });
  23559. svr.set_pre_request_handler([&](const Request &, Response &) {
  23560. pre_request_calls++;
  23561. return Server::HandlerResponse::Unhandled;
  23562. });
  23563. svr.Get("/http", [](const Request &, Response &res) {
  23564. res.set_content("http", "text/plain");
  23565. });
  23566. svr.WebSocket("/ws",
  23567. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23568. auto port = svr.bind_to_any_port("localhost");
  23569. std::thread t([&]() { svr.listen_after_bind(); });
  23570. auto se = detail::scope_exit([&] {
  23571. svr.stop();
  23572. t.join();
  23573. });
  23574. svr.wait_until_ready();
  23575. Headers upgrade = {{"Upgrade", "websocket"},
  23576. {"Connection", "Upgrade"},
  23577. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23578. {"Sec-WebSocket-Version", "13"}};
  23579. auto get = [&](const char *path) {
  23580. pre_routing_calls = 0;
  23581. return Client("localhost", port).Get(path, upgrade);
  23582. };
  23583. // No WebSocket route, but an HTTP one
  23584. auto res = get("/http");
  23585. ASSERT_TRUE(res);
  23586. EXPECT_EQ(StatusCode::OK_200, res->status);
  23587. EXPECT_EQ("http", res->body);
  23588. EXPECT_EQ(1, pre_routing_calls);
  23589. EXPECT_EQ(1, pre_request_calls);
  23590. // No route at all
  23591. res = get("/none");
  23592. ASSERT_TRUE(res);
  23593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23594. EXPECT_EQ(1, pre_routing_calls);
  23595. // Answered by the pre-routing handler
  23596. res = get("/handled");
  23597. ASSERT_TRUE(res);
  23598. EXPECT_EQ(StatusCode::OK_200, res->status);
  23599. EXPECT_EQ("handled", res->body);
  23600. EXPECT_EQ(1, pre_routing_calls);
  23601. // A WebSocket route
  23602. pre_routing_calls = 0;
  23603. pre_request_calls = 0;
  23604. {
  23605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23606. "/ws");
  23607. ASSERT_TRUE(client.connect());
  23608. std::string msg;
  23609. ASSERT_TRUE(client.read(msg));
  23610. EXPECT_EQ("ws", msg);
  23611. client.close();
  23612. }
  23613. EXPECT_EQ(1, pre_routing_calls);
  23614. EXPECT_EQ(1, pre_request_calls);
  23615. }
  23616. // An upgrade request answered by a hook leaves its body unread, so that body
  23617. // must not be served as the next request on the connection.
  23618. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23619. Server svr;
  23620. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23621. if (req.path == "/pre-routing") {
  23622. res.set_content("pre-routing", "text/plain");
  23623. return Server::HandlerResponse::Handled;
  23624. }
  23625. return Server::HandlerResponse::Unhandled;
  23626. });
  23627. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23628. if (req.matched_route == "/pre-request") {
  23629. res.set_content("pre-request", "text/plain");
  23630. return Server::HandlerResponse::Handled;
  23631. }
  23632. return Server::HandlerResponse::Unhandled;
  23633. });
  23634. svr.Get("/smuggled", [](const Request &, Response &res) {
  23635. res.set_content("smuggled", "text/plain");
  23636. });
  23637. svr.WebSocket("/pre-request",
  23638. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23639. auto port = svr.bind_to_any_port(HOST);
  23640. std::thread t([&]() { svr.listen_after_bind(); });
  23641. auto se = detail::scope_exit([&] {
  23642. svr.stop();
  23643. t.join();
  23644. });
  23645. svr.wait_until_ready();
  23646. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23647. for (auto path : {"/pre-routing", "/pre-request"}) {
  23648. std::string req = std::string("GET ") + path +
  23649. " HTTP/1.1\r\n"
  23650. "Host: localhost\r\n"
  23651. "Upgrade: websocket\r\n"
  23652. "Connection: Upgrade\r\n"
  23653. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23654. "Sec-WebSocket-Version: 13\r\n"
  23655. "Content-Length: " +
  23656. std::to_string(body.size()) + "\r\n\r\n" + body;
  23657. std::string res;
  23658. ASSERT_TRUE(send_request(5, req, &res, port));
  23659. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23660. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23661. // Only one response, and the body was not served as a request
  23662. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23663. }
  23664. }
  23665. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23666. Server svr;
  23667. std::atomic<int> pre_request_calls{0};
  23668. std::atomic<bool> route_matched{false};
  23669. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23670. pre_request_calls++;
  23671. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23672. if (req.get_header_value("Authorization") != "Bearer token123") {
  23673. res.status = StatusCode::Unauthorized_401;
  23674. res.set_content("Unauthorized", "text/plain");
  23675. return Server::HandlerResponse::Handled;
  23676. }
  23677. return Server::HandlerResponse::Unhandled;
  23678. });
  23679. std::atomic<bool> handler_called{false};
  23680. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23681. handler_called = true;
  23682. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23683. });
  23684. auto port = svr.bind_to_any_port("localhost");
  23685. std::thread t([&]() { svr.listen_after_bind(); });
  23686. svr.wait_until_ready();
  23687. // Without Authorization header - should be rejected before upgrade
  23688. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23689. "/ws/1");
  23690. EXPECT_FALSE(client1.connect());
  23691. EXPECT_FALSE(handler_called);
  23692. EXPECT_EQ(1, pre_request_calls);
  23693. EXPECT_TRUE(route_matched);
  23694. // The rejection is an ordinary HTTP response, not a protocol switch
  23695. {
  23696. Client cli("localhost", port);
  23697. Headers headers = {{"Upgrade", "websocket"},
  23698. {"Connection", "Upgrade"},
  23699. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23700. {"Sec-WebSocket-Version", "13"}};
  23701. auto res = cli.Get("/ws/1", headers);
  23702. ASSERT_TRUE(res);
  23703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23704. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23705. EXPECT_EQ("Unauthorized", res->body);
  23706. }
  23707. EXPECT_FALSE(handler_called);
  23708. // With Authorization header - should succeed
  23709. Headers headers = {{"Authorization", "Bearer token123"}};
  23710. ws::WebSocketClient client2(
  23711. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23712. ASSERT_TRUE(client2.connect());
  23713. std::string msg;
  23714. ASSERT_TRUE(client2.read(msg));
  23715. EXPECT_EQ("/ws/:id 2", msg);
  23716. EXPECT_TRUE(handler_called);
  23717. client2.close();
  23718. svr.stop();
  23719. t.join();
  23720. }
  23721. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23722. static Headers websocket_upgrade_headers() {
  23723. return {{"Upgrade", "websocket"},
  23724. {"Connection", "Upgrade"},
  23725. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23726. {"Sec-WebSocket-Version", "13"},
  23727. {"Sec-WebSocket-Protocol", "chat"}};
  23728. }
  23729. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23730. Server svr;
  23731. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23732. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23733. return Server::HandlerResponse::Unhandled;
  23734. });
  23735. svr.set_pre_request_handler([](const Request &req, Response &) {
  23736. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23737. return Server::HandlerResponse::Unhandled;
  23738. });
  23739. svr.set_exception_handler(
  23740. [](const Request &, Response &res, std::exception_ptr ep) {
  23741. try {
  23742. std::rethrow_exception(ep);
  23743. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23744. });
  23745. auto handler = [](const Request &, ws::WebSocket &) {};
  23746. svr.WebSocket("/pre-routing", handler);
  23747. svr.WebSocket("/pre-request", handler);
  23748. svr.WebSocket("/sub-protocol", handler,
  23749. [](const std::vector<std::string> &) -> std::string {
  23750. throw std::runtime_error("/sub-protocol");
  23751. });
  23752. auto port = svr.bind_to_any_port(HOST);
  23753. ASSERT_GT(port, 0);
  23754. thread t = thread([&] { svr.listen_after_bind(); });
  23755. auto se = detail::scope_exit([&] {
  23756. svr.stop();
  23757. t.join();
  23758. ASSERT_FALSE(svr.is_running());
  23759. });
  23760. svr.wait_until_ready();
  23761. Client cli(HOST, port);
  23762. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23763. auto res = cli.Get(path, websocket_upgrade_headers());
  23764. if (!res) {
  23765. ADD_FAILURE() << path << ": " << to_string(res.error());
  23766. continue;
  23767. }
  23768. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23769. EXPECT_EQ(path, res->body);
  23770. }
  23771. }
  23772. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23773. Server svr;
  23774. svr.set_pre_routing_handler(
  23775. [](const Request &, Response &) -> Server::HandlerResponse {
  23776. throw std::runtime_error("pre-routing");
  23777. });
  23778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23779. auto port = svr.bind_to_any_port(HOST);
  23780. ASSERT_GT(port, 0);
  23781. thread t = thread([&] { svr.listen_after_bind(); });
  23782. auto se = detail::scope_exit([&] {
  23783. svr.stop();
  23784. t.join();
  23785. ASSERT_FALSE(svr.is_running());
  23786. });
  23787. svr.wait_until_ready();
  23788. Client cli(HOST, port);
  23789. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23790. ASSERT_TRUE(res) << to_string(res.error());
  23791. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23792. }
  23793. #endif
  23794. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23795. Server svr;
  23796. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23797. // A read timeout is how a handler gets control back. Without it, a handler
  23798. // parked in read() can never write on the connection it is reading.
  23799. ws.set_read_timeout(std::chrono::milliseconds(100));
  23800. std::string msg;
  23801. while (ws.is_open()) {
  23802. auto r = ws.read(msg);
  23803. if (r == httplib::ws::Timeout) {
  23804. ws.send("tick");
  23805. continue;
  23806. }
  23807. if (r == httplib::ws::Fail) { break; }
  23808. ws.send(msg);
  23809. }
  23810. });
  23811. auto port = svr.bind_to_any_port("localhost");
  23812. std::thread t([&]() { svr.listen_after_bind(); });
  23813. svr.wait_until_ready();
  23814. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23815. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23816. ASSERT_TRUE(client.connect());
  23817. // The client sends nothing, so anything it receives came out of the
  23818. // handler's timeout path.
  23819. std::string msg;
  23820. ASSERT_EQ(client.read(msg), ws::Text);
  23821. EXPECT_EQ("tick", msg);
  23822. client.close();
  23823. svr.stop();
  23824. t.join();
  23825. }
  23826. // Stream::read may return fewer bytes than asked for. This is that contract at
  23827. // its worst -- one byte per call -- which is what a frame header straddling a
  23828. // read buffer's boundary looks like to the frame parser.
  23829. class WsByteAtATimeStream : public Stream {
  23830. public:
  23831. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23832. bool is_readable() const override { return true; }
  23833. bool wait_readable() const override { return true; }
  23834. bool wait_writable() const override { return true; }
  23835. ssize_t read(char *ptr, size_t size) override {
  23836. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23837. *ptr = data_[pos_++];
  23838. return 1;
  23839. }
  23840. ssize_t write(const char *, size_t size) override {
  23841. return static_cast<ssize_t>(size);
  23842. }
  23843. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23844. ip = "127.0.0.1";
  23845. port = 0;
  23846. }
  23847. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23848. ip = "127.0.0.1";
  23849. port = 0;
  23850. }
  23851. socket_t socket() const override { return INVALID_SOCKET; }
  23852. time_t duration() const override { return 0; }
  23853. private:
  23854. std::string data_;
  23855. size_t pos_ = 0;
  23856. };
  23857. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23858. // The payload uses the 16-bit extended length, so the header, the length
  23859. // and the mask key are all multi-byte fields here. Each used to be read
  23860. // with a single read() call, which fails as soon as one is split. The
  23861. // payload is also a little over one read chunk, so it is read in two.
  23862. std::string body;
  23863. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23864. body += static_cast<char>(i % 251);
  23865. }
  23866. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23867. std::string frame;
  23868. frame += static_cast<char>(0x81); // FIN + Text
  23869. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23870. frame += static_cast<char>(body.size() >> 8);
  23871. frame += static_cast<char>(body.size() & 0xff);
  23872. for (size_t i = 0; i < 4; i++) {
  23873. frame += static_cast<char>(mask[i]);
  23874. }
  23875. for (size_t i = 0; i < body.size(); i++) {
  23876. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23877. }
  23878. WsByteAtATimeStream strm(frame);
  23879. ws::Opcode opcode;
  23880. std::string payload;
  23881. bool fin = false;
  23882. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23883. /*expect_masked=*/true, body.size()),
  23884. ws::impl::FrameRead::Ok);
  23885. EXPECT_TRUE(fin);
  23886. EXPECT_EQ(opcode, ws::Opcode::Text);
  23887. EXPECT_EQ(payload, body);
  23888. }
  23889. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23890. std::string body(2000, 'x');
  23891. std::string frame;
  23892. frame += static_cast<char>(0x82); // FIN + Binary
  23893. frame += static_cast<char>(126); // 16-bit length follows
  23894. frame += static_cast<char>(body.size() >> 8);
  23895. frame += static_cast<char>(body.size() & 0xff);
  23896. frame += body;
  23897. detail::BufferStream strm;
  23898. strm.write(frame.data(), frame.size());
  23899. ws::Opcode opcode;
  23900. std::string payload;
  23901. bool fin;
  23902. EXPECT_EQ(
  23903. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23904. ws::impl::FrameRead::Ok);
  23905. EXPECT_EQ(body, payload);
  23906. }
  23907. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23908. // The header announces the largest payload allowed, and only 3 bytes of it
  23909. // ever arrive.
  23910. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23911. std::string frame;
  23912. frame += static_cast<char>(0x82); // FIN + Binary
  23913. frame += static_cast<char>(127); // 64-bit length follows
  23914. for (int shift = 56; shift >= 0; shift -= 8) {
  23915. frame += static_cast<char>((len >> shift) & 0xff);
  23916. }
  23917. frame += "abc";
  23918. detail::BufferStream strm;
  23919. strm.write(frame.data(), frame.size());
  23920. ws::Opcode opcode;
  23921. std::string payload;
  23922. bool fin;
  23923. EXPECT_EQ(
  23924. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23925. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23926. ws::impl::FrameRead::Fail);
  23927. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23928. }
  23929. TEST(WebSocketTest, QueryStringInHandshake) {
  23930. Server svr;
  23931. std::mutex mtx;
  23932. std::string received_target;
  23933. std::string received_token;
  23934. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23935. {
  23936. std::lock_guard<std::mutex> lock(mtx);
  23937. received_target = req.target;
  23938. if (req.has_param("token")) {
  23939. received_token = req.get_param_value("token");
  23940. }
  23941. }
  23942. std::string msg;
  23943. while (ws.read(msg)) {
  23944. ws.send(msg);
  23945. }
  23946. });
  23947. auto port = svr.bind_to_any_port("localhost");
  23948. std::thread t([&]() { svr.listen_after_bind(); });
  23949. svr.wait_until_ready();
  23950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23951. "/ws?token=ABC&session=123");
  23952. ASSERT_TRUE(client.connect());
  23953. // Round-trip ensures the handler has run and captured the request.
  23954. ASSERT_TRUE(client.send("hello"));
  23955. std::string msg;
  23956. ASSERT_TRUE(client.read(msg));
  23957. EXPECT_EQ("hello", msg);
  23958. client.close();
  23959. {
  23960. std::lock_guard<std::mutex> lock(mtx);
  23961. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23962. EXPECT_EQ("ABC", received_token);
  23963. }
  23964. svr.stop();
  23965. t.join();
  23966. }
  23967. // Run a handshake against a throwaway server and hand the request the server
  23968. // received back to the caller, so tests can assert on the headers the client
  23969. // actually put on the wire.
  23970. static void capture_websocket_handshake_request(
  23971. const Headers &client_headers,
  23972. std::function<void(const Request &, int port)> verify) {
  23973. Server svr;
  23974. std::mutex mtx;
  23975. Request received;
  23976. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23977. {
  23978. std::lock_guard<std::mutex> lock(mtx);
  23979. received = req;
  23980. }
  23981. std::string msg;
  23982. while (ws.read(msg)) {
  23983. ws.send(msg);
  23984. }
  23985. });
  23986. auto port = svr.bind_to_any_port("localhost");
  23987. std::thread t([&]() { svr.listen_after_bind(); });
  23988. auto se = detail::scope_exit([&] {
  23989. svr.stop();
  23990. t.join();
  23991. });
  23992. svr.wait_until_ready();
  23993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23994. client_headers);
  23995. ASSERT_TRUE(client.connect());
  23996. ASSERT_TRUE(client.send("hello"));
  23997. std::string msg;
  23998. ASSERT_TRUE(client.read(msg));
  23999. client.close();
  24000. {
  24001. std::lock_guard<std::mutex> lock(mtx);
  24002. verify(received, port);
  24003. }
  24004. }
  24005. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24006. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24007. // Non-default port must be present in the Host header. Default ports
  24008. // (80/443) are omitted; that logic is covered by
  24009. // MakeHostAndPortStringTest.
  24010. EXPECT_EQ("localhost:" + std::to_string(port),
  24011. req.get_header_value("Host"));
  24012. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24013. req.get_header_value("User-Agent"));
  24014. EXPECT_FALSE(req.has_header("Accept"));
  24015. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24016. EXPECT_FALSE(req.has_header("Content-Length"));
  24017. });
  24018. }
  24019. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24020. capture_websocket_handshake_request(
  24021. {{"Host", "example.com"},
  24022. {"User-Agent", "custom-agent"},
  24023. {"X-Custom", "value"}},
  24024. [](const Request &req, int) {
  24025. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24026. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24027. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24028. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24029. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24030. });
  24031. }
  24032. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24033. capture_websocket_handshake_request(
  24034. {{"Upgrade", "bogus"},
  24035. {"Connection", "close"},
  24036. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24037. {"Sec-WebSocket-Version", "8"}},
  24038. [](const Request &req, int) {
  24039. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24040. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24041. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24042. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24043. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24044. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24045. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24046. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24047. req.get_header_value("Sec-WebSocket-Key"));
  24048. });
  24049. }
  24050. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24051. // A header the client refuses to send must abort the handshake before any
  24052. // part of it reaches the wire; a lone request line would otherwise sit in
  24053. // the peer's buffer as a truncated request.
  24054. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24055. ASSERT_NE(INVALID_SOCKET, srv);
  24056. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24057. sockaddr_in addr{};
  24058. addr.sin_family = AF_INET;
  24059. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24060. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24061. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24062. ASSERT_EQ(0, ::listen(srv, 1));
  24063. sockaddr_in bound{};
  24064. socklen_t bound_len = sizeof(bound);
  24065. ASSERT_EQ(
  24066. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24067. auto port = ntohs(bound.sin_port);
  24068. ssize_t received = -1;
  24069. std::thread t([&] {
  24070. // Bound every blocking call so a regression fails the test with a bad
  24071. // value instead of hanging the suite.
  24072. fd_set rfds;
  24073. FD_ZERO(&rfds);
  24074. FD_SET(srv, &rfds);
  24075. timeval tv{5, 0};
  24076. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24077. 0) {
  24078. return;
  24079. }
  24080. sockaddr_in cli_addr{};
  24081. socklen_t cli_len = sizeof(cli_addr);
  24082. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24083. if (cli == INVALID_SOCKET) { return; }
  24084. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24085. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24086. char buf[4096];
  24087. received = ::recv(cli, buf, sizeof(buf), 0);
  24088. });
  24089. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24090. // connect() has already shut the socket down by the time it returns false,
  24091. // so the peer sees EOF without waiting for the client to be destroyed.
  24092. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24093. {{"X-Bad", "a\r\nInjected: 1"}});
  24094. EXPECT_FALSE(client.connect());
  24095. t.join();
  24096. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24097. EXPECT_EQ(0, received);
  24098. }
  24099. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24100. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24101. // contains "upgrade" as a substring is a different token and must not
  24102. // start a WebSocket handshake.
  24103. auto make_request = [](const std::vector<std::string> &connection_values) {
  24104. Request req;
  24105. req.method = "GET";
  24106. req.headers.emplace("Upgrade", "websocket");
  24107. for (const auto &value : connection_values) {
  24108. req.headers.emplace("Connection", value);
  24109. }
  24110. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24111. req.headers.emplace("Sec-WebSocket-Version", "13");
  24112. return req;
  24113. };
  24114. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24115. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24116. EXPECT_TRUE(
  24117. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24118. EXPECT_TRUE(
  24119. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24120. EXPECT_TRUE(
  24121. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24122. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24123. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24124. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24125. EXPECT_FALSE(
  24126. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24127. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24128. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24129. }
  24130. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24131. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24132. // asks recipients to match each protocol-name case-insensitively, and RFC
  24133. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24134. // client naming websocket alongside another protocol, or on a second field
  24135. // line, is offering websocket; a value that merely contains "websocket" as a
  24136. // substring is a different protocol name and is not.
  24137. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24138. Request req;
  24139. req.method = "GET";
  24140. for (const auto &value : upgrade_values) {
  24141. req.headers.emplace("Upgrade", value);
  24142. }
  24143. req.headers.emplace("Connection", "Upgrade");
  24144. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24145. req.headers.emplace("Sec-WebSocket-Version", "13");
  24146. return req;
  24147. };
  24148. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24149. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24150. EXPECT_TRUE(
  24151. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24152. EXPECT_TRUE(
  24153. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24154. EXPECT_TRUE(
  24155. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24156. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24157. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24158. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24159. EXPECT_FALSE(
  24160. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24161. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24162. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24163. }
  24164. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24165. Server svr;
  24166. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24167. auto port = svr.bind_to_any_port("localhost");
  24168. std::thread t([&]() { svr.listen_after_bind(); });
  24169. auto se = detail::scope_exit([&] {
  24170. svr.stop();
  24171. t.join();
  24172. });
  24173. svr.wait_until_ready();
  24174. Headers headers = {{"Upgrade", "websocket"},
  24175. {"Connection", "notupgrade"},
  24176. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24177. {"Sec-WebSocket-Version", "13"}};
  24178. Client cli("localhost", port);
  24179. auto res = cli.Get("/ws", headers);
  24180. // The route exists only as a WebSocket route, so a request that fails the
  24181. // handshake check falls through to ordinary routing.
  24182. ASSERT_TRUE(res);
  24183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24184. }
  24185. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24186. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24187. // Connection value is the only thing left for the client to reject.
  24188. Server svr;
  24189. svr.Get("/ws", [](const Request &req, Response &res) {
  24190. res.status = StatusCode::SwitchingProtocol_101;
  24191. res.set_header("Upgrade", "websocket");
  24192. res.set_header("Connection", "notupgrade");
  24193. res.set_header("Sec-WebSocket-Accept",
  24194. detail::websocket_accept_key(
  24195. req.get_header_value("Sec-WebSocket-Key")));
  24196. });
  24197. auto port = svr.bind_to_any_port("localhost");
  24198. std::thread t([&]() { svr.listen_after_bind(); });
  24199. auto se = detail::scope_exit([&] {
  24200. svr.stop();
  24201. t.join();
  24202. });
  24203. svr.wait_until_ready();
  24204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24205. auto res = client.connect();
  24206. EXPECT_FALSE(res);
  24207. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24208. EXPECT_FALSE(client.is_open());
  24209. }
  24210. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24211. Server svr;
  24212. svr.Get("/ws", [](const Request &req, Response &res) {
  24213. res.status = StatusCode::SwitchingProtocol_101;
  24214. res.set_header("Upgrade", "websocket");
  24215. res.set_header("Connection", "Upgrade");
  24216. res.set_header("Sec-WebSocket-Accept",
  24217. detail::websocket_accept_key(
  24218. req.get_header_value("Sec-WebSocket-Key")));
  24219. res.set_header("Sec-WebSocket-Protocol", "admin");
  24220. });
  24221. auto port = svr.bind_to_any_port("localhost");
  24222. std::thread t([&]() { svr.listen_after_bind(); });
  24223. auto se = detail::scope_exit([&] {
  24224. svr.stop();
  24225. t.join();
  24226. });
  24227. svr.wait_until_ready();
  24228. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24229. // Server selects a subprotocol the client never offered
  24230. {
  24231. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24232. ws::WebSocketClient client(url, headers);
  24233. auto res = client.connect();
  24234. EXPECT_FALSE(res);
  24235. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24236. EXPECT_FALSE(client.is_open());
  24237. EXPECT_TRUE(client.subprotocol().empty());
  24238. }
  24239. // Client offered none but the server named one anyway
  24240. {
  24241. ws::WebSocketClient client(url);
  24242. auto res = client.connect();
  24243. EXPECT_FALSE(res);
  24244. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24245. EXPECT_FALSE(client.is_open());
  24246. EXPECT_TRUE(client.subprotocol().empty());
  24247. }
  24248. }
  24249. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24250. // The socket path doubles as the URL host, so it must not contain '/'.
  24251. const char *shard = getenv("GTEST_SHARD_INDEX");
  24252. const std::string sock_path =
  24253. shard ? std::string("httplib-ws-") + shard + ".sock"
  24254. : std::string("httplib-ws.sock");
  24255. std::remove(sock_path.c_str());
  24256. Server svr;
  24257. std::mutex mtx;
  24258. std::string received_host;
  24259. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24260. {
  24261. std::lock_guard<std::mutex> lock(mtx);
  24262. received_host = req.get_header_value("Host");
  24263. }
  24264. std::string msg;
  24265. while (ws.read(msg)) {
  24266. ws.send(msg);
  24267. }
  24268. });
  24269. svr.set_address_family(AF_UNIX);
  24270. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24271. auto se = detail::scope_exit([&] {
  24272. svr.stop();
  24273. t.join();
  24274. std::remove(sock_path.c_str());
  24275. });
  24276. svr.wait_until_ready();
  24277. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24278. client.set_address_family(AF_UNIX);
  24279. ASSERT_TRUE(client.connect());
  24280. ASSERT_TRUE(client.send("hello"));
  24281. std::string msg;
  24282. ASSERT_TRUE(client.read(msg));
  24283. client.close();
  24284. {
  24285. std::lock_guard<std::mutex> lock(mtx);
  24286. // There is no host:port for a Unix socket, so the same "localhost"
  24287. // placeholder the HTTP client uses is expected.
  24288. EXPECT_EQ("localhost", received_host);
  24289. }
  24290. }
  24291. // Two threads must never parse WebSocket frames from the same stream.
  24292. // close() used to read the peer's Close reply with its own frame read, so it
  24293. // raced a reader thread that was in the middle of a payload: the payload loop
  24294. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24295. // so bytes taken by close() were replaced with bytes from further along the
  24296. // stream. The message kept its length and silently changed content.
  24297. //
  24298. // The raw peer below sends a frame header plus part of the payload, waits for
  24299. // the handler to call close(), and only then sends the rest. Whichever thread
  24300. // would win the race for those bytes, the message must arrive intact, because
  24301. // close() must not touch the stream while read() owns it.
  24302. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24303. #ifndef _WIN32
  24304. signal(SIGPIPE, SIG_IGN);
  24305. #endif
  24306. const size_t payload_len = 120; // fits the 7-bit length field
  24307. const size_t prefix_len = 8;
  24308. const int attempts = 8;
  24309. std::string expected(payload_len, '\0');
  24310. for (size_t i = 0; i < payload_len; i++) {
  24311. expected[i] = static_cast<char>('a' + i % 26);
  24312. }
  24313. std::atomic<bool> peer_stalled{false};
  24314. std::atomic<bool> handler_done{false};
  24315. std::mutex received_mutex;
  24316. std::vector<std::string> received;
  24317. // Bound every wait, so a regression fails the test instead of hanging the
  24318. // suite.
  24319. auto wait_for = [](const std::atomic<bool> &flag) {
  24320. for (int i = 0; i < 500 && !flag; i++) {
  24321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24322. }
  24323. };
  24324. Server svr;
  24325. svr.set_websocket_ping_interval(0);
  24326. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24327. std::thread reader([&]() {
  24328. std::string msg;
  24329. while (ws.read(msg)) {
  24330. std::lock_guard<std::mutex> guard(received_mutex);
  24331. received.push_back(msg);
  24332. }
  24333. });
  24334. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24335. // inside read_websocket_frame() when close() runs.
  24336. wait_for(peer_stalled);
  24337. ws.close();
  24338. reader.join();
  24339. handler_done = true;
  24340. });
  24341. auto port = svr.bind_to_any_port("127.0.0.1");
  24342. std::thread t([&]() { svr.listen_after_bind(); });
  24343. auto se = detail::scope_exit([&] {
  24344. svr.stop();
  24345. t.join();
  24346. });
  24347. svr.wait_until_ready();
  24348. auto send_bytes = [](socket_t s, const std::string &data) {
  24349. #ifdef _WIN32
  24350. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24351. #else
  24352. auto n = ::send(s, data.data(), data.size(), 0);
  24353. #endif
  24354. return n == static_cast<decltype(n)>(data.size());
  24355. };
  24356. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24357. // Every length used here fits the 7-bit length field.
  24358. auto masked_header = [](uint8_t first_byte, size_t len) {
  24359. std::string h;
  24360. h += static_cast<char>(first_byte);
  24361. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24362. h.append(4, '\0'); // mask key
  24363. return h;
  24364. };
  24365. for (int attempt = 0; attempt < attempts; attempt++) {
  24366. peer_stalled = false;
  24367. handler_done = false;
  24368. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24369. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24370. auto se_sock = detail::scope_exit([&] {
  24371. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24372. });
  24373. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24374. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24375. sockaddr_in addr{};
  24376. addr.sin_family = AF_INET;
  24377. addr.sin_port = htons(static_cast<uint16_t>(port));
  24378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24379. ASSERT_EQ(
  24380. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24381. << "attempt " << attempt;
  24382. ASSERT_TRUE(send_bytes(sock,
  24383. "GET /ws HTTP/1.1\r\n"
  24384. "Host: 127.0.0.1\r\n"
  24385. "Upgrade: websocket\r\n"
  24386. "Connection: Upgrade\r\n"
  24387. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24388. "Sec-WebSocket-Version: 13\r\n"
  24389. "\r\n"))
  24390. << "attempt " << attempt;
  24391. std::string response;
  24392. while (response.find("\r\n\r\n") == std::string::npos) {
  24393. char buf[512];
  24394. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24395. if (n <= 0) { break; }
  24396. response.append(buf, static_cast<size_t>(n));
  24397. }
  24398. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24399. << "attempt " << attempt;
  24400. // Send the header of a Binary message but only the first prefix_len bytes
  24401. // of its payload, leaving the reader thread stalled inside the payload.
  24402. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24403. expected.substr(0, prefix_len)))
  24404. << "attempt " << attempt;
  24405. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24406. peer_stalled = true;
  24407. // Let close() send its Close frame and park in its own read before the
  24408. // rest of the payload arrives, so both threads are waiting for it.
  24409. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24410. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24411. close_frame += static_cast<char>(0x03); // status 1000
  24412. close_frame += static_cast<char>(0xE8);
  24413. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24414. << "attempt " << attempt;
  24415. // Closing the peer releases the reader thread even on the buggy path,
  24416. // where it waits for bytes another thread already consumed.
  24417. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24418. detail::close_socket(sock);
  24419. sock = INVALID_SOCKET;
  24420. wait_for(handler_done);
  24421. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24422. }
  24423. std::lock_guard<std::mutex> guard(received_mutex);
  24424. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24425. << "a message in flight when close() ran was dropped";
  24426. for (size_t i = 0; i < received.size(); i++) {
  24427. EXPECT_EQ(expected, received[i]) << "message " << i;
  24428. }
  24429. }
  24430. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24431. // returning the socket, or INVALID_SOCKET.
  24432. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24433. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24434. if (sock == INVALID_SOCKET) { return sock; }
  24435. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24436. sockaddr_in addr{};
  24437. addr.sin_family = AF_INET;
  24438. addr.sin_port = htons(static_cast<uint16_t>(port));
  24439. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24440. std::string req = "GET " + path +
  24441. " HTTP/1.1\r\n"
  24442. "Host: 127.0.0.1\r\n"
  24443. "Upgrade: websocket\r\n"
  24444. "Connection: Upgrade\r\n"
  24445. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24446. "Sec-WebSocket-Version: 13\r\n"
  24447. "\r\n";
  24448. std::string res;
  24449. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24450. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24451. static_cast<ssize_t>(req.size())) {
  24452. char c;
  24453. while (res.find("\r\n\r\n") == std::string::npos &&
  24454. ::recv(sock, &c, 1, 0) == 1) {
  24455. res += c;
  24456. }
  24457. }
  24458. if (res.find(" 101 ") == std::string::npos) {
  24459. detail::close_socket(sock);
  24460. return INVALID_SOCKET;
  24461. }
  24462. return sock;
  24463. }
  24464. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24465. // The payload must fit the 7-bit length field.
  24466. static std::string masked_frame(uint8_t first_byte,
  24467. const std::string &payload) {
  24468. std::string f;
  24469. f += static_cast<char>(first_byte);
  24470. f += static_cast<char>(0x80 | payload.size());
  24471. f.append(4, '\0');
  24472. return f + payload;
  24473. }
  24474. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24475. std::atomic<bool> done{false};
  24476. std::string received;
  24477. Server svr;
  24478. svr.set_websocket_ping_interval(0);
  24479. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24480. std::string msg;
  24481. if (ws.read(msg) == ws::Binary) { received = msg; }
  24482. done = true;
  24483. });
  24484. auto port = svr.bind_to_any_port("127.0.0.1");
  24485. std::thread t([&]() { svr.listen_after_bind(); });
  24486. auto se = detail::scope_exit([&] {
  24487. svr.stop();
  24488. t.join();
  24489. });
  24490. svr.wait_until_ready();
  24491. auto sock = connect_raw_websocket(port, "/ws");
  24492. ASSERT_NE(INVALID_SOCKET, sock);
  24493. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24494. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24495. masked_frame(0x89, "p") + // FIN + Ping
  24496. masked_frame(0x80, "lo"); // FIN + Continuation
  24497. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24498. for (int i = 0; i < 500 && !done; i++) {
  24499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24500. }
  24501. ASSERT_TRUE(done);
  24502. EXPECT_EQ("Hello", received);
  24503. // The Ping between the fragments is answered with a Pong.
  24504. char pong[3];
  24505. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24506. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24507. }
  24508. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24509. Server svr;
  24510. svr.set_websocket_ping_interval(-1);
  24511. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24512. std::string msg;
  24513. while (ws.read(msg)) {}
  24514. });
  24515. auto port = svr.bind_to_any_port("127.0.0.1");
  24516. std::thread t([&]() { svr.listen_after_bind(); });
  24517. auto se = detail::scope_exit([&] {
  24518. svr.stop();
  24519. t.join();
  24520. });
  24521. svr.wait_until_ready();
  24522. auto sock = connect_raw_websocket(port, "/ws");
  24523. ASSERT_NE(INVALID_SOCKET, sock);
  24524. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24525. // Nothing comes while the client stays quiet.
  24526. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24527. char c;
  24528. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24529. }
  24530. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24531. // and that has to end a read() already waiting on the peer, on every platform.
  24532. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24533. // The peer sends no pings, and its handler never calls read(), which is
  24534. // where pongs are written.
  24535. std::mutex mutex;
  24536. std::condition_variable cv;
  24537. auto release = false;
  24538. svr.set_websocket_ping_interval(0);
  24539. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24540. std::unique_lock<std::mutex> lock(mutex);
  24541. cv.wait(lock, [&] { return release; });
  24542. });
  24543. auto port = svr.bind_to_any_port(HOST);
  24544. std::thread t([&]() { svr.listen_after_bind(); });
  24545. auto se = detail::scope_exit([&] {
  24546. {
  24547. std::lock_guard<std::mutex> lock(mutex);
  24548. release = true;
  24549. }
  24550. cv.notify_all();
  24551. svr.stop();
  24552. t.join();
  24553. });
  24554. svr.wait_until_ready();
  24555. ws::WebSocketClient client(std::string(scheme) +
  24556. "://localhost:" + std::to_string(port) + "/ws");
  24557. #ifdef CPPHTTPLIB_SSL_ENABLED
  24558. client.enable_server_certificate_verification(false);
  24559. #endif
  24560. // A ping a second, given up on after two go unanswered: about 3s
  24561. client.set_websocket_ping_interval(1);
  24562. client.set_websocket_max_missed_pongs(2);
  24563. // Well past that, so that a read the timeout ends instead stands out
  24564. client.set_read_timeout(10);
  24565. ASSERT_TRUE(client.connect());
  24566. auto start = std::chrono::steady_clock::now();
  24567. std::string msg;
  24568. EXPECT_EQ(ws::Fail, client.read(msg));
  24569. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24570. std::chrono::steady_clock::now() - start)
  24571. .count(),
  24572. 6000);
  24573. EXPECT_FALSE(client.is_open());
  24574. }
  24575. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24576. Server svr;
  24577. check_pong_timeout_ends_read(svr, "ws");
  24578. }
  24579. #ifdef CPPHTTPLIB_SSL_ENABLED
  24580. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24582. ASSERT_TRUE(svr.is_valid());
  24583. check_pong_timeout_ends_read(svr, "wss");
  24584. }
  24585. #endif
  24586. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24587. Server svr;
  24588. svr.set_websocket_ping_interval(0);
  24589. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24590. std::string msg;
  24591. while (ws.read(msg)) {}
  24592. });
  24593. auto port = svr.bind_to_any_port("127.0.0.1");
  24594. std::thread t([&]() { svr.listen_after_bind(); });
  24595. auto se = detail::scope_exit([&] {
  24596. svr.stop();
  24597. t.join();
  24598. });
  24599. svr.wait_until_ready();
  24600. // Each Close payload and the reply it should get: an echo when valid, 1002
  24601. // otherwise.
  24602. std::vector<std::pair<std::string, std::string>> cases = {
  24603. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24604. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24605. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24606. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24607. };
  24608. // Also between the fragments of a message.
  24609. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24610. for (const auto &c : cases) {
  24611. auto sock = connect_raw_websocket(port, "/ws");
  24612. ASSERT_NE(INVALID_SOCKET, sock);
  24613. auto frames = prefix + masked_frame(0x88, c.first);
  24614. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24615. std::string reply;
  24616. char buf[256];
  24617. while (reply.size() < 2 + c.second.size()) {
  24618. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24619. if (n <= 0) { break; }
  24620. reply.append(buf, static_cast<size_t>(n));
  24621. }
  24622. detail::close_socket(sock);
  24623. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24624. c.second,
  24625. reply);
  24626. }
  24627. }
  24628. }
  24629. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24630. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24631. protected:
  24632. void SetUp() override {
  24633. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24634. SERVER_PRIVATE_KEY_FILE);
  24635. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24636. std::string msg;
  24637. ws::ReadResult ret;
  24638. while ((ret = ws.read(msg))) {
  24639. if (ret == ws::Binary) {
  24640. ws.send(msg.data(), msg.size());
  24641. } else {
  24642. ws.send(msg);
  24643. }
  24644. }
  24645. });
  24646. port_ = server_->bind_to_any_port(HOST);
  24647. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24648. server_->wait_until_ready();
  24649. }
  24650. void TearDown() override {
  24651. server_->stop();
  24652. if (server_thread_.joinable()) { server_thread_.join(); }
  24653. }
  24654. std::unique_ptr<SSLServer> server_;
  24655. std::thread server_thread_;
  24656. int port_ = 0;
  24657. };
  24658. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24659. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24660. {
  24661. ws::WebSocketClient client(url);
  24662. client.enable_server_certificate_verification(false);
  24663. auto calls = 0;
  24664. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24665. calls++;
  24666. return false;
  24667. });
  24668. EXPECT_FALSE(client.connect());
  24669. EXPECT_GT(calls, 0);
  24670. }
  24671. {
  24672. ws::WebSocketClient client(url);
  24673. client.enable_server_certificate_verification(false);
  24674. client.set_session_verifier([](tls::session_t) {
  24675. return SSLVerifierResponse::CertificateRejected;
  24676. });
  24677. EXPECT_FALSE(client.connect());
  24678. }
  24679. {
  24680. ws::WebSocketClient client(url);
  24681. client.enable_server_certificate_verification(false);
  24682. client.set_session_verifier([](tls::session_t) {
  24683. return SSLVerifierResponse::CertificateAccepted;
  24684. });
  24685. EXPECT_TRUE(client.connect());
  24686. }
  24687. }
  24688. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24689. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24690. "/ws-echo");
  24691. client.enable_server_certificate_verification(false);
  24692. ASSERT_TRUE(client.connect());
  24693. ASSERT_TRUE(client.is_open());
  24694. ASSERT_TRUE(client.send("Hello WSS"));
  24695. std::string msg;
  24696. EXPECT_EQ(ws::Text, client.read(msg));
  24697. EXPECT_EQ("Hello WSS", msg);
  24698. client.close();
  24699. }
  24700. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24701. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24702. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24703. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24704. // client (without calling close() first) is the only path that runs
  24705. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24706. // bug exactly.
  24707. //
  24708. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24709. // when linked against an instrumented libssl; run under Valgrind to catch it
  24710. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24711. // suite (the freed session otherwise stalls on the close handshake) — this test
  24712. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24713. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24714. {
  24715. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24716. "/ws-echo");
  24717. client.enable_server_certificate_verification(false);
  24718. client.set_read_timeout(2, 0);
  24719. client.set_write_timeout(2, 0);
  24720. ASSERT_TRUE(client.connect());
  24721. ASSERT_TRUE(client.is_open());
  24722. ASSERT_TRUE(client.send("still open"));
  24723. // Intentionally do NOT call client.close(): leaving scope runs
  24724. // shutdown_and_close() with the WebSocket still open, which must send the
  24725. // close frame while the TLS session is still alive.
  24726. }
  24727. }
  24728. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24729. // shutdown_and_close() at the start of connect(), reproducing the same
  24730. // use-after-free within the test body rather than at scope exit. The second
  24731. // connect must succeed and echo, proving the close handshake ran over a live
  24732. // session. See the note above about memory-tool requirements.
  24733. TEST_F(WebSocketSSLIntegrationTest,
  24734. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24735. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24736. "/ws-echo");
  24737. client.enable_server_certificate_verification(false);
  24738. client.set_read_timeout(2, 0);
  24739. client.set_write_timeout(2, 0);
  24740. ASSERT_TRUE(client.connect());
  24741. ASSERT_TRUE(client.is_open());
  24742. ASSERT_TRUE(client.send("still open"));
  24743. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24744. // the still-open connection, which must not touch a freed TLS session.
  24745. ASSERT_TRUE(client.connect());
  24746. ASSERT_TRUE(client.is_open());
  24747. ASSERT_TRUE(client.send("after reconnect"));
  24748. std::string msg;
  24749. EXPECT_EQ(ws::Text, client.read(msg));
  24750. EXPECT_EQ("after reconnect", msg);
  24751. client.close();
  24752. }
  24753. #endif
  24754. #ifdef CPPHTTPLIB_SSL_ENABLED
  24755. class WebSocketSSLCATest : public ::testing::Test {
  24756. protected:
  24757. void SetUp() override {
  24758. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24759. SERVER_PRIVATE_KEY_FILE);
  24760. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24761. std::string msg;
  24762. while (ws.read(msg)) {
  24763. ws.send(msg);
  24764. }
  24765. });
  24766. port_ = server_->bind_to_any_port("127.0.0.1");
  24767. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24768. server_->wait_until_ready();
  24769. }
  24770. void TearDown() override {
  24771. server_->stop();
  24772. if (server_thread_.joinable()) { server_thread_.join(); }
  24773. }
  24774. std::string url() const {
  24775. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24776. }
  24777. std::unique_ptr<SSLServer> server_;
  24778. std::thread server_thread_;
  24779. int port_ = 0;
  24780. };
  24781. // A custom CA loaded as PEM verifies the server with full certificate
  24782. // verification enabled
  24783. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24784. ws::WebSocketClient client(url());
  24785. std::string cert;
  24786. read_file(SERVER_CERT2_FILE, cert);
  24787. client.load_ca_cert_store(cert.c_str(), cert.size());
  24788. ASSERT_TRUE(client.connect());
  24789. ASSERT_TRUE(client.send("hello"));
  24790. std::string msg;
  24791. EXPECT_EQ(ws::Text, client.read(msg));
  24792. EXPECT_EQ("hello", msg);
  24793. client.close();
  24794. }
  24795. // A custom CA that does not cover the server must fail verification (the
  24796. // custom CA is exclusive; system certs are not loaded alongside it)
  24797. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24798. ws::WebSocketClient client(url());
  24799. std::string cert;
  24800. read_file(CLIENT_CA_CERT_FILE, cert);
  24801. client.load_ca_cert_store(cert.c_str(), cert.size());
  24802. auto res = client.connect();
  24803. ASSERT_FALSE(res);
  24804. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24805. EXPECT_EQ(-1, res.status());
  24806. EXPECT_NE(0u, res.ssl_backend_error());
  24807. }
  24808. // The same CA as a file path rather than PEM in memory
  24809. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24810. ws::WebSocketClient client(url());
  24811. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24812. ASSERT_TRUE(client.connect());
  24813. ASSERT_TRUE(client.send("hello"));
  24814. std::string msg;
  24815. EXPECT_EQ(ws::Text, client.read(msg));
  24816. EXPECT_EQ("hello", msg);
  24817. client.close();
  24818. }
  24819. // ...and a CA file that does not cover the server still fails, so it is the
  24820. // path above that decides the outcome
  24821. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24822. ws::WebSocketClient client(url());
  24823. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24824. ASSERT_FALSE(client.connect());
  24825. }
  24826. // Regression test: reconnecting with a native custom CA store used to reuse
  24827. // a store handle the previous TLS context had already freed (use-after-free
  24828. // under the OpenSSL backend). The context now lives as long as the client.
  24829. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24830. ws::WebSocketClient client(url());
  24831. std::string cert;
  24832. read_file(SERVER_CERT2_FILE, cert);
  24833. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24834. ASSERT_TRUE(client.connect());
  24835. client.close();
  24836. ASSERT_TRUE(client.connect());
  24837. ASSERT_TRUE(client.send("again"));
  24838. std::string msg;
  24839. EXPECT_EQ(ws::Text, client.read(msg));
  24840. EXPECT_EQ("again", msg);
  24841. client.close();
  24842. }
  24843. // Regression test: a certificate with a trusted chain but no identity match
  24844. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24845. // verification entirely for IP hosts, so this connection succeeded there.
  24846. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24847. // chain verification while the identity check must still fail.
  24848. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24850. ASSERT_TRUE(svr.is_valid());
  24851. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24852. std::string msg;
  24853. while (ws.read(msg)) {
  24854. ws.send(msg);
  24855. }
  24856. });
  24857. auto port = svr.bind_to_any_port("127.0.0.1");
  24858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24859. auto se = detail::scope_exit([&] {
  24860. svr.stop();
  24861. t.join();
  24862. });
  24863. svr.wait_until_ready();
  24864. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24865. "/echo");
  24866. std::string cert;
  24867. read_file(SERVER_CERT_FILE, cert);
  24868. client.load_ca_cert_store(cert.c_str(), cert.size());
  24869. ASSERT_FALSE(client.connect());
  24870. }
  24871. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24872. // SNI, so nothing binds the host name to the TLS session. These bind the
  24873. // server to "localhost" instead, the only shape that exercises the SNI and
  24874. // hostname-verification path with certificate verification left enabled.
  24875. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24876. protected:
  24877. void Start(const char *cert_file) {
  24878. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24879. SERVER_PRIVATE_KEY_FILE);
  24880. ASSERT_TRUE(server_->is_valid());
  24881. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24882. std::string msg;
  24883. while (ws.read(msg)) {
  24884. ws.send(msg);
  24885. }
  24886. });
  24887. port_ = server_->bind_to_any_port("localhost");
  24888. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24889. server_->wait_until_ready();
  24890. }
  24891. void TearDown() override {
  24892. if (server_) { server_->stop(); }
  24893. if (server_thread_.joinable()) { server_thread_.join(); }
  24894. }
  24895. std::string url() const {
  24896. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24897. }
  24898. std::unique_ptr<SSLServer> server_;
  24899. std::thread server_thread_;
  24900. int port_ = 0;
  24901. };
  24902. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24903. // out and the connection is usable
  24904. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24905. Start(SERVER_CERT2_FILE);
  24906. ws::WebSocketClient client(url());
  24907. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24908. ASSERT_TRUE(client.connect());
  24909. ASSERT_TRUE(client.send("hello"));
  24910. std::string msg;
  24911. EXPECT_EQ(ws::Text, client.read(msg));
  24912. EXPECT_EQ("hello", msg);
  24913. client.close();
  24914. }
  24915. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24916. // while the identity check must still reject "localhost"
  24917. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24918. Start(SERVER_CERT_FILE);
  24919. ws::WebSocketClient client(url());
  24920. client.set_ca_cert_path(SERVER_CERT_FILE);
  24921. auto res = client.connect();
  24922. ASSERT_FALSE(res);
  24923. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24924. EXPECT_EQ(-1, res.status());
  24925. }
  24926. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24927. // disabled: the chain is still checked, only the identity check is skipped
  24928. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24929. Start(SERVER_CERT_FILE);
  24930. ws::WebSocketClient client(url());
  24931. client.set_ca_cert_path(SERVER_CERT_FILE);
  24932. client.enable_server_hostname_verification(false);
  24933. ASSERT_TRUE(client.connect());
  24934. ASSERT_TRUE(client.send("hello"));
  24935. std::string msg;
  24936. EXPECT_EQ(ws::Text, client.read(msg));
  24937. EXPECT_EQ("hello", msg);
  24938. client.close();
  24939. }
  24940. // A CA that did not sign the server certificate fails the chain, even though
  24941. // the name would match
  24942. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24943. Start(SERVER_CERT2_FILE);
  24944. ws::WebSocketClient client(url());
  24945. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24946. ASSERT_FALSE(client.connect());
  24947. }
  24948. // With verification disabled, neither the chain nor the name is checked
  24949. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24950. Start(SERVER_CERT_FILE);
  24951. ws::WebSocketClient client(url());
  24952. client.enable_server_certificate_verification(false);
  24953. ASSERT_TRUE(client.connect());
  24954. ASSERT_TRUE(client.send("hello"));
  24955. std::string msg;
  24956. EXPECT_EQ(ws::Text, client.read(msg));
  24957. EXPECT_EQ("hello", msg);
  24958. client.close();
  24959. }
  24960. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24961. protected:
  24962. void SetUp() override {
  24963. server_ = httplib::detail::make_unique<SSLServer>(
  24964. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24965. ASSERT_TRUE(server_->is_valid());
  24966. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24967. std::string msg;
  24968. while (ws.read(msg)) {
  24969. ws.send(msg);
  24970. }
  24971. });
  24972. port_ = server_->bind_to_any_port("localhost");
  24973. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24974. server_->wait_until_ready();
  24975. }
  24976. void TearDown() override {
  24977. server_->stop();
  24978. if (server_thread_.joinable()) { server_thread_.join(); }
  24979. }
  24980. std::string url() const {
  24981. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24982. }
  24983. void ConnectWithClientCert(const std::string &client_cert_file,
  24984. const std::string &client_private_key_file,
  24985. const char *private_key_password) {
  24986. std::string cert_pem, key_pem;
  24987. read_file(client_cert_file, cert_pem);
  24988. read_file(client_private_key_file, key_pem);
  24989. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24990. key_pem.c_str(), key_pem.size(),
  24991. private_key_password};
  24992. ConnectWithPem(pem);
  24993. }
  24994. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24995. ws::WebSocketClient client(url(), pem);
  24996. ASSERT_TRUE(client.is_valid());
  24997. client.enable_server_certificate_verification(false);
  24998. ASSERT_TRUE(client.connect());
  24999. ASSERT_TRUE(client.send("hello"));
  25000. std::string msg;
  25001. EXPECT_EQ(ws::Text, client.read(msg));
  25002. EXPECT_EQ("hello", msg);
  25003. client.close();
  25004. }
  25005. std::unique_ptr<SSLServer> server_;
  25006. std::thread server_thread_;
  25007. int port_ = 0;
  25008. };
  25009. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25010. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25011. }
  25012. // Control for the tests above: the fixture's server really does require a
  25013. // client certificate, so it is the PEM the constructor installed that decides
  25014. // the outcome.
  25015. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25016. ws::WebSocketClient client(url());
  25017. ASSERT_TRUE(client.is_valid());
  25018. client.enable_server_certificate_verification(false);
  25019. EXPECT_FALSE(client.connect());
  25020. }
  25021. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25022. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25023. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25024. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25025. }
  25026. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25027. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25028. std::string cert_pem, key_pem;
  25029. read_file(CLIENT_CERT_FILE, cert_pem);
  25030. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25031. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25032. std::vector<char> key(key_pem.begin(), key_pem.end());
  25033. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25034. key.size(), nullptr};
  25035. ConnectWithPem(pem);
  25036. }
  25037. #endif
  25038. #if !defined(_WIN32)
  25039. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25040. auto secret_dir = std::string("./symlink_test_secret");
  25041. auto served_dir = std::string("./symlink_test_served");
  25042. auto secret_file = secret_dir + "/secret.txt";
  25043. auto symlink_path = served_dir + "/escape";
  25044. // Setup: create directories and files
  25045. mkdir(secret_dir.c_str(), 0755);
  25046. mkdir(served_dir.c_str(), 0755);
  25047. {
  25048. std::ofstream ofs(secret_file);
  25049. ofs << "SECRET_DATA";
  25050. }
  25051. // Create symlink using absolute path so it resolves correctly
  25052. #ifdef PATH_MAX
  25053. char abs_secret[PATH_MAX];
  25054. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25055. #else
  25056. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25057. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25058. ASSERT_NE(nullptr, abs_secret);
  25059. #endif
  25060. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25061. auto se = detail::scope_exit([&] {
  25062. unlink(symlink_path.c_str());
  25063. unlink(secret_file.c_str());
  25064. rmdir(served_dir.c_str());
  25065. rmdir(secret_dir.c_str());
  25066. });
  25067. Server svr;
  25068. svr.set_mount_point("/", served_dir);
  25069. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25070. auto se2 = detail::scope_exit([&] {
  25071. svr.stop();
  25072. listen_thread.join();
  25073. });
  25074. svr.wait_until_ready();
  25075. Client cli("localhost", PORT);
  25076. // Symlink pointing outside base dir should be blocked
  25077. auto res = cli.Get("/escape/secret.txt");
  25078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25079. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25080. }
  25081. #endif
  25082. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25083. // "GET /smuggled" request), reads the first response, and only then sends the
  25084. // embedded request as the body. Returns how many times /smuggled ran.
  25085. //
  25086. // The body is sent AFTER receiving the first response (as in the original
  25087. // PoC) so that the stream_line_reader cannot buffer it together with the
  25088. // headers of the first request.
  25089. static int count_smuggled_requests(const std::string &outer_head,
  25090. std::string &first_response) {
  25091. Server svr;
  25092. svr.set_mount_point("/", "./www");
  25093. std::atomic<int> smuggled_count(0);
  25094. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25095. smuggled_count++;
  25096. res.set_content("oops", "text/plain");
  25097. });
  25098. svr.Post("/post", [&](const Request &req, Response &res) {
  25099. res.set_content(req.body, "text/plain");
  25100. });
  25101. auto port = svr.bind_to_any_port("localhost");
  25102. thread t = thread([&] { svr.listen_after_bind(); });
  25103. auto se = detail::scope_exit([&] {
  25104. svr.stop();
  25105. t.join();
  25106. });
  25107. svr.wait_until_ready();
  25108. auto error = Error::Success;
  25109. auto sock = detail::create_client_socket(
  25110. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25111. /*connection_timeout_sec=*/2, 0,
  25112. /*read_timeout_sec=*/2, 0,
  25113. /*write_timeout_sec=*/2, 0, std::string(), error);
  25114. EXPECT_NE(INVALID_SOCKET, sock);
  25115. if (sock == INVALID_SOCKET) { return -1; }
  25116. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25117. // The "smuggled" request will be sent as the body of the outer request
  25118. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25119. "Host: localhost\r\n"
  25120. "Connection: close\r\n"
  25121. "\r\n";
  25122. auto head = outer_head;
  25123. auto len = std::to_string(smuggled.size());
  25124. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25125. pos = head.find("{len}", pos + len.size())) {
  25126. head.replace(pos, 5, len);
  25127. }
  25128. // Step 1: Send only the outer request headers (no body yet)
  25129. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25130. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25131. // Step 2: Read the first response
  25132. char buf[4096];
  25133. for (;;) {
  25134. auto n = recv(sock, buf, sizeof(buf), 0);
  25135. if (n <= 0) break;
  25136. first_response.append(buf, static_cast<size_t>(n));
  25137. // Stop once we have a complete response (headers + body)
  25138. auto hdr_end = first_response.find("\r\n\r\n");
  25139. if (hdr_end != std::string::npos) {
  25140. // Check for Content-Length to know when the body is complete
  25141. auto cl_pos = first_response.find("Content-Length:");
  25142. if (cl_pos != std::string::npos) {
  25143. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25144. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25145. auto cl = std::stoul(
  25146. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25147. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25148. } else {
  25149. break; // No Content-Length, assume headers-only response
  25150. }
  25151. }
  25152. }
  25153. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25154. // vulnerable server the keep-alive loop reads this as a second request. The
  25155. // server may already have closed the connection, so the result is ignored.
  25156. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25157. // Half-close so that a server which drained the body sees EOF and closes,
  25158. // instead of the read below waiting for the read timeout.
  25159. #ifdef _WIN32
  25160. ::shutdown(sock, SD_SEND);
  25161. #else
  25162. ::shutdown(sock, SHUT_WR);
  25163. #endif
  25164. // Step 4: Read until the server closes the connection
  25165. for (;;) {
  25166. auto n = recv(sock, buf, sizeof(buf), 0);
  25167. if (n <= 0) break;
  25168. }
  25169. return smuggled_count.load();
  25170. }
  25171. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25172. // A GET request with Content-Length to a static file handler must have its
  25173. // body drained before the keep-alive connection is reused. Otherwise the
  25174. // unread body bytes are interpreted as the next HTTP request.
  25175. std::string first_response;
  25176. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25177. "Host: localhost\r\n"
  25178. "Content-Length: {len}\r\n"
  25179. "\r\n",
  25180. first_response));
  25181. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25182. }
  25183. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25184. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25185. // be answered with 400 and the connection closed. Treating it as "no body"
  25186. // leaves the body to be parsed as the next request.
  25187. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25188. const char *targets[] = {
  25189. "GET /file", // handler that never reads the body
  25190. "GET /not-found", // no handler matches (404)
  25191. "POST /post", // handler that reads the body
  25192. };
  25193. for (auto target : targets) {
  25194. for (auto value : values) {
  25195. std::string first_response;
  25196. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25197. " HTTP/1.1\r\n"
  25198. "Host: localhost\r\n"
  25199. "Content-Length: " +
  25200. value + "\r\n\r\n",
  25201. first_response))
  25202. << target << " with Content-Length: " << value;
  25203. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25204. << target << " with Content-Length: " << value;
  25205. }
  25206. }
  25207. }
  25208. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25209. // A 400 for an unparseable request line leaves the rest of the message
  25210. // unread, so the connection must be closed rather than reused.
  25211. std::string first_response;
  25212. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25213. "Host: localhost\r\n"
  25214. "Content-Length: {len}\r\n"
  25215. "\r\n",
  25216. first_response));
  25217. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25218. }
  25219. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25220. // Same as above for a header block that fails to parse.
  25221. std::string first_response;
  25222. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25223. "Host: localhost\r\n"
  25224. "Bad Header\r\n"
  25225. "Content-Length: {len}\r\n"
  25226. "\r\n",
  25227. first_response));
  25228. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25229. }
  25230. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25231. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25232. // server must not read another request on that connection, even when the
  25233. // request had no body to drain.
  25234. std::string first_response;
  25235. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25236. "Host: localhost\r\n"
  25237. "\r\n",
  25238. first_response));
  25239. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25240. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25241. }
  25242. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25243. // A content reader that stops early leaves the stream inside the body.
  25244. // Draining the whole Content-Length from there, or reading the body again,
  25245. // reads into the next request, and whatever follows is parsed as a request
  25246. // of its own.
  25247. Server svr;
  25248. std::atomic<int> smuggled_count(0);
  25249. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25250. svr.Post("/upload", [](const Request &req, Response &res,
  25251. const ContentReader &content_reader) {
  25252. // Stop at the last chunk, so the whole body has been read however it
  25253. // arrives.
  25254. auto length = req.get_header_value_u64("Content-Length");
  25255. size_t total = 0;
  25256. auto consumed = content_reader([&](const char *, size_t n) {
  25257. total += n;
  25258. return total < length;
  25259. });
  25260. EXPECT_FALSE(consumed);
  25261. if (req.has_param("retry")) {
  25262. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25263. }
  25264. // Replace the 400 the aborted read set, which would close the connection.
  25265. res.set_redirect("/done");
  25266. });
  25267. auto port = svr.bind_to_any_port(HOST);
  25268. thread t = thread([&] { svr.listen_after_bind(); });
  25269. auto se = detail::scope_exit([&] {
  25270. svr.stop();
  25271. t.join();
  25272. });
  25273. svr.wait_until_ready();
  25274. // A front end sees the second request as a POST whose body is the GET. The
  25275. // first body is as long as the POST's headers, so draining it again reads
  25276. // exactly those and leaves the GET to be parsed next.
  25277. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25278. "Host: localhost\r\n"
  25279. "\r\n";
  25280. std::string second_head = "POST /post HTTP/1.1\r\n"
  25281. "Host: localhost\r\n"
  25282. "Content-Length: " +
  25283. std::to_string(inner.size()) +
  25284. "\r\n"
  25285. "\r\n";
  25286. for (auto target : {"/upload", "/upload?retry"}) {
  25287. smuggled_count = 0;
  25288. std::string request = "POST " + std::string(target) +
  25289. " HTTP/1.1\r\n"
  25290. "Host: localhost\r\n"
  25291. "Content-Length: " +
  25292. std::to_string(second_head.size()) +
  25293. "\r\n"
  25294. "\r\n" +
  25295. std::string(second_head.size(), 'A') + second_head +
  25296. inner;
  25297. std::string response;
  25298. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25299. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25300. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25301. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25302. EXPECT_EQ(0, smuggled_count.load()) << target;
  25303. }
  25304. }
  25305. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25306. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25307. // must be rejected with 400 Bad Request.
  25308. Server svr;
  25309. svr.Post("/test", [&](const Request &, Response &res) {
  25310. res.set_content("ok", "text/plain");
  25311. });
  25312. thread t = thread([&] { svr.listen(HOST, PORT); });
  25313. auto se = detail::scope_exit([&] {
  25314. svr.stop();
  25315. t.join();
  25316. ASSERT_FALSE(svr.is_running());
  25317. });
  25318. svr.wait_until_ready();
  25319. // Exact "chunked"
  25320. {
  25321. auto req = "POST /test HTTP/1.1\r\n"
  25322. "Host: localhost\r\n"
  25323. "Content-Length: 5\r\n"
  25324. "Transfer-Encoding: chunked\r\n"
  25325. "Connection: close\r\n"
  25326. "\r\n"
  25327. "hello";
  25328. std::string response;
  25329. ASSERT_TRUE(send_request(1, req, &response));
  25330. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25331. response.substr(0, response.find("\r\n")));
  25332. }
  25333. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25334. {
  25335. auto req = "POST /test HTTP/1.1\r\n"
  25336. "Host: localhost\r\n"
  25337. "Content-Length: 5\r\n"
  25338. "Transfer-Encoding: gzip, chunked\r\n"
  25339. "Connection: close\r\n"
  25340. "\r\n"
  25341. "hello";
  25342. std::string response;
  25343. ASSERT_TRUE(send_request(1, req, &response));
  25344. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25345. response.substr(0, response.find("\r\n")));
  25346. }
  25347. }
  25348. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25349. Server svr;
  25350. svr.Post("/test", [&](const Request &, Response &res) {
  25351. res.set_content("ok", "text/plain");
  25352. });
  25353. thread t = thread([&] { svr.listen(HOST, PORT); });
  25354. auto se = detail::scope_exit([&] {
  25355. svr.stop();
  25356. t.join();
  25357. ASSERT_FALSE(svr.is_running());
  25358. });
  25359. svr.wait_until_ready();
  25360. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25361. // length cannot be determined, so the server must answer 400 and close
  25362. // rather than treat the request as bodyless and leave the body in the
  25363. // socket for the next request to pick up.
  25364. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25365. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25366. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25367. std::string response;
  25368. ASSERT_TRUE(send_request(1, req, &response));
  25369. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25370. response.substr(0, response.find("\r\n")))
  25371. << transfer_encoding;
  25372. }
  25373. // RFC 9110 5.3: the codings may also be split across several
  25374. // Transfer-Encoding lines, which combine in the order they were received.
  25375. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25376. // just like the single-line "chunked, gzip" above.
  25377. {
  25378. auto req = "POST /test HTTP/1.1\r\n"
  25379. "Host: localhost\r\n"
  25380. "Transfer-Encoding: chunked\r\n"
  25381. "Transfer-Encoding: gzip\r\n"
  25382. "\r\n"
  25383. "0\r\n\r\n";
  25384. std::string response;
  25385. ASSERT_TRUE(send_request(1, req, &response));
  25386. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25387. response.substr(0, response.find("\r\n")));
  25388. }
  25389. }
  25390. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25391. Server svr;
  25392. svr.Post("/test", [&](const Request &, Response &res) {
  25393. res.set_content("ok", "text/plain");
  25394. });
  25395. auto port = svr.bind_to_any_port(HOST);
  25396. ASSERT_GT(port, 0);
  25397. thread t = thread([&] { svr.listen_after_bind(); });
  25398. auto se = detail::scope_exit([&] {
  25399. svr.stop();
  25400. t.join();
  25401. ASSERT_FALSE(svr.is_running());
  25402. });
  25403. svr.wait_until_ready();
  25404. for (auto transfer_encoding :
  25405. {"Transfer-Encoding: gzip, chunked\r\n",
  25406. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25407. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25408. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25409. transfer_encoding + "\r\n0\r\n\r\n";
  25410. std::string response;
  25411. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25412. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25413. response.substr(0, response.find("\r\n")))
  25414. << transfer_encoding;
  25415. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25416. << transfer_encoding;
  25417. }
  25418. }
  25419. // Regression for issue #2450: a DELETE without Content-Length on a
  25420. // keep-alive connection must not let the post-response drain consume the
  25421. // next request's bytes.
  25422. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25423. Server svr;
  25424. std::atomic<int> delete_count(0);
  25425. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25426. delete_count++;
  25427. res.status = StatusCode::NoContent_204;
  25428. });
  25429. auto port = svr.bind_to_any_port(HOST);
  25430. thread t = thread([&] { svr.listen_after_bind(); });
  25431. auto se = detail::scope_exit([&] {
  25432. svr.stop();
  25433. t.join();
  25434. });
  25435. svr.wait_until_ready();
  25436. auto error = Error::Success;
  25437. auto sock = detail::create_client_socket(
  25438. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25439. /*connection_timeout_sec=*/2, 0,
  25440. /*read_timeout_sec=*/2, 0,
  25441. /*write_timeout_sec=*/2, 0, std::string(), error);
  25442. ASSERT_NE(INVALID_SOCKET, sock);
  25443. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25444. auto send_request_and_read_response = [&](const std::string &req,
  25445. std::string &out) -> bool {
  25446. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25447. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25448. char buf[4096];
  25449. for (;;) {
  25450. auto n = recv(sock, buf, sizeof(buf), 0);
  25451. if (n <= 0) { return !out.empty(); }
  25452. out.append(buf, static_cast<size_t>(n));
  25453. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25454. }
  25455. };
  25456. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25457. "Host: localhost\r\n"
  25458. "\r\n";
  25459. std::string resp1;
  25460. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25461. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25462. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25463. "Host: localhost\r\n"
  25464. "Connection: close\r\n"
  25465. "\r\n";
  25466. std::string resp2;
  25467. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25468. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25469. EXPECT_EQ(2, delete_count.load());
  25470. }
  25471. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25472. Server svr;
  25473. svr.Post("/ingest", [&](const Request &, Response &res,
  25474. const ContentReader &content_reader) {
  25475. auto consumed = content_reader([](const char *, size_t) { return false; });
  25476. EXPECT_FALSE(consumed);
  25477. res.status = StatusCode::Conflict_409;
  25478. res.set_header("Connection", "close");
  25479. });
  25480. auto port = svr.bind_to_any_port(HOST);
  25481. thread t = thread([&] { svr.listen_after_bind(); });
  25482. auto se = detail::scope_exit([&] {
  25483. svr.stop();
  25484. t.join();
  25485. });
  25486. svr.wait_until_ready();
  25487. auto error = Error::Success;
  25488. auto sock = detail::create_client_socket(
  25489. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25490. /*connection_timeout_sec=*/2, 0,
  25491. /*read_timeout_sec=*/1, 0,
  25492. /*write_timeout_sec=*/2, 0, std::string(), error);
  25493. ASSERT_NE(INVALID_SOCKET, sock);
  25494. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25495. std::string request = "POST /ingest HTTP/1.1\r\n"
  25496. "Host: localhost\r\n"
  25497. "Transfer-Encoding: chunked\r\n"
  25498. "\r\n"
  25499. "4\r\n"
  25500. "data\r\n";
  25501. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25502. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25503. std::string response;
  25504. ssize_t received = 0;
  25505. do {
  25506. char buf[4096];
  25507. received = recv(sock, buf, sizeof(buf), 0);
  25508. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25509. } while (received > 0);
  25510. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25511. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25512. EXPECT_EQ(0, received);
  25513. }
  25514. namespace no_proxy_test {
  25515. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25516. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25517. // calling listen().
  25518. class ScopedServer {
  25519. public:
  25520. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25521. ~ScopedServer() {
  25522. svr_.stop();
  25523. if (th_.joinable()) { th_.join(); }
  25524. }
  25525. Server &svr() { return svr_; }
  25526. int port() const { return port_; }
  25527. void listen() {
  25528. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25529. svr_.wait_until_ready();
  25530. }
  25531. private:
  25532. Server svr_;
  25533. std::thread th_;
  25534. int port_ = 0;
  25535. };
  25536. class ProxyAndTargetServers {
  25537. public:
  25538. ProxyAndTargetServers() {
  25539. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25540. proxy_hits_++;
  25541. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25542. res.set_content("via-proxy", "text/plain");
  25543. });
  25544. target_.Get(".*", [this](const Request &req, Response &res) {
  25545. target_hits_++;
  25546. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25547. res.set_content("direct", "text/plain");
  25548. });
  25549. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25550. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25551. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25552. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25553. proxy_mock_.wait_until_ready();
  25554. target_.wait_until_ready();
  25555. }
  25556. ~ProxyAndTargetServers() {
  25557. proxy_mock_.stop();
  25558. target_.stop();
  25559. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25560. if (target_thread_.joinable()) { target_thread_.join(); }
  25561. }
  25562. Server &proxy_mock() { return proxy_mock_; }
  25563. Server &target() { return target_; }
  25564. int proxy_port() const { return proxy_port_; }
  25565. int target_port() const { return target_port_; }
  25566. int proxy_hits() const { return proxy_hits_.load(); }
  25567. int target_hits() const { return target_hits_.load(); }
  25568. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25569. void reset_counters() {
  25570. proxy_hits_ = 0;
  25571. target_hits_ = 0;
  25572. last_had_proxy_authz_ = false;
  25573. }
  25574. private:
  25575. Server proxy_mock_;
  25576. Server target_;
  25577. std::thread proxy_thread_;
  25578. std::thread target_thread_;
  25579. int proxy_port_ = 0;
  25580. int target_port_ = 0;
  25581. std::atomic<int> proxy_hits_{0};
  25582. std::atomic<int> target_hits_{0};
  25583. std::atomic<bool> last_had_proxy_authz_{false};
  25584. };
  25585. inline std::unique_ptr<Client> make_client(const std::string &host,
  25586. ProxyAndTargetServers &s) {
  25587. auto cli = detail::make_unique<Client>(host, s.target_port());
  25588. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25589. cli->set_proxy("127.0.0.1", s.proxy_port());
  25590. return cli;
  25591. }
  25592. } // namespace no_proxy_test
  25593. using no_proxy_test::make_client;
  25594. using no_proxy_test::ProxyAndTargetServers;
  25595. // A stream request carries the credentials a buffered request does
  25596. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25597. no_proxy_test::ScopedServer origin;
  25598. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25599. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25600. });
  25601. origin.listen();
  25602. Client cli("127.0.0.1", origin.port());
  25603. cli.set_basic_auth("user", "pass");
  25604. auto handle = cli.open_stream("GET", "/x");
  25605. ASSERT_TRUE(handle.is_valid());
  25606. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25607. Client bearer("127.0.0.1", origin.port());
  25608. bearer.set_bearer_token_auth("tok");
  25609. auto handle2 = bearer.open_stream("GET", "/x");
  25610. ASSERT_TRUE(handle2.is_valid());
  25611. EXPECT_EQ("Bearer tok", read_all(handle2));
  25612. }
  25613. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25614. // takes its own credentials, as for a buffered request
  25615. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25616. std::string target, authz, proxy_authz;
  25617. no_proxy_test::ScopedServer proxy;
  25618. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25619. target = req.target;
  25620. authz = req.get_header_value("Authorization");
  25621. proxy_authz = req.get_header_value("Proxy-Authorization");
  25622. res.set_content("ok", "text/plain");
  25623. });
  25624. proxy.listen();
  25625. Client cli("origin.example", 8080);
  25626. cli.set_proxy("127.0.0.1", proxy.port());
  25627. cli.set_proxy_basic_auth("puser", "ppass");
  25628. cli.set_basic_auth("user", "pass");
  25629. auto handle = cli.open_stream("GET", "/x");
  25630. ASSERT_TRUE(handle.is_valid());
  25631. EXPECT_EQ("ok", read_all(handle));
  25632. EXPECT_EQ("http://origin.example:8080/x", target);
  25633. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25634. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25635. }
  25636. TEST(NoProxyTest, ExactHostnameBypasses) {
  25637. ProxyAndTargetServers s;
  25638. auto cli = make_client("example.com", s);
  25639. cli->set_no_proxy({"example.com"});
  25640. auto res = cli->Get("/");
  25641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25642. EXPECT_EQ(0, s.proxy_hits());
  25643. EXPECT_EQ(1, s.target_hits());
  25644. }
  25645. TEST(NoProxyTest, SubdomainBypasses) {
  25646. ProxyAndTargetServers s;
  25647. auto cli = make_client("foo.example.com", s);
  25648. cli->set_no_proxy({"example.com"});
  25649. auto res = cli->Get("/");
  25650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25651. EXPECT_EQ(0, s.proxy_hits());
  25652. EXPECT_EQ(1, s.target_hits());
  25653. }
  25654. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25655. // Regression guard: "evilexample.com" must not be considered a subdomain
  25656. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25657. // check would let traffic bypass the proxy and leak credentials direct
  25658. // to the attacker host.
  25659. ProxyAndTargetServers s;
  25660. auto cli = make_client("evilexample.com", s);
  25661. cli->set_no_proxy({"example.com"});
  25662. auto res = cli->Get("/");
  25663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25664. EXPECT_GE(s.proxy_hits(), 1);
  25665. EXPECT_EQ(0, s.target_hits());
  25666. }
  25667. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25668. ProxyAndTargetServers s;
  25669. auto cli = make_client("example.com.evil.com", s);
  25670. cli->set_no_proxy({"example.com"});
  25671. auto res = cli->Get("/");
  25672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25673. EXPECT_GE(s.proxy_hits(), 1);
  25674. EXPECT_EQ(0, s.target_hits());
  25675. }
  25676. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25677. ProxyAndTargetServers s;
  25678. auto cli = make_client("example.com", s);
  25679. cli->set_no_proxy({".example.com"});
  25680. auto res = cli->Get("/");
  25681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25682. EXPECT_EQ(0, s.proxy_hits());
  25683. EXPECT_EQ(1, s.target_hits());
  25684. }
  25685. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25686. ProxyAndTargetServers s;
  25687. auto cli = make_client("Example.COM", s);
  25688. cli->set_no_proxy({"EXAMPLE.com"});
  25689. auto res = cli->Get("/");
  25690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25691. EXPECT_EQ(0, s.proxy_hits());
  25692. EXPECT_EQ(1, s.target_hits());
  25693. }
  25694. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25695. ProxyAndTargetServers s;
  25696. auto cli = make_client("example.com.", s);
  25697. cli->set_no_proxy({"example.com"});
  25698. auto res = cli->Get("/");
  25699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25700. EXPECT_EQ(0, s.proxy_hits());
  25701. EXPECT_EQ(1, s.target_hits());
  25702. }
  25703. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25704. // Trailing dots must be normalized on BOTH sides — host and entry.
  25705. // An implementation that only strips the host-side trailing dot would
  25706. // fail to match host "example.com" against entry "example.com." because
  25707. // a literal substring search would compare 11 chars against 12.
  25708. ProxyAndTargetServers s;
  25709. auto cli = make_client("example.com", s);
  25710. cli->set_no_proxy({"example.com."});
  25711. auto res = cli->Get("/");
  25712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25713. EXPECT_EQ(0, s.proxy_hits());
  25714. EXPECT_EQ(1, s.target_hits());
  25715. }
  25716. TEST(NoProxyTest, WildcardBypassesEverything) {
  25717. ProxyAndTargetServers s;
  25718. auto cli = make_client("anything.invalid.test", s);
  25719. cli->set_no_proxy({"*"});
  25720. auto res = cli->Get("/");
  25721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25722. EXPECT_EQ(0, s.proxy_hits());
  25723. EXPECT_EQ(1, s.target_hits());
  25724. }
  25725. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25726. ProxyAndTargetServers s;
  25727. Client cli("127.0.0.1", s.target_port());
  25728. cli.set_proxy("127.0.0.1", s.proxy_port());
  25729. cli.set_no_proxy({"127.0.0.1"});
  25730. auto res = cli.Get("/");
  25731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25732. EXPECT_EQ(0, s.proxy_hits());
  25733. EXPECT_EQ(1, s.target_hits());
  25734. }
  25735. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25736. ProxyAndTargetServers s;
  25737. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25738. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25739. cli.set_proxy("127.0.0.1", s.proxy_port());
  25740. cli.set_no_proxy({"::1"});
  25741. auto res = cli.Get("/");
  25742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25743. EXPECT_EQ(0, s.proxy_hits());
  25744. EXPECT_EQ(1, s.target_hits());
  25745. }
  25746. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25747. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25748. // must still be recognized as IPv6 for CIDR matching. Implementations
  25749. // that detect IPv6 only when the host begins with '[' would parse the
  25750. // host as a hostname and miss the match.
  25751. ProxyAndTargetServers s;
  25752. Client cli("fe80::1", s.target_port());
  25753. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25754. cli.set_proxy("127.0.0.1", s.proxy_port());
  25755. cli.set_no_proxy({"fe80::/10"});
  25756. auto res = cli.Get("/");
  25757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25758. EXPECT_EQ(0, s.proxy_hits());
  25759. EXPECT_EQ(1, s.target_hits());
  25760. }
  25761. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25762. ProxyAndTargetServers s;
  25763. Client cli("::1", s.target_port());
  25764. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25765. cli.set_proxy("127.0.0.1", s.proxy_port());
  25766. cli.set_no_proxy({"[::1]"});
  25767. auto res = cli.Get("/");
  25768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25769. EXPECT_EQ(0, s.proxy_hits());
  25770. EXPECT_EQ(1, s.target_hits());
  25771. }
  25772. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25773. ProxyAndTargetServers s;
  25774. Client cli("fe80::1", s.target_port());
  25775. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25776. cli.set_proxy("127.0.0.1", s.proxy_port());
  25777. cli.set_no_proxy({"[fe80::]/10"});
  25778. auto res = cli.Get("/");
  25779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25780. EXPECT_EQ(0, s.proxy_hits());
  25781. EXPECT_EQ(1, s.target_hits());
  25782. }
  25783. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25784. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25785. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25786. // tricks via address-family conversion.
  25787. ProxyAndTargetServers s;
  25788. Client cli("::ffff:127.0.0.1", s.target_port());
  25789. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25790. cli.set_proxy("127.0.0.1", s.proxy_port());
  25791. cli.set_no_proxy({"127.0.0.1"});
  25792. auto res = cli.Get("/");
  25793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25794. EXPECT_GE(s.proxy_hits(), 1);
  25795. EXPECT_EQ(0, s.target_hits());
  25796. }
  25797. TEST(NoProxyTest, IPv4CidrMatch) {
  25798. ProxyAndTargetServers s;
  25799. Client cli("127.0.0.1", s.target_port());
  25800. cli.set_proxy("127.0.0.1", s.proxy_port());
  25801. cli.set_no_proxy({"127.0.0.0/8"});
  25802. auto res = cli.Get("/");
  25803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25804. EXPECT_EQ(0, s.proxy_hits());
  25805. EXPECT_EQ(1, s.target_hits());
  25806. }
  25807. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25808. ProxyAndTargetServers s;
  25809. Client cli("127.0.0.1", s.target_port());
  25810. cli.set_proxy("127.0.0.1", s.proxy_port());
  25811. cli.set_no_proxy({"10.0.0.0/8"});
  25812. auto res = cli.Get("/");
  25813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25814. EXPECT_GE(s.proxy_hits(), 1);
  25815. EXPECT_EQ(0, s.target_hits());
  25816. }
  25817. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25818. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25819. // IPv4 target matches.
  25820. ProxyAndTargetServers s;
  25821. Client cli("127.0.0.1", s.target_port());
  25822. cli.set_proxy("127.0.0.1", s.proxy_port());
  25823. cli.set_no_proxy({"0.0.0.0/0"});
  25824. auto res = cli.Get("/");
  25825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25826. EXPECT_EQ(0, s.proxy_hits());
  25827. EXPECT_EQ(1, s.target_hits());
  25828. }
  25829. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25830. ProxyAndTargetServers s;
  25831. Client cli("127.0.0.1", s.target_port());
  25832. cli.set_proxy("127.0.0.1", s.proxy_port());
  25833. cli.set_no_proxy({"127.0.0.1"});
  25834. auto res = cli.Get("/");
  25835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25836. EXPECT_EQ(0, s.proxy_hits());
  25837. EXPECT_EQ(1, s.target_hits());
  25838. }
  25839. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25840. ProxyAndTargetServers s;
  25841. Client cli("127.0.0.1", s.target_port());
  25842. cli.set_proxy("127.0.0.1", s.proxy_port());
  25843. cli.set_no_proxy({"127.0.0.0/33"});
  25844. auto res = cli.Get("/");
  25845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25846. EXPECT_GE(s.proxy_hits(), 1);
  25847. EXPECT_EQ(0, s.target_hits());
  25848. }
  25849. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25850. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25851. ProxyAndTargetServers s;
  25852. Client cli("127.0.0.1", s.target_port());
  25853. cli.set_proxy("127.0.0.1", s.proxy_port());
  25854. cli.set_no_proxy({"127.0.0.1/"});
  25855. auto res = cli.Get("/");
  25856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25857. EXPECT_GE(s.proxy_hits(), 1);
  25858. EXPECT_EQ(0, s.target_hits());
  25859. }
  25860. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25861. ProxyAndTargetServers s;
  25862. auto cli = make_client("internal.corp", s);
  25863. cli->set_proxy_basic_auth("u", "p");
  25864. cli->set_no_proxy({"internal.corp"});
  25865. auto res = cli->Get("/");
  25866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25867. EXPECT_EQ(1, s.target_hits());
  25868. EXPECT_EQ(0, s.proxy_hits());
  25869. EXPECT_FALSE(s.last_had_proxy_authz())
  25870. << "Proxy-Authorization must not be sent direct to the target";
  25871. }
  25872. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25873. ProxyAndTargetServers s;
  25874. auto cli = make_client("public.example", s);
  25875. cli->set_proxy_basic_auth("u", "p");
  25876. cli->set_no_proxy({"internal.corp"}); // does not match
  25877. auto res = cli->Get("/");
  25878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25879. EXPECT_GE(s.proxy_hits(), 1);
  25880. EXPECT_TRUE(s.last_had_proxy_authz());
  25881. }
  25882. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25883. std::atomic<int> hits{0};
  25884. std::atomic<int> hits_with_authz{0};
  25885. no_proxy_test::ScopedServer proxy_mock;
  25886. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25887. hits++;
  25888. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25889. if (req.target.find("/redir") != std::string::npos) {
  25890. res.set_redirect("http://other.example/landed");
  25891. } else {
  25892. res.set_content("via-proxy", "text/plain");
  25893. }
  25894. });
  25895. proxy_mock.listen();
  25896. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25897. hits = 0;
  25898. hits_with_authz = 0;
  25899. Client cli("public.example", 80);
  25900. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25901. cli.set_proxy_basic_auth(c.first, c.second);
  25902. cli.set_follow_location(true);
  25903. // The redirect to another host goes through the proxy as well
  25904. auto res = cli.Get("/redir");
  25905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25906. EXPECT_EQ(2, hits.load());
  25907. EXPECT_EQ(2, hits_with_authz.load());
  25908. }
  25909. }
  25910. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25911. ProxyAndTargetServers s;
  25912. auto cli = make_client("anything.test", s);
  25913. auto res = cli->Get("/");
  25914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25915. EXPECT_GE(s.proxy_hits(), 1);
  25916. EXPECT_EQ(0, s.target_hits());
  25917. }
  25918. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25919. ProxyAndTargetServers s;
  25920. auto cli = make_client("example.com", s);
  25921. cli->set_no_proxy({"example.com:8080"});
  25922. auto res = cli->Get("/");
  25923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25924. EXPECT_GE(s.proxy_hits(), 1);
  25925. EXPECT_EQ(0, s.target_hits());
  25926. }
  25927. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25928. ProxyAndTargetServers s;
  25929. auto cli = make_client("anything.test", s);
  25930. cli->set_no_proxy({"", " ", "\t"});
  25931. auto res = cli->Get("/");
  25932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25933. EXPECT_GE(s.proxy_hits(), 1);
  25934. EXPECT_EQ(0, s.target_hits());
  25935. }
  25936. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25937. // An entry with leading/trailing whitespace must still match — env-style
  25938. // values are commonly pasted with stray spaces and an implementation
  25939. // that feeds the raw token directly to inet_pton would fail to match
  25940. // valid CIDRs because of the spaces.
  25941. ProxyAndTargetServers s;
  25942. Client cli("127.0.0.1", s.target_port());
  25943. cli.set_proxy("127.0.0.1", s.proxy_port());
  25944. cli.set_no_proxy({" 127.0.0.0/8 "});
  25945. auto res = cli.Get("/");
  25946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25947. EXPECT_EQ(0, s.proxy_hits());
  25948. EXPECT_EQ(1, s.target_hits());
  25949. }
  25950. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25951. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25952. // go direct and must NOT carry Proxy-Authorization.
  25953. std::atomic<int> proxy_hits{0};
  25954. std::atomic<int> target_hits{0};
  25955. std::atomic<bool> target_saw_authz{false};
  25956. no_proxy_test::ScopedServer proxy_mock, target;
  25957. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25958. proxy_hits++;
  25959. res.status = 302;
  25960. res.set_header("Location", "http://127.0.0.1:" +
  25961. std::to_string(target.port()) + "/landed");
  25962. });
  25963. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25964. target_hits++;
  25965. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25966. res.set_content("direct", "text/plain");
  25967. });
  25968. proxy_mock.listen();
  25969. target.listen();
  25970. Client cli("public.example", target.port());
  25971. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25972. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25973. cli.set_proxy_basic_auth("u", "p");
  25974. cli.set_no_proxy({"127.0.0.1"});
  25975. cli.set_follow_location(true);
  25976. auto res = cli.Get("/redir");
  25977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25978. EXPECT_GE(proxy_hits.load(), 1);
  25979. EXPECT_GE(target_hits.load(), 1);
  25980. EXPECT_FALSE(target_saw_authz.load());
  25981. }
  25982. #ifdef CPPHTTPLIB_SSL_ENABLED
  25983. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25984. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25985. // proxy creds would be sent to the (possibly hostile) origin.
  25986. std::atomic<int> target_hits{0};
  25987. std::atomic<bool> target_saw_proxy_authz{false};
  25988. no_proxy_test::ScopedServer target;
  25989. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25990. target_hits++;
  25991. if (req.has_header("Proxy-Authorization")) {
  25992. target_saw_proxy_authz = true;
  25993. }
  25994. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25995. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25996. "nonce=\"abc\", algorithm=MD5");
  25997. });
  25998. target.listen();
  25999. // The proxy address is set to the target's port: the bypass MUST kick in;
  26000. // if it doesn't, the test still routes "via proxy" to the same server and
  26001. // the Proxy-Authorization assertion below catches the leak.
  26002. Client cli("evil.example", target.port());
  26003. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26004. cli.set_proxy("127.0.0.1", target.port());
  26005. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26006. cli.set_no_proxy({"evil.example"});
  26007. auto res = cli.Get("/x");
  26008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26009. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26010. EXPECT_EQ(1, target_hits.load());
  26011. EXPECT_FALSE(target_saw_proxy_authz.load());
  26012. }
  26013. #endif
  26014. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26015. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26016. std::atomic<int> proxy_hits{0};
  26017. std::atomic<int> bypass_hits{0};
  26018. std::atomic<bool> proxy_saw_c_url{false};
  26019. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26020. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26021. proxy_hits++;
  26022. if (req.path.find("/start") != std::string::npos) {
  26023. res.status = 302;
  26024. res.set_header("Location", "http://127.0.0.1:" +
  26025. std::to_string(bypass_server.port()) +
  26026. "/middle");
  26027. return;
  26028. }
  26029. if (req.path.find("/end") != std::string::npos) {
  26030. proxy_saw_c_url = true;
  26031. res.set_content("c-via-proxy", "text/plain");
  26032. return;
  26033. }
  26034. res.set_content("unexpected", "text/plain");
  26035. });
  26036. // public.example's "advertised" port is arbitrary (the request never lands
  26037. // there — it goes through the proxy), but use a dynamic value to stay
  26038. // friendly with sharded parallel runs.
  26039. int public_port = bypass_server.port();
  26040. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26041. bypass_hits++;
  26042. res.status = 302;
  26043. res.set_header("Location", "http://public.example:" +
  26044. std::to_string(public_port) + "/end");
  26045. });
  26046. proxy_mock.listen();
  26047. bypass_server.listen();
  26048. Client cli("public.example", public_port);
  26049. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26050. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26051. cli.set_no_proxy({"127.0.0.1"});
  26052. cli.set_follow_location(true);
  26053. auto res = cli.Get("/start");
  26054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26055. EXPECT_EQ(StatusCode::OK_200, res->status);
  26056. EXPECT_EQ("c-via-proxy", res->body);
  26057. EXPECT_GE(proxy_hits.load(), 2);
  26058. EXPECT_GE(bypass_hits.load(), 1);
  26059. EXPECT_TRUE(proxy_saw_c_url.load());
  26060. }
  26061. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26062. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26063. // request reconnects to the correct endpoint.
  26064. std::atomic<int> proxy_hits{0};
  26065. std::atomic<int> target_hits{0};
  26066. no_proxy_test::ScopedServer proxy_mock, target;
  26067. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26068. proxy_hits++;
  26069. res.set_content("via-proxy", "text/plain");
  26070. });
  26071. target.svr().Get(".*", [&](const Request &, Response &res) {
  26072. target_hits++;
  26073. res.set_content("direct", "text/plain");
  26074. });
  26075. proxy_mock.listen();
  26076. target.listen();
  26077. Client cli("public.example", target.port());
  26078. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26079. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26080. cli.set_keep_alive(true);
  26081. auto res1 = cli.Get("/a");
  26082. ASSERT_TRUE(res1);
  26083. EXPECT_EQ("via-proxy", res1->body);
  26084. EXPECT_EQ(1, proxy_hits.load());
  26085. EXPECT_EQ(0, target_hits.load());
  26086. cli.set_no_proxy({"public.example"});
  26087. auto res2 = cli.Get("/b");
  26088. ASSERT_TRUE(res2);
  26089. EXPECT_EQ("direct", res2->body);
  26090. EXPECT_EQ(1, proxy_hits.load());
  26091. EXPECT_EQ(1, target_hits.load());
  26092. }
  26093. // Forward declarations (see the base64_encode note).
  26094. namespace httplib {
  26095. namespace detail {
  26096. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26097. int shutdown_socket(socket_t sock) noexcept;
  26098. } // namespace detail
  26099. } // namespace httplib
  26100. namespace proxy_tunnel_test {
  26101. const char *const kTunnelEstablished =
  26102. "HTTP/1.1 200 Connection established\r\n\r\n";
  26103. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26104. using ConnectReply = std::function<std::string(const std::string &head)>;
  26105. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26106. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26107. class ScopedConnectProxy {
  26108. public:
  26109. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26110. : forward_port_(forward_port), reply_(std::move(reply)) {
  26111. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26112. if (listen_sock_ == INVALID_SOCKET) { return; }
  26113. auto a = loopback(0);
  26114. auto addr = reinterpret_cast<sockaddr *>(&a);
  26115. socklen_t alen = sizeof(a);
  26116. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26117. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26118. ::listen(listen_sock_, 4) != 0) {
  26119. return;
  26120. }
  26121. port_ = ntohs(a.sin_port);
  26122. th_ = std::thread([this] { run(); });
  26123. }
  26124. ~ScopedConnectProxy() {
  26125. if (th_.joinable()) {
  26126. stop_ = true;
  26127. auto wake = connect_to(port_);
  26128. th_.join();
  26129. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26130. }
  26131. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26132. }
  26133. int port() const { return port_; }
  26134. int connect_hits() const { return connect_hits_.load(); }
  26135. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26136. std::string connect_request() const {
  26137. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26138. return connect_request_;
  26139. }
  26140. private:
  26141. static sockaddr_in loopback(int port) {
  26142. sockaddr_in a{};
  26143. a.sin_family = AF_INET;
  26144. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26145. a.sin_port = htons(static_cast<unsigned short>(port));
  26146. return a;
  26147. }
  26148. static socket_t connect_to(int port) {
  26149. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26150. if (sock == INVALID_SOCKET) { return sock; }
  26151. auto a = loopback(port);
  26152. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26153. detail::close_socket(sock);
  26154. return INVALID_SOCKET;
  26155. }
  26156. return sock;
  26157. }
  26158. static bool send_all(socket_t sock, const char *data, size_t size) {
  26159. while (size > 0) {
  26160. auto n = detail::send_socket(sock, data, size, 0);
  26161. if (n <= 0) { return false; }
  26162. data += n;
  26163. size -= static_cast<size_t>(n);
  26164. }
  26165. return true;
  26166. }
  26167. void run() {
  26168. for (;;) {
  26169. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26170. if (stop_) {
  26171. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26172. return;
  26173. }
  26174. if (client == INVALID_SOCKET) { continue; }
  26175. serve(client);
  26176. detail::close_socket(client);
  26177. }
  26178. }
  26179. void serve(socket_t client) {
  26180. std::string head;
  26181. char buf[2048];
  26182. while (head.find("\r\n\r\n") == std::string::npos) {
  26183. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26184. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26185. if (n <= 0) { return; }
  26186. head.append(buf, static_cast<size_t>(n));
  26187. }
  26188. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26189. connect_hits_++;
  26190. {
  26191. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26192. connect_request_ = head;
  26193. }
  26194. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26195. if (!send_all(client, res.data(), res.size()) ||
  26196. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26197. return;
  26198. }
  26199. auto origin = connect_to(forward_port_);
  26200. if (origin == INVALID_SOCKET) { return; }
  26201. // When either side stops, shut both down so the other pump returns too.
  26202. auto pump = [&](socket_t from, socket_t to) {
  26203. char b[8192];
  26204. for (;;) {
  26205. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26206. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26207. }
  26208. detail::shutdown_socket(client);
  26209. detail::shutdown_socket(origin);
  26210. };
  26211. std::thread up([&] { pump(client, origin); });
  26212. pump(origin, client);
  26213. up.join();
  26214. detail::close_socket(origin);
  26215. }
  26216. int forward_port_;
  26217. ConnectReply reply_;
  26218. socket_t listen_sock_ = INVALID_SOCKET;
  26219. int port_ = 0;
  26220. std::thread th_;
  26221. std::atomic<bool> stop_{false};
  26222. std::atomic<int> connect_hits_{0};
  26223. mutable std::mutex connect_request_mutex_;
  26224. std::string connect_request_;
  26225. };
  26226. } // namespace proxy_tunnel_test
  26227. #ifdef CPPHTTPLIB_SSL_ENABLED
  26228. namespace proxy_tunnel_test {
  26229. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26230. class ScopedSSLServer {
  26231. public:
  26232. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26233. port_ = svr_.bind_to_any_port("127.0.0.1");
  26234. }
  26235. ~ScopedSSLServer() {
  26236. svr_.stop();
  26237. if (th_.joinable()) { th_.join(); }
  26238. }
  26239. SSLServer &svr() { return svr_; }
  26240. int port() const { return port_; }
  26241. void listen() {
  26242. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26243. svr_.wait_until_ready();
  26244. }
  26245. private:
  26246. SSLServer svr_;
  26247. std::thread th_;
  26248. int port_ = 0;
  26249. };
  26250. // Sends one request through the CONNECT proxy to the TLS origin with a
  26251. // credential configured for each hop, and checks that each credential reaches
  26252. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26253. // origin's (every header in origin_headers) on the tunnelled request.
  26254. void CredentialsStayWithTheirHop(
  26255. const std::function<void(SSLClient &)> &set_credentials,
  26256. const std::string &scheme,
  26257. const std::vector<std::string> &origin_headers = {"Authorization"},
  26258. bool stream = false) {
  26259. std::atomic<int> origin_hits{0};
  26260. std::atomic<bool> origin_saw_proxy_authz{false};
  26261. std::atomic<bool> origin_saw_headers{false};
  26262. ScopedSSLServer origin;
  26263. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26264. origin_hits++;
  26265. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26266. origin_saw_headers =
  26267. std::all_of(origin_headers.begin(), origin_headers.end(),
  26268. [&](const std::string &h) { return req.has_header(h); });
  26269. res.set_content("ok", "text/plain");
  26270. });
  26271. origin.listen();
  26272. ScopedConnectProxy proxy(origin.port());
  26273. ASSERT_NE(0, proxy.port());
  26274. // Pinned to 127.0.0.1 for the same reason as the test below.
  26275. SSLClient cli("127.0.0.1", origin.port());
  26276. cli.enable_server_certificate_verification(false);
  26277. cli.set_proxy("127.0.0.1", proxy.port());
  26278. set_credentials(cli);
  26279. if (stream) {
  26280. auto handle = cli.open_stream("GET", "/x");
  26281. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26282. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26283. } else {
  26284. auto res = cli.Get("/x");
  26285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26286. EXPECT_EQ(StatusCode::OK_200, res->status);
  26287. }
  26288. EXPECT_EQ(1, origin_hits.load());
  26289. EXPECT_EQ(1, proxy.connect_hits());
  26290. EXPECT_TRUE(origin_saw_headers.load());
  26291. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26292. << "Proxy-Authorization must not be sent inside the tunnel";
  26293. auto connect_req = proxy.connect_request();
  26294. EXPECT_NE(std::string::npos,
  26295. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26296. for (const auto &h : origin_headers) {
  26297. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26298. << h << " must not be sent to the proxy on CONNECT";
  26299. }
  26300. }
  26301. } // namespace proxy_tunnel_test
  26302. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26303. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26304. [](SSLClient &cli) {
  26305. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26306. cli.set_basic_auth("origin-user", "origin-pass");
  26307. },
  26308. "Basic");
  26309. }
  26310. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26311. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26312. [](SSLClient &cli) {
  26313. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26314. cli.set_basic_auth("origin-user", "origin-pass");
  26315. },
  26316. "Basic", {"Authorization"}, true);
  26317. }
  26318. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26319. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26320. [](SSLClient &cli) {
  26321. cli.set_proxy_bearer_token_auth("proxy-token");
  26322. cli.set_bearer_token_auth("origin-token");
  26323. },
  26324. "Bearer");
  26325. }
  26326. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26327. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26328. [](SSLClient &cli) {
  26329. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26330. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26331. {"Cookie", "sid=origin-session"},
  26332. {"X-Api-Key", "origin-key"}});
  26333. },
  26334. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26335. }
  26336. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26337. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26338. // retry; otherwise proxy creds would be sent to the origin.
  26339. std::atomic<int> origin_hits{0};
  26340. std::atomic<bool> origin_saw_proxy_authz{false};
  26341. proxy_tunnel_test::ScopedSSLServer origin;
  26342. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26343. origin_hits++;
  26344. if (req.has_header("Proxy-Authorization")) {
  26345. origin_saw_proxy_authz = true;
  26346. }
  26347. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26348. res.set_header("Proxy-Authenticate",
  26349. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26350. "algorithm=MD5");
  26351. });
  26352. origin.listen();
  26353. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26354. ASSERT_NE(0, proxy.port());
  26355. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26356. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26357. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26358. // and answer with its own status, making this test flaky.
  26359. SSLClient cli("127.0.0.1", origin.port());
  26360. cli.enable_server_certificate_verification(false);
  26361. cli.set_proxy("127.0.0.1", proxy.port());
  26362. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26363. auto res = cli.Get("/x");
  26364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26365. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26366. EXPECT_EQ(1, origin_hits.load());
  26367. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26368. EXPECT_EQ(1, proxy.connect_hits());
  26369. }
  26370. #endif
  26371. namespace proxy_tunnel_test {
  26372. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26373. // anything else gets a 407 with `challenge`.
  26374. ConnectReply require_proxy_auth(const std::string &expected,
  26375. const std::string &challenge) {
  26376. return [=](const std::string &head) -> std::string {
  26377. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26378. std::string::npos) {
  26379. return kTunnelEstablished;
  26380. }
  26381. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26382. "Proxy-Authenticate: " +
  26383. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26384. };
  26385. }
  26386. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26387. // request, then echoes.
  26388. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26389. ws.send(
  26390. "authorization:" + req.get_header_value("Authorization") +
  26391. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26392. std::string msg;
  26393. while (ws.read(msg)) {
  26394. ws.send(msg);
  26395. }
  26396. }
  26397. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26398. class ScopedWebSocketOrigin {
  26399. public:
  26400. ScopedWebSocketOrigin() {
  26401. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26402. server_.listen();
  26403. }
  26404. int port() const { return server_.port(); }
  26405. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26406. std::string url() const {
  26407. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26408. }
  26409. private:
  26410. no_proxy_test::ScopedServer server_;
  26411. };
  26412. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26413. // passed as a constructor header, and checks that each reaches only its hop.
  26414. void WebSocketCredentialsStayWithTheirHop(
  26415. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26416. const std::string &proxy_authz, const std::string &origin_authz) {
  26417. ScopedWebSocketOrigin origin;
  26418. ScopedConnectProxy proxy(
  26419. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26420. ASSERT_NE(0, proxy.port());
  26421. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26422. client.set_proxy("127.0.0.1", proxy.port());
  26423. set_proxy_credentials(client);
  26424. auto res = client.connect();
  26425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26426. std::string msg;
  26427. ASSERT_TRUE(client.read(msg));
  26428. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26429. client.close();
  26430. EXPECT_EQ(1, proxy.connect_hits());
  26431. EXPECT_EQ(std::string::npos,
  26432. proxy.connect_request().find("\r\nAuthorization: "))
  26433. << "origin credentials must not be sent to the proxy";
  26434. }
  26435. } // namespace proxy_tunnel_test
  26436. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26437. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26438. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26439. ASSERT_NE(0, proxy.port());
  26440. ws::WebSocketClient client(origin.url());
  26441. client.set_proxy("127.0.0.1", proxy.port());
  26442. auto res = client.connect();
  26443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26444. std::string msg;
  26445. ASSERT_TRUE(client.read(msg));
  26446. ASSERT_TRUE(client.send("hello"));
  26447. ASSERT_TRUE(client.read(msg));
  26448. EXPECT_EQ("hello", msg);
  26449. client.close();
  26450. EXPECT_EQ(1, proxy.connect_hits());
  26451. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26452. auto connect_req = proxy.connect_request();
  26453. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26454. EXPECT_NE(std::string::npos,
  26455. connect_req.find("\r\nHost: " + target + "\r\n"));
  26456. }
  26457. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26458. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26459. [](ws::WebSocketClient &cli) {
  26460. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26461. },
  26462. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26463. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26464. }
  26465. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26466. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26467. [](ws::WebSocketClient &cli) {
  26468. cli.set_proxy_bearer_token_auth("proxy-token");
  26469. },
  26470. "Bearer proxy-token", "Bearer origin-token");
  26471. }
  26472. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26473. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26474. proxy_tunnel_test::ScopedConnectProxy proxy(
  26475. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26476. "Basic " + detail::base64_encode("proxy-user:"),
  26477. "Basic realm=\"proxy\""));
  26478. ASSERT_NE(0, proxy.port());
  26479. ws::WebSocketClient client(origin.url());
  26480. client.set_proxy("127.0.0.1", proxy.port());
  26481. client.set_proxy_basic_auth("proxy-user", "");
  26482. auto res = client.connect();
  26483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26484. client.close();
  26485. EXPECT_EQ(1, proxy.connect_hits());
  26486. }
  26487. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26488. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26489. proxy_tunnel_test::ScopedConnectProxy proxy(
  26490. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26491. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26492. ASSERT_NE(0, proxy.port());
  26493. ws::WebSocketClient client(origin.url());
  26494. client.set_proxy("127.0.0.1", proxy.port());
  26495. auto res = client.connect();
  26496. EXPECT_FALSE(res);
  26497. EXPECT_EQ(Error::ProxyConnection, res.error());
  26498. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26499. EXPECT_EQ("Basic realm=\"proxy\"",
  26500. res.get_header_value("Proxy-Authenticate"));
  26501. EXPECT_FALSE(client.is_open());
  26502. }
  26503. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26504. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26505. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26506. ASSERT_NE(0, proxy.port());
  26507. ws::WebSocketClient client(origin.url());
  26508. client.set_proxy("127.0.0.1", proxy.port());
  26509. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26510. client.set_no_proxy({"127.0.0.1"});
  26511. auto res = client.connect();
  26512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26513. std::string msg;
  26514. ASSERT_TRUE(client.read(msg));
  26515. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26516. << "proxy credentials must not reach a bypassed origin";
  26517. client.close();
  26518. EXPECT_EQ(0, proxy.connect_hits());
  26519. }
  26520. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26521. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26522. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26523. ASSERT_NE(0, proxy.port());
  26524. ws::WebSocketClient client(origin.url());
  26525. client.set_proxy("127.0.0.1", proxy.port());
  26526. ASSERT_TRUE(client.connect());
  26527. ASSERT_TRUE(client.connect());
  26528. client.close();
  26529. EXPECT_EQ(2, proxy.connect_hits());
  26530. }
  26531. #ifdef CPPHTTPLIB_SSL_ENABLED
  26532. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26533. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26534. proxy_tunnel_test::ScopedConnectProxy proxy(
  26535. origin.port(), [](const std::string &head) -> std::string {
  26536. if (head.find(
  26537. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26538. std::string::npos) {
  26539. return proxy_tunnel_test::kTunnelEstablished;
  26540. }
  26541. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26542. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26543. "nonce=\"abc\", algorithm=MD5\r\n"
  26544. "Content-Length: 0\r\n\r\n";
  26545. });
  26546. ASSERT_NE(0, proxy.port());
  26547. ws::WebSocketClient client(origin.url());
  26548. client.set_proxy("127.0.0.1", proxy.port());
  26549. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26550. auto res = client.connect();
  26551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26552. std::string msg;
  26553. ASSERT_TRUE(client.read(msg));
  26554. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26555. client.close();
  26556. EXPECT_EQ(2, proxy.connect_hits());
  26557. }
  26558. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26559. proxy_tunnel_test::ScopedSSLServer origin;
  26560. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26561. origin.listen();
  26562. proxy_tunnel_test::ScopedConnectProxy proxy(
  26563. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26564. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26565. ASSERT_NE(0, proxy.port());
  26566. ws::WebSocketClient client(
  26567. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26568. client.enable_server_certificate_verification(false);
  26569. client.set_proxy("127.0.0.1", proxy.port());
  26570. client.set_proxy_bearer_token_auth("proxy-token");
  26571. auto res = client.connect();
  26572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26573. std::string msg;
  26574. ASSERT_TRUE(client.read(msg));
  26575. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26576. << "Proxy-Authorization must not be sent inside the tunnel";
  26577. client.close();
  26578. EXPECT_EQ(1, proxy.connect_hits());
  26579. }
  26580. #endif